Reading a text file into an array and performing a sort in Java

Question: I have a homework question I need help with
We have been given a text file containing one word per line, of a story.
We need to read this file into an array, perform a sort on the array and then perform a binary search.
The task also says I'll need to use an overload method, but I'm unsure where
I have a bubble sort, that I've tested on a small array of characters which works
public static void bubbleV1String(String[]numbers)
{
    for(int i = 0; i < numbers.length-1; i++)
    {
        for(int j = 0; j < numbers.length-1; j++)
        {
            if(numbers[j] .compareTo(numbers[j+1])>0)
            {
                String temp = numbers[j+1];
                numbers[j+1] = numbers[j];
                numbers[j] = temp;
            }
        }
    }
}`

And my binary search which I've tested on the same small array
    public static String binarySearch(int[] numbers, int wanted)
{
    ArrayUtilities.bucketSort(numbers);

    int left = 0;
    int right = numbers.length-1;

    while(left <= right)
    {
        int middle = (left+right)/2;

        if (numbers[middle] == wanted)
        {
            return (wanted + " was found at position " + middle);
        }

        else if(numbers[middle] > wanted)
        {
            right = middle - 1;
        }

        else
        {
            left = middle + 1;
        }

    }
    return wanted + " was not found";
}

Here is my code in an app class to read in a file and sort it
        String[] myArray = new String[100000];
    int index = 0;

    File text = new File("threebears.txt");

    try {
        Scanner scan = new Scanner(text);

        while(scan.hasNextLine() && index < 100000)
        {
            myArray[index] = scan.nextLine();
            index++;
        }
        scan.close();
    } catch (IOException e) {
        System.out.println("Problem with file");
        e.printStackTrace();
    }

    ArrayUtilities.bubbleV1String(myArray);
    try {
        FileWriter outFile = new FileWriter("sorted1.txt");
        PrintWriter out = new PrintWriter(outFile);

        for(String item : myArray)
        {
            out.println(item);

        }
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

When I go to run the code, I get a null pointer exception and the following message
 Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.compareTo(Unknown Source)
at parrayutilities.ArrayUtilities.bubbleV1String(ArrayUtilities.java:129)
at parrayutilities.binarySearchApp.main(binarySearchApp.java:32)

Line 129 refers to this line of code of my bubblesort
                if(numbers[j] .compareTo(numbers[j+1])>0)

And line 32 refers to the piece of code where I call the bubblesort
ArrayUtilities.bubbleV1String(myArray);

Does anyone know why I'm getting a null pointer exception when I've tested the bubblesort on a small string array? I'm thinking possibly something to do with the overloaded method mentioned earlier but I'm not sure
Thanks
Comment: `numbers[j]` most likely is `null`. You created an array with length 100000 but I doubt the file has that many lines. Thus instead of looping from 0 to `numbers.length - 1` you should loop from 0 to `index - 1`. It would be better to use a `List` in that case but I have the feeling that this is one thing your teacher is trying to hint at  (maybe at some later point in time).
Comment: An easier way to fix your code would be to create a [copy of `myArray`](https://stackoverflow.com/questions/5785745/make-copy-of-an-array) which has  the correct length, i.e. an array of length `index` - after reading the file. Then you replace `myArray` with that copy.
Comment: @Thomas
You answered my question, for the most part. I didn't realise the array needed to be created to the same number of lines that the text file contained.

I checked the number of lines and remember overhearing the teacher mention about the specific number of lines in class, although this wasn't put in the task sheet, so after a few days I had forgotten about what she had said

Once I corrected the array length the code ran fine

Thank you
Comment: If you'd like to add an answer, I can select it as the best answer and close the question
Comment: If allowed in your homework, you may use the java.nio.file API, which makes it easier reading files with the Files.readAllLines(Path) method. This returns a list. You may convert the list into an array using the streams API: myList.stream().toArray(String[]::new).
Comment: No problem, I'll add an answer. :)
Answer: It seems that you have some null values in your numbers array. Try to debug your code (or just print array's content) and verify what you have there. Hard to tell anything not knowing what is in your input file.
Answer: Method overloading is when multiple functions have the same name but different parameters.
e.g. (taken from wikipedia - function overloading)
// volume of a cube
int volume(const int s)
{
    return s*s*s;
}

// volume of a cylinder
double volume(const double r, const int h)
{
    return 3.1415926*r*r*static_cast<double>(h);
}

Regarding your null pointer exception, you've created an array of size 100000, but it's likely you haven't read in enough information to fill that size. Therefore some of the array is empty when you try to access it. There are multiple ways you can go about this, off the top of my head that includes array lists, dynamic arrays or even moving the contents of the array to another one, once you know the size of the contents (however this is inefficient).
Answer: You are creating an array of length 100000 and fill the lines as they are read. Initially all elements will be null and after reading the file quite a number of them is likely to still be null. Thus when you sort the array numbers[j] will eventually be a null element and thus calling compareTo(...) on that will throw a NullPointerException.
To fix that you need to know where in the array the non-null part ends. You are already tracking the number of read lines in index so after reading the file that would be the index of the first null element.
Now you basically have 2 options:

Pass index to bubbleV1String() and do for(int i = 0; i < index-1; i++) etc.
Make a copy of the array after reading the lines and before sorting it:

    String[] copy = new String[index];
    StringSystem.arrayCopy(myArray,0,copy,0,index);
    //optional but it can make the rest of the code easier to handle: replace myArray with copy
    myArray = copy;

Finally you could also use a List<String> which would be better than using arrays but I assume that's covered by a future lesson.


hibernate select data according to user input where user input is alongside few comma separated data

Question: LeaveType Table
<code>leave_name       emp_gender   employment_type       max_allowed_leave
Sick Leave       male,female  permanent,contractual    10
Maternity Leave  female       permanent                240
Annual Leave     male,female  permanent                15
Paternity Leave  male         permanent                30
</code>
I want to create a drop down list according to employment_type and gender.If Employee is female and permanent then value of the drop down would be Sick Leave,Maternity and Annual as well as only Sick Leave would be shown form employee who is a contractual male and female employee.How to do so in hibernate.N.B: data in emp_gender and  employment_type fields are separated using comma.
 I tried little like following:
<code>    Query query = session.createQuery("from LeaveTable where empGender = :empGender and employmentType =:employmentType ");
query.setParameter("empGender ", currentUser.getGender());
query.setParameter("employmentType ", currentUser.getemploymentType ());
List list = query.list();
</code>
For Female and permanent leave type will be: 1.Sick 2.Maternity 3.Annual.Need suggestions to fix the problem in hibernate.
Answer: You are not following database normalization. You need to segregate your data into multiple tables for efficient and reliable querying. For the above table you need to use 'LIKE' Operator else you would end up getting nothing.
Comment: I an not allowed to use normalization.I want to use comma separetor for empgender field in java.
Comment: Then you need use LIKE operator


Are customer surveys used in LeanUX

Question: Do current LeanUX methods advocate sending out surveys to understand potential customer segments?
Or should personas be written based on assumptions and then just user tested with customers that fit those segments?
(this relates to entirely new products where the customer is unknown but there may already be competitors/solutions in the market)
Answer: Not always, especially with self funded startups. They just don't have the resources/money/manpower to do so.
I've worked with numerous startups for developing their apps and most of them stray away from sending surveys to potential customers. Infact the reliable information for the design specs comes from company's own resources(people in sales, marketing managers, etc).
Exceptions, are VC funded startups, they really have a proclivity towards customer surveys.

About, "How to write personas?"

I am not Jeff Gothelf, and frankly I don't work with startups that provide huge resources to designers. The reality is that for most of the part personas are developed based upon the company's resources, with very little market research done. You will have to do the research all by yourself, you'll have to look into the resources and learn as much as you can from the available resources. As user research is time taking, it is negated because startups are always in a hurry to launch the optimized product as soon as possible.
Ideally, you make a persona from the available resources. And when you start testing your UX, you iterate your persona.
For example, if John's characteristic was "Smart, tech savvy and Fashionable", from testing you may find that John is "Smart, tech savvy but unfashionable". That being said, you are iterating on the user characteristics on the persona, and not on the "type of user". It is important that you get the target user right, otherwise testing in Lean UX would be very frustrating.
With this kind of testing you will understand user frustration, how they want to achieve their targets, etc and can iterate your persona with it.
Again, I would like to remind, persona based UX is the trait of startups (SMBs), majority  multi-national corporations are data driven with their decisions.
Answer: It depends on the kind of analytic data you are following for the current process. I do believe that, customer surveys will add more weightage to the ux process. Reason is pretty simple - LeanUX develops on cross-functional collaboration.
As far as concerned second part - personas are fictitious, they are based on knowledge of real users. Also , I do believe that, some form of user research is conducted before they are written to ensure they represent end users rather than the just your assumptions.
Comment: I've heard the term 'personas are fictitious' before. I guess this is why I find them fairly useless. If they are based on real users - why not distill what they do into a overall user type and include a few real users as an example? That's what I now tend to do.
Comment: The kind of project am on, based on that experience and depends on each projects personas are going to define. While we do not have access to real world users have to sketch based on knowledge of real users. As I mentioned earlier and being ux person have to do user research before getting involved in personas. If you do have real users to grab the facts about analytic data then personas are "factual" than "fictitious".
Comment: @StewartDean A proper persona ought to be the rolled up "average" user of a given segment. In a sense they are like an overall user type. But by naming it as a fictitious persona person, it allows the rest of the team and people in other departments to more easily identify with the user. Kind of like there's thousands of hungry kids in Africa, but it's way more salient to help one. The danger of using real users is that you may run into a problem that is specific to just that particular user. That's why personas, if used correctly, are more effective.
Comment: It depends on the audience for your persona. If you work in UX then 'averaged' personas are better than nothing but I would pick knowing the range of ages over being given an 'average' age. In terms of problems specific to one user, the danger with assumptive personas is that that persona might not actually exist. Also the real people are what should be used to create the persona - so why not just use the raw data rather than one level removed?
Comment: @StewartDean: "why not just use the raw data rather than one level removed?" Because numbers & trend lines are boring, abstract, potentially confusing, and impersonal. Beyond a certain # of data points your trends & conclusions no longer have a face. Personas help maintain empathy & a concrete connection to "real" users by making the same data more tangible & approachable. They help keep designers from losing the will to live during meetings, and help ensure you/your boss/your client truly understand your conclusions because they force you to first distill and explain the data.
Answer: The simple answer is yes. With Lean UX all tools are still available - but you really have to make sure it's taking things forward.
Recently I have been using one on one research sessions with recruited users. If you build these into the heartbeat of the project you can phase from user research to user testing as the project continues and do 2-3 sessions ever 2 weeks, keeping things as direct and lean as possible (easier said than done).
Personas, for example, can often be needless fluff (in my view) compared to understanding what the user does, why the do it and what they need whilst doing it. Assumption based personas can be dangerous as they amplify prejudice in a team. Good solid personas are useful, on the other hand. Things I like to know is what is the age range of my users, what kind of environments do they use what we're designing in and generally as much as possible to set the context of use.
One more thing - doing one to one sessions with your competitor sites is a great way to benchmark your competitors and give you a very good steer about where any new product could go.
Any user research will nearly always save time even if it takes time - and in Lean it's all about working about what is the most effective thing to do in the time given. No two projects will be the same.
Comment: In other words, iteration is expensive. At some point, you make a the best possible decision that moves you forward instead of holding up the process for another agile cycle. Lean basically codifies what a good UX designer should be able to do anyway - know when to compromise and use his/her intuition. I think, perhaps, it leans too far the other way at times but it that's all part of the art vs. the science.

Are customer surveys used in LeanUX


Responsive image inside bootstrap modal - not showing until I resize the window

Question: I'm using the TwentyTwenty jQuery library to allow me to have 2 images with a before and after slider, and I want to display these inside a Bootstrap modal.
However once I click on the thumbnail image to open the modal, the image doesn't display in the modal until I resize the browser (I can resize it by 1px and it'll display straight after).
I've tried using window.dispatchEvent(new Event('resize')); to the browser to calculate the height required for the image, but it isn't working. Is there some function in JavaScript (or jQuery) that force the browser to display the image?
The page is here:
http://turfectsolutions.chrisstclair.co.uk/Gallery/
Thanks! :)
Answer: late to the party but i figured out a fix for my set up (chrome - asp.net core razor page, Twenty Twenty, style:height = 0 but only shows when resize (not scroll))
I added a container to the markup - fixed a few but intermittently.
I read forums that stated Twenty Twenty only triggers on SHOWN divs, or Visibility: visible.
add an OnClick event to the button/anchor which triggers the modal.
<code> <button type="button" onClick="modalButtonClick()"
                        class="btn btn-info btn-lg"
                        data-toggle="modal"
                        data-target="#myModal">Bigger?</button>
</code>
the function will show the modal, and then you call the twenty twenty function to format the images. the alert is just there for test to make sure the function is being called.
<code>function modalButtonClick() {
            $("#myModal").show();
            $("#before_after_container1modal").twentytwenty();
            alert("I am an alert box!");
        }
</code>
I am sure there is a better way, but this seems to work - if any one has a better suggestion im all for learning :)


User login overwrites user fields

Question: I have a Django app which uses LDAP as the authentication backend.
I'm not sure whether it's the LDAP module or just Django itself but, if a user changes their email address, first name or last name and then logs out and back in again, the values revert to their original values (ie. the ones obtained from the LDAP record).
Has anyone seen this kind of behaviour before and is there any way to prevent it?
The problem I have is that the email addresses in the LDAP records are incorrect and need updating but I have no control over them. The only thing I can control is the Django user database.
Comment: You should be able to post an answer to this question yourself and accept it (you might have to wait a day or two)
Comment: And of course, as soon as I post the question, I find the answer.

For those that are interested, there is a setting in the LDAP module called AUTH_LDAP_ALWAYS_UPDATE_USER which you need to set to False to make sure it doesn't update every time.
Answer: For those that are interested, the solution was that there is a setting in the LDAP module called AUTH_LDAP_ALWAYS_UPDATE_USER which you need to set to False to make sure it doesn't update every time.

User login overwrites user fields


Prove that there does not exist a linear map

Question: I have to prove that there does not exist a linear map from $\mathbb{R}^5$ to $\mathbb{R}^2$ whose kernel is $\left\{\left(\begin{matrix} x_1 \\ x_2 \\ x_3 \\ x_4 \\ x_5 \end{matrix}\right) | x_1 = 3x_2 \space and \space x_3 = x_4 = x_5 \right\}$
but I do not know where to start
Comment: Hint:  What's are the possible dimensions for the kernel of a map from $\mathbb R^5\to \mathbb R^2$?
Comment: Any theorem connecting the dimensions of the kernel, range and domain?
Comment: I know dim(range(T)) + dim(ker(T)) = dim(v) and I know there are 5 dimensions in $ℝ^5$ and 2 in $ℝ^2$, but I do not know how to connect these ideas.
Answer: If $\phi:\mathbb{R}^{5}\rightarrow\mathbb{R}^{2}$ is any linear map, then the rank-nullity theorem tells you that
$$5=\dim(\text{Ker}(\phi))+\dim(\text{Im}(\phi)).$$
Since $\text{Im}(\phi)\subset\mathbb{R}^{2}$, its dimension is at most $2$, so that $\dim(\text{Ker}(\phi))\geq 3$. The subspace you are given is
$$\text{Span}\{(3,1,0,0,0),(0,0,1,1,1)\},$$
which is $2$-dimensional. So it cannot possibly be the kernel of a linear map $\phi:\mathbb{R}^{5}\rightarrow\mathbb{R}^{2}$.
Answer: Suppose there actually exists a linear map T. We know $ker(T)+rank(T)=5$ by rank-nullity theorem. Now $rank(T)\leq2$, so $ker(T) \geq 3$. Now what is the dimension of the kernel given? Is it greater or equal to 3? Do you see a contradiction?


Hide or display a chart while its updating

Question: I am working on a chart application and the user changes options many times to update the chart. Sometimes the updating may take few second.
(A)  Should I hide it to avoid any misunderstanding about data
(B)  Or is it better to keep the old one while updating (old information is better than no information)
Answer: (B), but only if you make it very clear that information is being updated.
A different colo(u)r scheme like in your example works well.
You might want to display 'updating...' close to/instead of your spinner.
Bonus points if your graph animates from the old state to the new! (while subtly hinting that updating succeeded.)
Answer: Whether you hide or display the old graph, neither method really helps the user visualise the change. Either way, you present the new graph abruptly leaving the user to work out what changed, if anything.
Ideally you should be indicating not that there is a change going on, but also what that change is relative to what was there before.
To help the user transition, you should make the data itself communicate the transition. That can be done in three steps:

Indicate the areas of change: Animate the graph from the old version to the new version. Users can see the fastest moving parts as the points of most change.
Retain what the change is relative to: Keep a copy of the old graph as a background, but faded, so that the user can see the relative difference between old and new.
On completion, lose the old data: Once the animation is complete and the new version is shown, transition a fade out of the old background graph so that it disappears leaving only the new graph.

Ideally, there would also be an undo/redo, where the transitioning works in reverse, and forward again, so the user can review if they wish.
I appreciate that's probably more work than you anticipated!
Comment: very interesting point. Unfortunately i have to deal with technical limits right now but I keep that in mind.
Answer: The second option, with a clear but not abrupt transition is better because it makes it obvious the change is happening, rather than forcing users to consciously think about what they've done and what the result of their changes will be.
One way to get the message across would be to animate your change, as seen in this example which uses the ZingChart JavaScript charting library: http://zingchart.com/playground/run/53ab17132f5d5
Another option would be to consider choosing a library that renders the charts quickly enough that the stage between updates is fairly imperceptible. This would basically eliminate the need for a blank screen or transition state.
Answer: I would be inclined to go with option B, as it would have a less jarring effect than A. The feedback needs to be obvious to the user that the chart is updating.
One thing you need to consider is how often is the chart being updated? If its frequently, they won't need the feedback to be as obvious as an occasional user updating it. Also if the user is intently changing data and expecting to see it reflected in the chart again the feedback can be more subtle.
Answer: I am assuming that the new chart is not related to the first one in terms of info value.
This reply really changes according to your scenario. It would be different for a linkedin viewers number in time than to have 3-4 financial data. Keeping the line on the screen would not matter much if you are changing the time span or (I dunno if LinkedIn actually has it but) field of work of your viewers, etc... However viewing 3-4 different kinds of financial data according to time, sub categories, sums and all would require a clean sheet to refresh the users's mind.
As a generic answer; I would suggest A because if you need to "compare" the old / new data, then you want to do a different kind of chart rendering like having both in hand. Seeing the new data emerging would probably get more attention to the new chart.
Answer: My short answer would be to use option B, as it is less abrupt and can possibly be animated to show the changing information.
There are also several other factors to consider:

How much comparison will the user be doing between the old and updated chart? If the behavior is change parameters --> update --> compare --> repeat, then showing some sort of transparent overlay of the older results may be the way to go. If this is not the case, then Option B with animation to show the change may be enough.
Is the chart updating based on parameters that the user can re-select, or is the updated chart something that cannot be reproduced, like a real-time stock chart?

Overall, I agree with @roger-attrill - but I think there are degrees of how far you need to go with representing the change based on the nature of the chart and what exactly is being updated.


Am I able to remap action groups after I've launched?

Question: Action groups have become useful for things like extending solar panels, ladders, as well as toggling engines.  I know how to set them up in the VAB, but I want to know if I can change action groups after I've launched.
Comment: Not currently I think...
Comment: I've started a bounty cause I have a ship in flight like, now, not 7 years ago, and in Kerbin years it means ages had passed and many things are in vanilla game or Breaking Ground, and mods all have changed.
Answer: Unfortunately, right now you can't.
It has happened a lot to me, launching and then realizing I didn't remember to set up the keys to something. If you have to do something synchronized, you can try to pause/unpause the game while mousing from one component to the other to minimize the desynchronization.
Answer: The best solution to this problem that I have been able to find was the tiny mod Actions on the Fly which allows you to edit the action groups in flight mode.
Answer: It's tricky and difficult, but doable. You'll need a good text editor (e.g. Notepad++) and to know your way around the game files, in particular saves and .craft files
Keep backups of everything at every step, because it's very easy to corrupt the save, or replace something else than you should have.
If you have the craft's template saved (as .craft file) half the work is done, skip the next step. If not, you'll need to create it.
If you don't have it saved, first, dig out the craft from your save file. src Create a new (dummy) craft and save it, then open your save file in a text editor, find your craft in flight (be it by craft name if unique, crew members names, or a unique part name, or orbital parameters), then copy it - the part after its ORBIT { } block - into the .craft file for the 'dummy', retaining the headers of the .craft file but replacing the craft structure.
Next (or first, if you had the .craft saved before launching it), load the .craft file into VAB, fix the action groups making them as you want, test if everything is alright, save it. Open the .craft file, then find the ACTIONS { } block. Open the save file, find your craft in flight again, and replace its ACTIONS { } with the fixed ones.
Comment: I thought this could be done in game now. I honestly haven't played in years, though, and this is just coming from a vague recollection from watching a YouTube video.
Comment: @MBraedley I got that feeling too, but when it came to it, I couldn't find it, and I have both expansions. If there is no in-game way or working lightweight mod, I'm going to use save edit method shown here.


Getting rid of java.util.Iterator

Question: My problem is related to Java.  I don't like the java.util package because of the optional methods.  For instance, I don't like it that, when I return a List, I have to prevent the user to modify the list; I would like to return a list that implements, say, interface UnmodifiableList (yes, I know about Collections.unmodifiableList(), but for many reasons, I don't like to encapsulate my list).  On the other hand, when I am given a list from an external piece of code, this list could be a1) unmodifiable, a2) modifiable with side-effects on the object that returned me the list, or a3) modifiable without side-effects, and b1) immutable (assuming the elements in the list are immutable as well) or b2) mutable and unsafe to use as a key.
I can rewrite most existing classes (just copy/paste the java.util package) and introduce interfaces UnmodifiableList, ModifiableList, etc. without much effort.  However, I have the following problem: I really like the forall mechanism
for (final Object o: listOfObjects) {
  // do something
}

which uses class java.lang.Iterable, which uses java.util.Iterator.
So my problem is, how should I cope with the Iterator class?
I have several possible solutions but I am looking for the most elegant.

Is it possible to make java use a different class than Iterable for the forall loops?
If not, is it possible to mark java.util.Iterator.remove() as deprecated?
Also, is it possible to customise my IDEs (eclipse and netbeans) so that they warn me every time I use Iterator?

My current plan is to define my own Iterator, as an extension of java.util.Iterator, and to mark the remove() method as deprecated.  Next, I will have some script looking at my code and making sure that java.util is used nowhere (except in the definition of my own Iterator).  That way, I should be safe.
Edit: Thanks for your advises and links, guys.  Cheers.
Comment: What's wrong with `Iterator` ??
Comment: The normal way to do that is to just let the optional operation `remove` throw an `UnsupportedOperationException`.

It comes with the downside that there is no compile-time check and the IDE shows a method that is not really meant to be called. Anyway, I would do it like this, since working against the common practice of a language or framework usually creates more pain than gain.
Comment: Related question [Why were Java collections implemented with "optional methods" in the interface](http://programmers.stackexchange.com/questions/77897/why-were-java-collections-implemented-with-optional-methods-in-the-interface).
Comment: With Eclipse (and NetBeans I suppose) there are many plugins that will yell a warn under   some  conditions. Take a look at CheckStyle plugin. (Question 3)
Comment: You might have a look at Guava, which already has ImmutableList, UnmodifiableIterator, etc.
Comment: @tantale, perhaps you are trying to solve a theorical problem which doens't need to be solved. What is the actual situation hyou have which you are trying to solve?
Answer: I will not go into the wisdom (or lack thereof) of replacing java.util.*, but as far as Iterable and Iterator go:

You cannot replace Iterable in foreach loops - it's practically hardcoded in the Java compiler.
The Java specification allows for throwing a perfectly fine UnsupportedOperationException when an optional operation is, well, unsupported. What is wrong with that? If your testsuite has proper coverage, you would know immediately, anyway. The abstract implementations of several Java interfaces (Abstract*) throw an exception for unsupported operations by default.
If your code is trying to remove objects from a Collection that does not support it, you probably have greater problems than deciding what to do with remove(). And if you are passing collections to third-party code, something will break if you violate the Java interfaces.
You could always override remove() with a method that does nothing to silence any errors... if you can take unexpected breakage in code that expects removed items to be removed.
Comment: It's hardcoded in the compiler. The JVM knows nothing of high-level constructs such as "for loops".
Answer: You may be interested in reading the official FAQ that explains some design choices made for java Collections : http://download.oracle.com/javase/1.4.2/docs/guide/collections/designfaq.html#1
There are quite good reasons for having optional operations. If you really want compiler support to manage the mutability of your types, your best bet is to use Scala and its Collection library. The type system of Scala is more suitable for checking such constraints.
Answer: If you want to return a list from a method, but do not want to let the user of the method change the list used in your code, you can always return a copy of the list:
return new ArrayList<?>(oldArrayList);

Rewriting the entire collection library is not likely to make you end up with a program that performs better and is easier to maintain compared to using the standard API.
Comment: *Rewriting the entire collection library is not likely to make you end up with a program that performs better:* Too true. As a matter of fact, due to field visibility issues, merely *moving* e.g. the HashMap implementation outside the java.util package results in slower code...

Getting rid of java.util.Iterator


Problem about Exponential Distribution

Question:
Suppose to have two meetings in a day. The first meeting is scheduled for $10.00$ a.m., the second one is scheduled for $11.00$ a.m. Let $X_1$ the duration of the first meeting and $X_2$ the duration of the second meeting. $X_1$ and $X_2$ are independent exponential random variables with $E[X_i]=60$(minutes), $i=1,2$.
(a) Determinate the probability of late arrival at the second meeting.
(b) The second meeting begins when the first one is finished. Determine the mean time of second meeting's late (the late is equal to zero if the first meeting'duration is less of $60$ minutes).

To resolve the point (a) I do in this way:
Let $Y=P($late arrival at the second meeting$)$.
$Z=P($get on time at the second meeting$)=P(X_1\leq60)=1-e^{-\lambda x}=1-e^{-1}$
$Y=1-Z=e^{-1}$
It's correct?
For the point (b) I don't know how I can do to resolve. So I hope somebody can help me. Thank you so much.
Comment: first one is correct! Question b however, I don't understand. Do you mean the probability that your meetings are in total more than 120 minutes?
Comment: Yes, I think it asks the mean time for more than 120 minutes.
Comment: mmm i think he is asking to find how much late the second meeting starts on average, knowing that it starts when the first one ends. If that's the case then you want to evaluate: $E(Y)=P(X_1 \le 60)\cdot 0 + \int_{60}^{\infty}(x-60)f(x)dx$ where $f(x)$ is the pdf. $Y $ is just the random variable of the time waiting, $Y=0, X \le 60 \; Y=X-60, X> 60 $.
Answer: Be more precise with your task at b, but when I did the right interpretation, at b you search for:
$\Bbb{E}[\Bbb{1}_{\{X_1 > 60\}} (X_1-60)] = \int\limits_{60}^\infty \lambda e^{-\lambda x}(x - 60)dx$
Here $X_1 \sim Exp(\lambda)$ and with your conditions it's easy to see that $\lambda = 60^{-1}$.

Problem about Exponential Distribution


A difference in a formula of theorem 4.2(e) on congruence relations.

Question: The statement of the theorem said :
If $a \equiv b \pmod n$ then $ac \equiv bc \pmod n$.
But I have seen it in other place as:
$a \equiv b \pmod n$ then $ac \equiv bc \pmod {nc}$.
Are they equivalent ? if so why?
Comment: They are not equivalent, but both hold. Actually, the second one implies the first.
Comment: how the second one implies the first one? @Berci
Answer: Well, they both hold.
By definition of modular congruence, $a\equiv b\pmod n$ means $n|b-a$, that is, $b-a=dn$ for some $d$.
But then $bc-ac=dnc$, showing $ac\equiv bc\pmod{nc}$.
Generally, if $x\equiv y\pmod{nc}$, we always have $x\equiv y\pmod n$, too, because the condition means $nc|y-x$ which implies $n|y-x$.


How to change color only for data grid or x and y axis in chart in D3.js

Question: I have created JSFiddle here -
I want make separate Data grid from the X and Y axis. Very light DataGrid and Dark X and Y axis
I tried but its always take stroke = Current Color in Path domain
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis);

Here is CSS
.axis line {
    stroke: red !important;
    opacity: 0.3;
}

.axis path {
    stroke: red !important;
    opacity: 0.3;
}

.axis text {
    fill: red !important;
}

    [![enter image description here][2]][2]

Answer: There are two ways you can approach this:
There is a d3 solution wich basically needs no css
svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .call(g => g.selectAll(".tick:first-of-type line")
                .attr("class", "axis_bar")
                .attr("stroke", "black"))
    .call(g => g.selectAll(".tick:not(:first-of-type) line")
                .attr("class", "axis_y_tick")
                .attr("stroke", "red"));

svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis)
    .call(g => g.selectAll(".tick:first-of-type line")
                .attr("class", "axis_bar")
                .attr("stroke", "black"))
    .call(g => g.selectAll(".tick:not(:first-of-type) line")
                .attr("class", "axis_y_tick")
                .attr("stroke", "red"));

svg.append("path") // Add the valueline path.
    .attr("d", valueline(data))
    .attr("class", "graph")
    .attr("stroke", "blue")
    .attr("stroke-width", 2);

This selects the first and every following line and applies different style parameters.
The second solution would be to do it only in css. You may see the class-selectors you need already in the d3 snippet:
.tick:first-of-type line {} //Selects the first Tick/Line wich becomes the main axis.

.tick:not(:first-of-type) line {} // Will select every other tick line, but the first.

I edited your fiddle fit the d3 solution: http://jsfiddle.net/nk13jycw/2/
There is also a nice observable by Mike Bostock on this: https://observablehq.com/@d3/styled-axes
Comment: This really helps!!!! Thanks a lot @D.icon.. I really appreciate for answers
Answer: d3 adds the class tick to the all of the groups containing grid lines (called tick because they can also be used as tick marks).
You can do something like this in CSS to only select them:
.axis .tick line {
  fill: none;
  stroke: black;
  opacity: 0.1;
}

Updated fiddle: http://jsfiddle.net/w7jrxnk5/
Comment: This helps but following above answers.. Thanks @Steve


Where is the guard that drops the "Bearer of sorrows"?

Question: According to the PAthfinder:Wrath wiki, the Bearer of Sorrows drops from "Senior guard in the Fleshmarket in act 4".

But in the Fleshmarket there is no "Senior guard" - there are slave traders, two regular guards, a pirate and various traders that you can attack via dialog option. But no "senior guard".
Answer: On my second playthrough, I've managed to get this weapon, but it seems that the "senior guard" only spawns when you start a big fight in the Fleshmarket:
I've attacked first Raggy, Black Mask and Dyunk the Slave trader, but the guards did not interfere. But when I've attacked Sarzaksys (the owner of the Fleshmarket), every NPC around became hostile (so it is wise to get rid of the other traders first), with exception of the Venture-Captain Gristoff, who can help you if you donate 50k gold to the Pathfinder society.
Since the whole fight is quite chaotic, I can only vaguely pinpoint the location of the Senior Guard, as spawning somewhere between Raggy's shop and the shadow-slaver selling possessed slaves (I think that his name is Kerz).
It is worth noting that my fight was part of the "Where is my dragon?" quest for the Azata path, which gives you a huge bonuses when fighting in the Fleshmarket.


How to connect sqlite with mysql database using ionic framework?

Question: now I'm working on hybrid mobile application with SQLite. This application just only retrieve the data from database. The data come from MYSQL database, but I want to store the data into local storage which is SQLite so when the user don't have the internet, they can retrieve the data from local storage. So,is there a way to connect mysql db and sqlite? I have been following the tutorial from this site
but I do not know how to connect sqlite with mysql db. So,anyone can help me to solve my problem ?
Answer: You can connect using a API that give a response as a JSON and store and access those using ionic local storage
Or you can design a server side code using node js and connect to db


How to install a door in a load bearing basement wall that is only 80 inches high

Question: I would like to install a door in a load baring wall in my basement that is only 80 inches from the floor to the joist.
It's an old 1940s home where half the house has joists running east west and half running north south. The two joists come together just past the load baring wall.
I want to know what my best options are to install a door between the existing studs and only removing one stud. Goal is it to have the doorway to be as high as possible.
Please see attached pictures for clarification.
enter image description here.
Comment: What is directly over the area where you want the door on the floor above?
Comment: Edited the answer to the final version
Comment: You want to put a door where those plaster walls are?
Answer: You will need a new rough opening that will measure 76 1/2" X 26 1/2", give or take 1/4" This is assuming there is nothing on the floor above like pianos, bookcases, and such. This also assuming that there is nothing required above in the way of a point load that happens to be right at the location of the new header.
To add the header, cut out the 2 top plates at the sides of the studs you want to keep for the beginning of the rough opening. You can temporally support the one joist in the middle if you choose, IF there is no load on the floor in that area. If there is a load, then this whole idea needs to be rethought. Using 4X4 solid wood cut to the length between the 2 cuts where the plates were. Set it in place, keeping it in place with a few toenails. It needs to move a little. Make sure it is tight to the center joist and pretty level. After that is confirmed, measure the jack stud lengths that will hold the header. Add 1/8" to that number. By the way if there is tile on the floor above, this may or will crack it. The first piece you cut will go in readily. DO NOT nail it, Cut the other, this one will need to be driven in. Set the top in place and drive the bottom in. If it gets really tough to drive in and the bottom is still 4 " away from the stud, remove it and cut it 1/16" shorter. It should drive in all the way this time. While driving things will shift around and settle in. Drive everything back in line and nail everything off. Some folks may say put truss plates at the meeting place where the header and plates meet, but the subfloor above will not let anything spread, and the new jack studs will not let anything drop. So I would not sweat the plates. Now cut out the bottom plate. set your door
The doors you need can be ordered cut to 74" instead of 80". This door will be a 24" wide door. It is a special order but it will be done right by the maker of the door. If you must do it yourself, you will need to cut the bottom 2" off the door, and with a table saw, CAREFULLY skin the finish layer off the bottom filler, clear the webbing out of the bottom if it is a hollow core door and cover all meeting surfaces in glue. It will be messy. Insert the filler. Clean most of the glue mess with a damp sponge and water. Use 2 strips of wood the width of the door and clamp them on with wax paper between the wood and the door to keep the glue from bonding the wood to the face of the door. Let it dry for a day, trim off the excess glue and clean up the cuts and prime. Cut the bottoms of the jambs and set your door(s).
The downside of this is the knob will be 6" lower. The bottom hinge will be at the floor as well. This is why the door should be custom ordered.
Of course you could cut the top off and the bottom, and rework everything, but that is up to you.
FREE TIP OF THE DAY!!!!
If you are planning to salvage the plaster wall, your best chance to do so is screw a strip of 1X over the stud that the cut will be at, top to bottom. Screw it (not nailed, vibrations destroy plaster) about every foot, closer is better, not farther. Do this on both sides. This will keep the wood lath from flying off when the cutting starts for the opening. This is after the new jack studs are in place and secured.
Comment: You might could cut it all off the top, and reset the hinge....
Answer: Get your asbestos remediated the tape on your hvac boots is almost 100% asbestos.
Assuming the room that is receiving the door also has the ceiling open.  The best trade off thing to do here is to eliminate a portion of one joist.
Easiest method.  Support joist with portion to be removed via temporary pony wall.  Cut portion of joist directly above wall inline with bearing wall.  Build a header and insert header into removed thickness of joist directly above bearing wall.  Hang joist on both sides of header.  Add studs to support header.
Now that the loads are dealt with install your door without a header.
Comment: Is this just a comment or is there an answer in there. That is a rhetorical question because i can see that this is **not an answer** but is a comment with a question.


What is The Eldritch Truth?

Question: Spoilers Ahead...
Numerous times in Bloodborne, there is mention of different people encountering 'the eldritch truth,' including the Byrgenwerth scholars, the Pthrmarians, and even an anonymously mentioned doctor and his sister. Some are glad to encounter it, and nearly all who encounter it have gone mad to some degree. But what could it be? It seems to be connected to the Kin, but I don't know for certain. Is it the simple knowledge of the Great Ones? Was it the finding/killing of Mother Kos at the Fishing Hamlet years ago, and had those fishermen been blessed by it? Or is it something more (or less)?
What is the eldritch truth?
Answer: I got this about halfway down the Bloodborne Wikia:
The idea of the Eldritch truth is spread throughout the game as people from Master Willem, to even the choir (a group of people), have tried to achieve an evolution toward a higher state of being by learning the Eldritch truth. The truth it is not expressed by simply a sentence or a phrase, rather it is a state of being in existence. The great ones understood this either through naturally knowing the eldritch truth, having been humans or beings which gained enough insight to evolve, or an otherwise unknown method to understand the true state of reality. Later as you, the player, by killing Rom made the true reality of the world shown (for an arbitrary reason his* [sic] death either as part of a ritual or by being the thing holding back people from seeing reality. (This needs to be confirmed or greatly defined)) or by gaining 40 insight you saw the reality of the world as it truly was, and achieved what those before you sought to do but failed. They failed by using other methods like lining your brain with eyes, using the Mensis cage, or accepting a great ones power many of which failed to achieve true enlightenment as a side effect resulted in madness, deformation/transformation into a monstrosity, or death for the user with their corresponding method.

However you, as the player, achieved this by gathering insight throughout the world and absorbing it into your itself. Following this, utilizing the action of using the item in game you crush the skull in your hand releasing this partial knowledge into the world which channels into you for some reason either because of proximity or another variable. Other ways such as fighting nightmarish enemies which provoke your mind into perceiving them, which forces you to gain insight so you can fight them it is also a safe method of gaining insight. This way you don't get side effects (as far as I know if you find any then add them).
This makes you able to perceive the great ones fully, and able to see the world as it truly is plus interacting with the real reality; such as being able to enter and face enemies in the Yahar'gul Unseen Village under the blood moon which was previously not fully available. The difference in the area as far as how deep you can go into it between the variety of enemies is shown in a comparison of the area and when you are captured by the Snatchers and taken to Hypogean Gaol as well as after you visit the area and have killed Rom. The player thus gain's true enlightenment or simply understand the eldritch truth. As well on a final note, you are probably wondering how blood ministration fits into this explanation well in the Bloodborne universe blood is used as a cure/healing or a way of making a individual stronger. Therefore, in a sense it is moving towards this same goal although from a different direction. It ultimately never leads to the Eldritch Truth as the humans wanted (ideally they got to be elevated, understand more with a clear mind, and be in control of themselves), just a monstrous transformation but considering many of these enemies end up in the true reality you could say they reached the physical state of enlightenment but their minds are completely gone in most cases and they just attack anything they can. So they got what the wanted they just can't enjoy it.
*Canonically, Rom the Vacuous Spider is female.
Comment: So what you're saying is that **The Eldritch Truth is the ability of a mind to perceive all planes of reality at once _(meaning that the Great Ones can somehow chose which plane they exist on at a time)_**? And that the reason that new enemies appear in Yahar'gul (and other places) is that you have broken the metaphysical barrier preventing you from interacting with those realities (done by killing Rom, who seems to have become linked to that barrier)?
Comment: Upon some further investigating in Yahar'gul after killing Rom (which tells you that the ritual secret is broken) I pieced together certain notes and I theorized this: The School of Mensis, which established Yahar'gul (meaning Unseen Village) to remain unnoticed, was attempting to use blood in a ritual to break the barrier of The Eldritch Truth (which Rom preserved) by initiating a 'paleblood' moon in this plane (Mensis may be derived from a word meaning moon). Failed attempts to work around this barrier, involving kidnapping people, may have caused the beasts. Am I in the ballpark on this?
Comment: I Geuss you could say it like that

What is The Eldritch Truth?


Can't turn git source control provider off for solution

Question: Title says it all.  I know how to turn it off and I've done so for every version of VS that has had it.  My experience has always been that it makes VS chug, I don't like all the visual clutter (and it's even worse in VS 2015 with the function annotations!), and in general I much prefer using git bash when I'm ready to start doing git type things.
The issue is that now when I change the Source Control provider to 'None' it prompts and tells me the solution is using a different provider than the one selected and continuing will close the solution.  If you hit yes and reopen the solution the git provider is still enabled for that solution.
I really really want this turned off.  I'll go back to VS 2013 if I can't find a solution to this, it's that much of a showstopper for me.
Does anyone have any ideas about how to actually turn it off?
Answer: I use the NoGit Visual Studio Extension.
https://visualstudiogallery.msdn.microsoft.com/146b404a-3c91-46ff-932a-fb0f8b826f94


Query simplification by using oracle sample database

Question: Task :
List Name and salary of highest and lowest paid employee from each department.
You can perform the queries for highest and lowest separately also.
Tried Query :
SELECT dept.deptno,
       dname,
       minsal,
       maxsal
FROM   dept,
       (SELECT deptno,
               Max (sal) MAXSAL
        FROM   emp
        GROUP  BY deptno) MAXSALARY,
       (SELECT deptno,
               Min (sal)MINSAL
        FROM   emp
        GROUP  BY deptno) MINSALARY
WHERE  MAXSALARY.deptno = dept.deptno
       AND MINSALARY.deptno = dept.deptno;

Result

The Result is correct.
Question)
 Is there any other way to simplify the query?
Answer: You can use ORACLE's window functions like row_number combined with conditional aggregation using CASE EXPRESSION :
SELECT t.ename,t.dname,
       MAX(CASE WHEN t.low_ind = 1 then t.salary END),
       MAX(CASE WHEN t.high_ind = 1 then t.salary END)
FROM (SELECT e.name as ename,d.name as dname,e.salary,
             ROW_NUMBER() OVER(PARTITION BY d.name ORDER BY e.salary ASC) as low_ind,
             ROW_NUMBER() OVER(PARTITION BY d.name ORDER BY e.salary DESC) as high_ind
      FROM emp e
      INNER JOIN dept d
       ON(d.deptno = e.deptno)) t
GROUP BY t.ename,t.dname

EDIT: if all you need is the min and max salary on each department then thats a simple group by clause :
SELECT d.deptno,d.dname,MIN(e.salary) as min_sal,MAX(e.salary) as max_sal
FROM dept d
INNER JOIN emp e
 ON(d.deptno = e.deptno)
GROUP BY d.deptno,d.name

Comment: I am a beginner in sql . So can we simplify it by using simple sub-quries ? @sagi
Comment: @nafeesahmed are you required to bring back employee name? or you just need to output -> `DEPname,maxSal,minSal` ?
Comment: i NEED JUST DEPname,maxSal,minSal
Answer: SELECT d.dname, Max(e.sal) MAXSAL, Min(e.sal) MINSAL
  FROM dept d, emp e
 WHERE d.deptno = e.deptno
 group by d.dname


What are the hardware differences between the Xbox 360 slim and the Xbox 360 E?

Question: What are the hardware differences between the Xbox 360 slim and the Xbox 360 E?
Are there any significant improvements or benefits of the Xbox 360 E that one should consider?
Answer: The 360S(lim) and 360E are fairly similar, with some slight differences:

The S has 5 USB ports, where the E has 4.
The S was the last model to feature the "AV Connector".  The E drops this port in favor of a separate HDMI port and composite (ugh) out port.  Optical audio appears to be missing.
The case design has been updated to match the design of the Xbox One.
The hard drive is slightly easier to remove, although it is still only replaceable with official Microsoft replacements.

Notable elements kept constant:

Price & configurations.  The E was introduced at the same price as the S.
Fans & optical drive design.  This means the E likely has the same noise profile as the S.
Architecture.  It's the same chips, same amount of flash, RAM, etc.  Halo won't run any faster on it ;)
Answer: I just want to add insight into why the E might be cooler.
I don't have an S but about it feeling like a better build and the E having a thinner case, well that would in fact make huge differences in heat transfer. The better build probably insulates more than than the other. The reason this wouldn't make any difference on the noise levels would be because the fans are mounted right on the other side of a plastic grill. Both models use the same case fans now if the E was a cheaper build AND stayed cooler they should've invested in a couple pennies for a quieter fan.
That could've taken way too much away from the S though, who knows...
Answer: Other than the above, the Xbox 360 E is meant to be cooler (temperature) and quieter, though no-one can notice the difference.
Answer: I have the Slim and the E. They both make the same noise when running. The Slim feels like a better build. The E is a good looker, but has a cheap thin case. Other than that, they both work the same with any game. So, if you have a Slim and it's OK, keep it.


Best practice for changing TextBox Border color?

Question: Suppose you have a View with multiple Texboxes like this
<TextBox Text="{Binding myText1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

each already containing some text. If the user changes this text the Textbox Border should change to Orange and if he undos his changes it should get it's default color.
At the moment I do it like this
<TextBox Height="23"  Text="{Binding myText1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" BorderThickness="2">
   <TextBox.Style>

        </Style>
    </TextBox.Style>
</TextBox>

Is there a more generic / simpler way to do this?
Edit
I am already using IDataErrorInfo + System.ComponentModel.DataAnnotations for Error validation. Maybe there is a similar way in this case but I didn't found anything useful to reduce my xaml and code to an minimum.
EDIT 2.0
i think you doesn't really understand my problem so i will provide a better sample of how it actual looks like:
View Xaml (no codebehind)
<Grid Margin="12">

    <TextBox Height="23" HorizontalAlignment="Left" Margin="102,2,0,0" VerticalAlignment="Top" Width="170" BorderThickness="2"
             Text="{Binding NameD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
        <TextBox.Style>

            </Style>
        </TextBox.Style>
    </TextBox>

    <TextBox BorderThickness="2" Height="23" HorizontalAlignment="Left" Margin="102,36,0,0" VerticalAlignment="Top" Width="170"
             Text="{Binding AnzeigetextD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
        <TextBox.Style>

            </Style>
        </TextBox.Style>
    </TextBox>

    <TextBox BorderThickness="2" Height="23" HorizontalAlignment="Left" Margin="102,70,0,0" VerticalAlignment="Top" Width="170"
             Text="{Binding PreisD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, StringFormat=\{0:c\}}">
        <TextBox.Style>

            </Style>
        </TextBox.Style>
    </TextBox>

    <Button Content="Speichern" Height="23" HorizontalAlignment="Left" Margin="102,110,0,0" VerticalAlignment="Top" Width="75" Command="{Binding SaveCommand}"/>
    <Button Content="Abbrechen" Height="23" HorizontalAlignment="Left" Margin="197,110,0,0" VerticalAlignment="Top" Width="75" Command="{Binding CancelCommand}"/>
</Grid>

ViewModel
public class MenuangebotVM : DetailVM, IContains
{
    #region private Values
    private Menuangebot myOriginal = new Menuangebot();
    private Menuangebot myValue = new Menuangebot();
    #endregion // private Values

    #region Properties

    #region Detail Properties
    public int Id { get { return myOriginal.Id; } }
    public bool? Result { get; private set; }
    public string Beschreibung { get { return "Einrichtung"; } }

    [Required]
    [RegularExpression(@"^[0-9a-zA-ZäöüßÄÖÜß''-'\s]{2,40}$")]
    public string NameD
    {
        get { return myValue.Name; }
        set
        {
            myValue.Name = value;
            RaisePropertyChanged(() => Reg(() => NameD));
            RaisePropertyChanged(() => Reg(() => dirtyName));
        }
    }
    public bool dirtyName
    {
        get { return (!isNew && myValue.Name != myOriginal.Name) ? true : false; }
    }

    [Required]
    [RegularExpression(@"^[0-9a-zA-ZäöüßÄÖÜß''-'\s]{2,25}$")]
    public string AnzeigetextD
    {
        get { return myValue.Anzeigetext; }
        set
        {
            myValue.Anzeigetext = value;
            RaisePropertyChanged(() => Reg(() => AnzeigetextD));
            RaisePropertyChanged(() => Reg(() => dirtyAnzeigetext));
        }
    }
    public bool dirtyAnzeigetext
    {
        get { return (!isNew && myValue.Anzeigetext != myOriginal.Anzeigetext) ? true : false; }
    }

    [Required]
    public decimal PreisD
    {
        get { return myValue.Preis; }
        set
        {
            myValue.Preis = value;
            RaisePropertyChanged(() => Reg(() => PreisD));
            RaisePropertyChanged(() => Reg(() => dirtyPreis));
        }
    }
    public bool dirtyPreis
    {
        get
        {
            var value = myValue.Preis;
            var Original = myOriginal.Preis;

            return (!isNew && value != Original) ? true : false;
        }
    }

    #endregion //Detail Properties
    #endregion //Properties

// more code

}

what i excspect should be something like
View
<Grid Margin="12">

    <TextBox Height="23" HorizontalAlignment="Left" Margin="102,2,0,0" VerticalAlignment="Top" Width="170" BorderThickness="2"
             Text="{Binding NameD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, EditesOnDataChanges=true}">

    </TextBox>

    <TextBox BorderThickness="2" Height="23" HorizontalAlignment="Left" Margin="102,36,0,0" VerticalAlignment="Top" Width="170"
             Text="{Binding AnzeigetextD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, EditesOnDataChanges=true}">
    </TextBox>

    <TextBox BorderThickness="2" Height="23" HorizontalAlignment="Left" Margin="102,70,0,0" VerticalAlignment="Top" Width="170"
             Text="{Binding PreisD, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, StringFormat=\{0:c\, EditesOnDataChanges=true}}">
    </TextBox>

    <Button Content="Speichern" Height="23" HorizontalAlignment="Left" Margin="102,110,0,0" VerticalAlignment="Top" Width="75" Command="{Binding SaveCommand}"/>
    <Button Content="Abbrechen" Height="23" HorizontalAlignment="Left" Margin="197,110,0,0" VerticalAlignment="Top" Width="75" Command="{Binding CancelCommand}"/>
</Grid>

ViewModel
public class MenuangebotVM : DetailVM, IContains
{
    #region private Values
    private Menuangebot myOriginal = new Menuangebot();
    private Menuangebot myValue = new Menuangebot();
    #endregion // private Values

    #region Properties

    #region Detail Properties
    public int Id { get { return myOriginal.Id; } }
    public bool? Result { get; private set; }
    public string Beschreibung { get { return "Einrichtung"; } }

    [Required]
    [RegularExpression(@"^[0-9a-zA-ZäöüßÄÖÜß''-'\s]{2,40}$")]
    [Default(myOriginal.Name)] //<-- added
    public string NameD
    {
        get { return myValue.Name; }
        set
        {
            myValue.Name = value;
            RaisePropertyChanged(() => Reg(() => NameD));
        }
    }

    [Required]
    [RegularExpression(@"^[0-9a-zA-ZäöüßÄÖÜß''-'\s]{2,25}$")]
    [Default(myOriginal.Anzeigetext)] //<-- added
    public string AnzeigetextD
    {
        get { return myValue.Anzeigetext; }
        set
        {
            myValue.Anzeigetext = value;
            RaisePropertyChanged(() => Reg(() => AnzeigetextD));
        }
    }

    [Required]
    [Default(myOriginal.Preis)] //<-- added
    public decimal PreisD
    {
        get { return myValue.Preis; }
        set
        {
            myValue.Preis = value;
            RaisePropertyChanged(() => Reg(() => PreisD));
        }
    }
    #endregion //Detail Properties
    #endregion //Properties

// more code

}

Answer: public class ViewModel:INotifyPropertyChanged
    {
        private string initialText;
        public ViewModel()
        {
            Text = "ABCD";
            initialText = Text;
            DefaultBorder = true;
        }
        private string text;
        public string Text
        {
            get { return text; }
            set { text = value;
            if (value == initialText)
                DefaultBorder = true;
            else
                DefaultBorder = false;
                Notify("Text"); }
        }

        private bool defaultBorder;
        public bool DefaultBorder
        {
            get { return defaultBorder; }
            set { defaultBorder = value; Notify("DefaultBorder"); }
        }

        private void Notify(string propertyName)
        {
            if(PropertyChanged!=null)
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

public class MyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value is bool && !(bool)value)
                return new SolidColorBrush(Colors.Orange);
            else
                return new SolidColorBrush(Colors.Navy); //Or default whatever you want

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    <Window.Resources>
    <local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<Grid>
    <TextBox BorderThickness="4" BorderBrush="{Binding DefaultBorder, Converter={StaticResource MyConverter}}" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

Here I have property Text in ViewModel that is bound to TextBox and at the beginning i preserved the initial Text value . and then whenever user type i compare it in setter of Text property and set Bool Property accordingly , this bool property will specify which color to Bind using converter.Ignore minor issues hope you will get an idea.
Comment: mhh so i only move the problem (self repeating) in my Text Property and didn't deny them. I thought there could be a `ValidationAttribute` Solution
Comment: you mean you want to show Orange Border Brush as Error in Text.
Comment: no not as Error just as Visual eye catcher if the actual `Text != startText`
Answer: You can probably turn this to a custom control/UserControl and add a IsDirtyDependencyProperty, and the IsDirtyColorDependencyProperty (or attached dependency property). That way you replace all your textboxes with this and not have to repeat the code over and over.
Answer: Coincidentally I just had a problem almost identical to yours, and I solved it by wrapping the TextBox in a Border. Furthermore, this also solved a problem whereby BorderBrush colours cannot be changed on Windows 8 machines.
I would thus recommend this approach. The code is quite straightforward, whereby you just add your textBox to the Border and change the border's BorderBrush property.
Comment: so you created a costume Control like TYY suggested?
Comment: @WiiMaxx - No, my approach is a lot simpler than that. Literally just wrap your TextBox inside a `Border` control. No need for any custom controls.
Comment: could you please show me an example because i can't see the improvement in your solution at the moment
Comment: I don't have access to any code at the moment, but you can read about the `Border` control and its properties over here: http://msdn.microsoft.com/en-us/library/system.windows.controls.border.aspx

You may notice that the property `Child` is perfect for storing your TextBoxes.
Answer: You can use Attached behavior for that
public static class TextChangedAttachedBehavior
{
    public static bool GetChanged(DependencyObject obj)
    {
        return (bool)obj.GetValue(ChangedProperty);
    }

    public static void SetChanged(DependencyObject obj, string value)
    {
        obj.SetValue(ChangedProperty, value);
    }

    public static readonly DependencyProperty ChangedProperty =
        DependencyProperty.RegisterAttached("Changed", typeof(bool),
        typeof(TextChangedAttachedBehavior), new PropertyMetadata(false, HookupBehavior));

    private static void HookupBehavior(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;
        if (textBox == null)
            return;
        textBox.TextChanged += TextBoxOnTextChanged;
    }

    private static void TextBoxOnTextChanged(object sender, TextChangedEventArgs args)
    {
        var textBox = sender as TextBox;
        if (textBox == null)
            return;
        textBox.BorderBrush = new SolidColorBrush(Colors.Orange);
    }
}

And than in xaml
<TextBox Text="{Binding myText1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextChangedAttachedBehavior.Changed = "True" />


How can I make my shell prompt look like a cheeseburger?

Question: I want my shell prompt to look like a cheeseburger!
It would be nice if it also displayed: username, hostname, and current directory.
Comment: The source code for  is
Comment: The Unicode character you used is the one for [hamburger](http://graphemica.com/%F0%9F%8D%94), not cheeseburger. We must petition the Unicode committee to include more fast food-related glyphs. Where are nuggets? Why is there no "with bacon" combining glyph? How on Earth can a Double Whopper and a Big Mac be conflated to the same code point, despite the enormous difference in significance? It's outrageous.
Comment: What font can display these Unicodes?
Comment: @the_Seppi, [Symbola](http://users.teilar.gr/~g1951d/) is one suitable font, which on Ubuntu is part of the `ttf-ancient-fonts` package.
Comment: Can you add a screenshot? I only see , which isn't any fun! ;-)
Comment: @SPRBRN, [unicode-table.com](http://unicode-table.com/) can search for character: http://unicode-table.com/en/search/?q=%F0%9F%8D%94
Comment: I have to say the question looks much better now that I've installed `ttf-ancient-fonts`
Comment: For time, user, host, directory AND git branch (!) see http://unix.stackexchange.com/q/127799/10043
Comment: It doesn't look anything like that in the font I have here though.
Comment: @SPRBRN Use the answer - install taht font package, then the browser will find the glyph too, just like the terminal.
Comment: possible duplicate of [How can I shorten my command line (bash) prompt?](http://askubuntu.com/questions/145618/how-can-i-shorten-my-command-line-bash-prompt)
Answer: great choice!
$ sudo apt-get install ttf-ancient-fonts
$ export PS1="\\u@\h \\w  "

enjoy.
Answer: Putting a cheeseburger on the prompt:

Install a unicode font that contains this character:
sudo apt-get install ttf-ancient-fonts

Try the prompt:
export PS1="\\u@\h \\w   "

Make permanent the change (if you don't do that, it will reset once terminal is closed):

Run nano .bashrc
Go to the 59th line approx. (You can view the current line number pressing Ctrl+C)
Locate these lines:
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

Replace \$ character a the end of the lines beginning with PS1= by the cheeseburger:
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]  '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\  '
fi

Typing a cheeseburger everywhere (linux only):

Press Ctrl+Shift+U
A underlined lowercase u will appear.
Type 1f354
Press Return
A nice cheeseburger will appear.
Comment: Ctrl-shift-u is not linux only, it's GTK only (should work in Windows GIMP, for example, too). Won't work neither in xterm nor emacs nor any Qt-based application including the whole of KDE. Also, there's no need to press Return, just release Ctrl and Shift, and the char will be entered.
Comment: Ctrl-shift-u does not appear to work in xterm or emacs.
Comment: @FindMeInTheWoods, did you install ttf-ancient-fonts?
Comment: It doesn't show for me
Comment: All I get is square
Comment: @Ruslan: Sorry, it may be as you're saying. However `xterm` shows a small box when I enter Ctrl+Shift+U and it allows me to put a unicode character, but only in the "printable" range.
Answer: I couldn't help but take this probably a step too far. This version updates your prompt to display a different character based on time of day, to illustrate what you should be doing at that time.
declare -A pp
pp=(["09"]="" ["07"]="" ["08"]="" [10]="" [11]="" [12]="" [13]="" [14]="" [15]="" [16]="" [17]="" [18]="" [19]="" [20]="" [24]="")
u_pp() {
  c=${pp[`date +"%H"`]}
  if [[ $c == "" ]]; then
    c=${pp[24]}
  fi
  PS1='\u@\h:\w${c} '
};
u_pp
export PROMPT_COMMAND="u_pp;"

Probably there's a more concise way to do it; my bash isn't all that great.
To add the current time of day on the left side, replace the assignment of PS1:
PS1='[\@] \u@\h:\w${c} '

Comment: I know this is the most stupid question to be asked in the `askubuntu`, but I'm just wondering do you have an idea on get this working with `mac`, coz I'm getting `no matches found: [9]=  ` when I add this in to my (mac) ~/.bash_profile :)
Comment: Oh crap, that's a string-vs-integer bug that I found and fixed on my machine, but forgot to update text.

Basically, change single-digit keys like [9] and [7] to ["08"] etc. See updated answer. My bad, sorry.
Answer: If you can't install the 'ancient fonts' maybe a sideways ASCII art cheeseburger would work?
export PS1="\\u@\h \\w (||]"

Of course, there could be different ways of typing this, possibly including lettuce, pickles, etc.
Answer: You can use the following code to create a useful and colorful prompt with an ASCII art hamburger. Well... to be correct, this is a cheeseburger, red meat, with salad on white Italian bread! Special delight! ;-)
Login as the user, go to the home folder and open the bashrc file:
vim ~/.bashrc

Add or replace the following line:
export PS1="\[\e[01;37m\][\[\e[0m\]\[\e[01;32m\]\u\[\e[0m\]\[\e[00;37m\]@\[\e[0m\]\[\e[01;34m\]\h\[\e[0m\]\[\e[00;37m\] \[\e[0m\]\[\e[00;37m\]\t\[\e[0m\]\[\e[01;37m\] \W \e[1;37m(\e[1;32m|\e[1;33m|\e[1;31m|\e[1;37m]\\$ \[\e[0m\]"

Result (no colors):
[john@server003 15:39:14 ~ (|||]$

Create your own format using the bashrcgenerator.
List of color codes
Answer: Green Cheeseburger:
export PS1='\[\e[1;32m\][\u@\h \W]\ \[\e[0m\] '

Red Cheesburger:
export PS1='\[\e[1;31m\][\u@\h \W]\ \[\e[0m\] '

Bicycle:
export PS1="\\u@\h \\w  "

or
export PS1="\\u@\h \\w  "

Love hearts:
export PS1="\\u@\h \\w      "

Show the time on the left and a watch on the right:
export PS1="[\@] \u@\h  "

Answer: Aside from pasting the emoji into the prompt definition directly, you can use the Unicode code point for cheeseburger with printf and command substitution within the prompt:
$ PS1='$(printf "\U0001f354") $ '
 $ echo "Hello,my cheesy prompt!"
Hello,my cheesy prompt!
 $


How do I go about running cable to an off site garage?

Question: So I want to run power to my off site garage about 20 meters from my land. It would need to run down the alleyway from the back of my garden in a straight line to my garage.
It's been cemented over and I don't know what permissions I would need to get to dig it up or where to check for ownership in order to ask permission, it would either be council or shared land from the residents I would imagine though.
Does anyone have any insights to help me here?
Edit: sorry I missed some important points, I'm in the UK, Swindon specifically.
I want to use it to power a workshop, most power at one time will be 2KW and generally for periods of 10 mins tops, other than that it will be LED lights at about 30w. I may consider a dehumidifier though but probably nothing consistent above 400w. So far I have been using a 50m extension lead that's had some slack.
I considered something overhead but I don't know what I would fix it to since the fence posts down the alleyway have gates on the back.
As far as neighbours permission I know I'll need to talk to a lot of them for permission but I get on well with them so I don't think it will be a problem, it's just whether it will be council owned or not.
Comment: Presumably UK  location from the word choice here? Since rules vary with locale, helpful to be certain, not guessing. You can [edit] to clarify.
Comment: Council should have the records of ownership.  Permissions might be difficult, since might be dealing with a few different departments and neighbours together.  Overhead might be another way instead of digging up an alleyway.  Depending on what you want power for, there might be different solutions to running power lines.
Comment: Given the government hassles involved, which Britain is famous for, and the low continuous usage and intermittent medium usage, this setup *is just screaming for* solar/battery.
Comment: Your plans on what you want power for might be helpful.  Running a workshop hours a day is much different to wanting a light or two.
Answer: Lacking details yet:
In most cases, the simplest way (though it has costs associated, it's also often either the least expensive way or the only way) to provide utility power to an "offsite" building is to have the utility provide a separate metered service to that building.
They (and not you, normally) have the rights of way for getting the power from their system to end users. Rather than being a single end user with a cable run in common space, you'll become two end users (house and garage) with separate utility feeds to separate meters.
If your needs are limited, these days a solar panel/battery system may pay off for certain uses (the monthly fee for the metered service adds up) such as limited lighting and recharging garden tools, but may not be adequate for others (you're charging your electric car at night, in the winter, and have poor sun exposure during the day in winter's short days.)
Comment: I would have to agree that a separate drop from the local utility company sounds like a _much_ easier, cheaper and lower liability option than attempting to run your own overhead cable. Even presuming the OP got permission from all the neighbors to string it up, he's still going to be liable should someone back into somebody's fence and bring the power line down and electrify that person's car before he can get out. I would take a stab that _most_ countries with (enforced) electrical codes would prohibit this.
Answer: Based on the combination of:

Other people's land between your two buildings

and

Low total usage

this sounds ideal for a solar + battery setup.
Normally I wouldn't recommend that. But because there are other people's property in between your two buildings, running power between your buildings may be very complicated. If you can get an easement and do it legally and safely, great. That would be a one-time cost and done. But if you can't get an easement due to legal issues (may not be allowed by either local laws or utility company rules) or lack of permission from the neighbors, a separate utility connection may cost a lot, both in up-front costs and monthly costs.
Since your largest planned usage is 2 kW for 10 minutes at a time, solar can be a very practical solution. Let's say you have 50W x 24 hours (though I suspect you won't need the LED lights running all the time) = 1,200 Wh. Add 2 kWh (2 kW run for 10 minutes 6 times a day) and that's a total of 3,200 Wh. Then round things up quite a bit, because large batteries used half-way last a lot longer than small batteries pushed to the limit, and to allow for occasional higher usage - and go for 5 kWh of battery. Plus enough solar to charge up 5 kWh in an average day. Well, more than that because you want it to work in the winter.
How much will all that cost? I don't know! A quick search shows that this will likely end up in the $5,000 - $10,000 range. But if you size things right and do a lot of work yourself (instead of relying on packaged solutions) then I suspect it will be towards the lower end. Still a lot of money, but I think an option worth considering. Big bonus: after installation no electric bill.


Camera Invalidate() can't work in onSensorChanged method

Question: I have a Variable "azimuth_angle"
I hope when i touch the screen and change the direction
the Variable "azimuth_angle" will be decrease
in my code
touch the screen the variable can decrease
but change the direction it cant work
i use the invalidate() same
what wrong with this??

public class HelloCamera extends Activity implements SensorEventListener
{
    private MyView mView;
    float azimuth_angle = 365;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        mView = new MyView(this);

        setContentView(new HelloCameraPreview(this));

        addContentView(mView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }

    private class MyView extends View
    {
        private Paint mPaint;

        public MyView(Context context)
        {
            super(context);
            mPaint = new Paint();
            mPaint.setColor(Color.YELLOW);
            mPaint.setTextSize(12);
        }

        public void onDraw(Canvas canvas)
        {
            float x = 10;
            float y = 20;
            canvas.drawText(String.valueOf(azimuth_angle), x, y, mPaint );
            azimuth_angle--;
        }

        public boolean onTouchEvent(MotionEvent event)
        {
            invalidate();//But this can work
            return true;
        }
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
         if(event.sensor.getType() == Sensor.TYPE_ORIENTATION)
         {
             azimuth_angle = event.values[0];
             mView.invalidate();//it doesnt work
         }

    }
}

Answer: Since the sensor event is not delivered to you in the UI thread, you need to use postInvalidate() instead of invalidate().


Finding 2D array length?

Question: I know that array.length returns the number of rows, but I'm looking for the length of each row.  Apparently array[0].length doesnt do it.  Any ideas?
Comment: offhand it seems like it should, *if* it's been initialized. do you get an exception? if not, what are you getting for the length?
Comment: I get the same length for array[0].length as I do for array.length.
Comment: and it's *not* the same length in reality?
Answer: <code>
jcomeau@intrepid:~/rentacoder$ cat /tmp/test.java
public class test {
 public static void main(String[] args) {
  int[][] blah = {{1, 2}, {3, 4, 5}};
  System.out.println("lengths: " + blah.length + ", " + blah[0].length +
   ", " + blah[1].length);
 }
}
jcomeau@intrepid:~/rentacoder$ (cd /tmp && java test)
lengths: 2, 2, 3
</code>
Seems to work.
Answer: In Java there are only one-dimensional arrays internally.
A two-dimensional array is an array of arrays, so the array for the first dimension and each of the arrays for the second dimension may have a different size.

Finding 2D array length?


Header Alignment on centered page layout

Question: Context
Current page layout stretches across the screen, as this was overlooked in the past due to a small team. I'm looking to fix content width and stretch first and last column of the grid system to improve readability.
The Problem
I've been looking online for information regarding the placement of the header regarding the content, but I haven't gotten anything clear out of it.
My experience says that the page header being on top of the content will require less energy from the user to identify where he's at, as well as reduce the effort for clicking on the back button. However, I haven't found many cases or studies supporting this (or supporting anything, there's little information out there).
Comment: what do you mean by `header`? Based on your screenshot it looks like the logo. Or do you have something else, like a navigation or info or whatever?
Comment: I think it's a mix of concepts, _header_ in UX has a different meaning from _header_ in layout design. For the screenshot, I assume the OP is referring to the titles.
Comment: @Danielillo in that case the question should be edited to *headings*, hence why I asked
Comment: Hi both, thanks for replying. It's actually a header within the page. In our design system we call it "Page Header".

It includes Either a slot for custom usage, which adds tons of flexibility, or it's most wide usage which is a back button (if needed), the page title, and a couple of buttons on the right with a primary and secondary action contextual to the page.
Answer: You are right, the most relevant actions and information must be at the top. There's also data to back this up. There is eye tracking data on how human eyes scan pages (NN Group on F shaped pattern)
Here's a list of eye tracking patterns for anyone whom needs it: https://www.nngroup.com/articles/text-scanning-patterns-eyetracking/
Comment: But in this case he has a sidebar which I assume includes all actions, so they're at the left. The problem here (IMHO) is the huge spacing that is created by narrowing teh content section
Comment: @Devin the concept remains the same, important actions are top-left area. I was just handing OP the data to back that up.
Comment: Thanks for the response Kitanga. Whilst it's true that F shaped patterns are usually a safe bet, on the current use case we do have big descriptive headers that would probably show a cake-layer pattern much more prevalent.
Comment: @Angel yes, which is good, I thought for a sec there that you didn't like the layer-cake pattern. Anyways, I was just linking to the F-shape pattern page as a way to share data on where most people's eyes are fixated on a page. I'll link to more patterns if it helps anyone else in truth.
Answer: As I can remember, using the title on the left, not aligned with the content, is better suited to breadcrumb title styles, but I've failed to find something using this style now.
That being said, I see the title aligned with the content being widely used around (my) web references.
As examples, i found it on pages focused on content:
Like Medium

Open Doors

And Built for Mars

I found this style almost on the entire Storybook's site too
Comment: Hi Eduardo, thanks for the answer.

Yes, I've seen this pattern used in lots of other places. I do however worry about having the navigation on the left side of the app, and moving the back button away from it.
Answer: If the design is responsive, there will be a moment when, depending on the width of the screen, the title will be attached to the left margin of the content (the right option from the screenshot) :

Starting from this premise, you can define a maximum width for the title when the screen exceeds this minimum width. In this way you do not have either of the two cases raised in the question but a middle one  (not stuck to the main content, not stuck to the main navigation):

Main title of this page

Blah... blah..

Comment: Hi Danielillo, thanks for the response.

That's actually an interesting approach, I did not think of it! I still have the question of what is the heuristically-strong approach.

I'll take the approach into account anyway whilst iterating. Thanks!
Answer: We faced a similar problem when cleaning up our app navigation and layout recently. In the end, we decided that aligning the header with the content was the best solution. It means each page has a consistent alignment, making it easier to scan and anchor things like secondary nav or actions.

On scroll, we have the page title transition into the header where it is centre aligned.

We have a minimum width layouts and full-screen, fluid layouts. In every case the content is consistently aligned.


Bodymovin shows wilder animation

Question: We have created some animation with Body Movin, all of them works great.
The problem we have now is, the Body Movin animation animate really wild compared to what it supposed to animate.
Original Animation:

Bodymovin Animation:

You can test and play around here:
https://codepen.io/albertdp/project/editor/AmbRgM
I am calling it the same way it has in the demo.
<code>var animation = bodymovin.loadAnimation({
  container: document.getElementById('bm'),
  renderer: 'canvas',
  loop: true,
  autoplay: true,
  path: 'data.json'
})
</code>
Please let me know if you ever encounter the same issue.
Answer: There is three way to render the animation, maybe you can try :
<code>    var animation = bodymovin.loadAnimation({
            container: document.getElementById('bm'),
            renderer: 'svg',
            loop: true,
            autoplay: true,
            path: 'data.json'
    })
</code>
Comment: Thanks. I have tried that but still not working. We found out that the actual problem was we are using programming function on AE to random the movements. After we remove that, and change to static animation, everything run smoothly

Bodymovin shows wilder animation


WCF service to multiple endpoints

Question: How do I go about making sure that my WCF service can be accessed from any other language(Java, PHP, whatever iOS uses, etc.)?
I have kept everything as httpbinding plus not used any of the .net roles/membership authentication for the clients. But there are some things that I am not sure of. Like, can I return a generic List that is readable by those other languages?
Answer: You cannot be 100% sure if you don't have any control over the client technology that is used to consume your services. But you can be very confident if your web service (WSDL) conforms to the WS-I basic profile v1.1. This standard is very widely supported and mature. You can use the excellent SoapUI test tool to test your WSDL for conformance.
Answer: Any of the WCF bindings that don't start with net (netTcp, netMsmq etc.) should be fine - they're designed to be interoperable.
The most basic one is basicHttpBinding which is pretty much plain HTTP - nothing much can be added to it. You should be able to call this from any scripting language (PHP etc.).
The more advanced binding is wsHttpBinding which implements lots of the WS-* standards and can be called from other languages where the networking stack can handle WS-* - stuff like Java etc.
And then there's the webHttpBinding which exposes your service not via SOAP, but via a REST endpoint. This should be callable from just about any language, any device, any place.
And of course, you get the best coverage if you expose multiple endpoints from your service, offering a variety of choices to anyone trying to call you. All this is done simply in config - no code change necessary to support multiple endpoints, multiple bindings etc.
As for lists and stuff: WCF exchanges serialized messages - basically XML - which is governed by a XML schema. The combination of a WSDL and XSD is totally interoperable and can be understood by a wide variety of other languages.
A List<T> in .NET will be turned into an array in your XML structure, and that's totally interoperable - don't worry. The client might just get back an array instead of a list  - but that's not a problem.
The only problem is that you cannot really model a generic list, since the XML schema doesn't support generics - you need to be explicit about what it is you're sending back. A List<T> won't work - a List<Customer> will (if your Customer object is part of your data contract and marked as such)
Comment: Thanks :). How do I mark an object as part of a data contract?
Comment: @Matt: put an `[DataContract]` attribute on the class, and decorate all members that should be serialized (included in the WCF message) with `[DataMember]`

WCF service to multiple endpoints


LiveOS - Uninstallation by `apt purge` is supposed to increase free disk space, but it actually decreases free disk space. Why?

Question: By uninstalling a package, we expect that there will be more free disk space.  However, "sudo apt purge PACKAGE" actually decreases the free disk space.  It seems that "apt purge" creates more garbage than it deletes anything.  (Edit: This problem occurs only on LiveOS but not on an installed OS. It was later found that this weird phenomenon comes from the unavoidable nature of LiveOS and that apt itself is innocent.)
In the following demonstrative experiment, "apt purge" performed uninstallation of Firefox, followed by uninstallation of ffmpeg.  Before and after each "apt purge", the used space and the free space (available space) of the disk were examined by "df -h /".
Before the first "apt purge", "df -h /" showed the following.  G and M printed by df mean GiB and MiB respectively if -h is present.
Size  Used Avail Use%
1.9G   60M  1.8G   4%

Then, Firefox was to be uninstalled by "sudo apt purge firefox", which printed the following message.
After this operation, 220 MB disk space will be freed.
Do you want to continue? [Y/n]

Y was entered, and the uninstallation was executed.
Then, "df -h /" showed the following.
Size  Used Avail Use%
1.9G  141M  1.7G   8%

Thus, the used space increased by 81 MiB (bc <<< '141-60'), even though it was supposed to decrease by 220 MB.
Next, following the uninstallation of Firefox, ffmpeg was to be uninstalled by "sudo apt purge ffmpeg", which printed the following message.
After this operation, 2058 kB disk space will be freed.
Do you want to continue? [Y/n]

So, 2 MB was supposed to be freed.  Y was entered, and the uninstallation was executed.
Then, "df -h /" showed the following.
Size  Used Avail Use% Mounted on
1.9G  230M  1.6G  13% /

Thus, the used space increased by 89 MiB (bc <<< '230-141'), even though it was supposed to decrease by 2 MB.
Question 1:  Why does the uninstallation by "apt purge" increase the used disk space?
Question 2:  I am not even sure whether "apt purge" ever deletes anything.  I wonder if "apt purge" only moves the package out of the system to a temporary space so that apt can undo the uninstallation later.  If that is the case, exactly in which directory is the uninstalled package staying?  I want to delete it.  Even if shutting down or restarting the machine automatically deletes it, I want to delete it without shutting down or restarting the machine.
Question 3:  "apt purge" seems to create big garbage on the disk.  Where is the garbage?  I want to delete it.  Even if shutting down or restarting the machine automatically deletes it, I want to delete it without shutting down or restarting the machine.
My Ubuntu is Ubuntu MATE 20.04.3 Live.  It is a Live OS.  I am using Ubuntu from the Ubuntu installation media (read-only) without installing the Ubuntu to HDD.  Both Firefox and ffmpeg came with Ubuntu MATE 20.04.3 by default.  I ran the above experiment immediately after the booting of Ubuntu Live completed.
-- update --
The purpose of this question is to solve this problem on the Live OS.  I like Live OSs better than real OSs installed on rw file systems.  If "apt purge" works differently depending on whether a Live OS or an installed OS, and if this problem does not exist on the installed OS, it does not solve my situation at all.  I would like to know why this problem exists on the Live OS.  The Live OS is part of my question.
-- update --
The following comment by Thomas Ward cleared all the mystery that I could not figure out regarding this problem when running on LiveOS.

The difference is stored in memory as a differing file, so you lose space the larger you change the system between the live OS image and your current state.

Especially the clause "The difference is stored in memory as a differing file" is the most helpful infomation.  Without this comment by Thomas Ward, the answer by Nmath did not convince me.
I guess that the "memory" refers to the RAM disk of which "df -h /" reports about the used space and the free space.
Comment: Repeat your experiment using a real OS installed on a rw file system, and then we may talk.
Comment: The expected behavior will never be replicated on the Live OS.  The Live OS is fixed to a specific disk image, and you can't edit that image (it's a read only OS).  The difference is stored in memory as a differing file, so you lose space the larger you change the system between the live OS image and your current state.  See the answers.
Comment: Read [this answer](https://askubuntu.com/questions/295701/what-would-be-the-differences-between-a-persistent-usb-live-session-and-a-instal/295776#295776) for why deleting app in Live USB reduces persistent disk space.
Comment: You cannot uninstall packages in a read only file system.
Answer: "It is a Live OS"
This is the reason.
A live session is based on a read-only file system. Any changes you make during the live session are written in addition to this read only file system.
So if you delete an application, you don't actually delete any of the application files, but more data has to be written to accommodate for the changes you have made.