Jquery ready function with click and ajaxForm calls

Question: I m really new working with JQuery and I have an error in my code. The next piece of code was working perfect when a user click a "Button", it load a file in a content div.
<code> $(document).ready(function() {

        $('.Button').click(function() {
        var href = $(this).attr('href');

        if( typeof href != "undefined" && href != ""){
            $.ajax({
                url: href,
                dataType: 'text',
                success: function(data) {
                            $('#content').html(data);
                            ultXML = href;
                }
            });
        }
    });

});
</code>
But now I m trying to use JQuery Form plugin (with this example http://www.malsup.com/jquery/form/) And it doesnt work (the ajaxForm call), I cant understand how to merge the next code in my orignal code. I try many ways, for example making 2 ready function but it also doesnt work,
<code> $(document).ready(function() {
            // bind 'myForm' and provide a simple callback function
            $('#myForm').ajaxForm(function() {
                alert("Thank you for your comment!");
            });
        });
</code>
Where I must put the next piece of code in my original ready function? How can meger both?
<code> $('#myForm').ajaxForm(function() {
                alert("Thank you for your comment!");
            });
</code>
Answer: Like this, work?
<code>$(document).ready(function() {

$('.Button').click(function() {
    var href = $(this).attr('href');

    if( typeof href != "undefined" && href != ""){
        $.ajax({
            url: href,
            dataType: 'text',
            success: function(data) {
                        $('#content').html(data);
                        ultXML = href;
            }
        });
    }
});

$('#myForm').ajaxForm(function() {
    alert("Thank you for your comment!");
});
</code>
});
Comment: No, I tried that way but it doesnt work, is that the proper way of do it? In that way just the Button click work and if I put first myForm, the Button doesnt work
Comment: I take this code out of my application (just to test it) and it works, I supose there is an error in another part of the code I m doing, thanks!


FastApi runs with DockerFile doesn't run with docker-compose

Question: I have this simple project structure:

I use FastApi as backend and React as frontend.
When I run FastApi DockerFile it works just fine:
FROM python

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY ./app .

ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

But the moment I use docker-compose:
version: "3.9"
services:
  backend:
    container_name: backend
    build: ./FastAPI
    ports:
      - "8000:8000"
    depends_on:
      - redis
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload

  frontend:
    container_name: frontend
    build: ./React/react-app
    ports:
      - "3000:3000"
    depends_on:
      - backend

  redis:
    container_name: redis
    image: "redis:alpine"

I get this error:

Error response from daemon: failed to create shim task: OCI runtime
create failed: runc create failed: unable to start c ontainer process:
exec: "uvicorn": executable file not found in $PATH: unknown
docker-compose process finished with exit code 1
Comment: try without command in docker-compose. Use CMD in dockerfile
Comment: @Mate, done. Still same error.
Answer: try
1st delete your "backend" local image
docker rmi -f {imageid}

docker-compose.yml
services:
  backend:
    container_name: backend
    build:
      context: ./FastAPI
      dockerfile: ./Dockerfile
    ports:
      - "8000:8000"

requirements.txt
fastapi==0.95.*
uvicorn[standard]==0.21.*

Comment: After 6 hours with this I understood I only needed to rebuilt this backend image...
Comment: oohhh, typical!


Defining Equality for $\mathbb{N}\times\mathbb{N}$

Question: I recently learned about equivalence relations and how equality between integers is an example of an equivalence relation. I also learned that operations such as addition (and possibly relations like equality) may be defined differently on different objects.
Consider the set of ordered pairs of natural numbers, $S=\mathbb{N}\times\mathbb{N}$. Then following is an equivalence relation on $S$:
Let $(a,b),(c,d)\in S$. Then $(a,b)R(c,d)$ if $a+d=b+c$.
I was wondering if we can define equality between elements of $S$ by the above relation. I suppose that we typically define equality on $S=\mathbb{N}\times\mathbb{N}$ as we do in $\mathbb{R}^2$:
Let $(a,b),(c,d)\in S$. Then $(a,b)=(c,d)$ if $a=c$ and $b=d$.
According to Wikipedia Definition of Equality, $x=y$ if and only if, given any predicate $P$, $P(x)$ if and only if $P(y)$. Would the following be an example to show that the definition of equality as $(a,b)=(c,d)$ if $a+d=b+c$ is invalid?
Under this definition of equality for elements of $S$, $(2,3)=(4,5)$. If $P$ is the predicate, $s\in S$ has first coordinate $2$, then $P(2,3)$ is true but $P(4,5)$ is false.
If so, would the only acceptable definition of equality in $S$ be $(a,b)=(c,d)$ if $a=c$ and $b=d$? This question Defining an Equality appears to be relevant but I am not sure how to interpret I.4.
Thank you for your help. I would appreciate an explanation suitable for a undergraduate like myself.
Comment: This will not work if you define the equiv rel using equality...
Answer: In the standard set theory of Zermelo-Fraenkel, two objects are equal if they are the same set, i.e. if all their elements are the same (axiom of extensionality).
This said, you can define different kind of equalities on sets -basing on your needs- through, for instance, equivalence relations. This does not violate the equality in ZF, it is just an internal definition (e.g. equivalence relation) that you can call "equality", but it is not the actual equality of sets.
What you are trying to define seems to be the set-theoretical definition of integers $\mathbb{Z}$. Integers are usually defined as $(\mathbb{N}\times \mathbb{N})/ R$, where $R$ is the equivalence relation on $S=\mathbb{N}\times \mathbb{N}$ that you defined.
The idea behind this definition is that a pair $(a,b)\in S$ in meant to represent $a-b$, thus $a-b=c-d \iff a+d=c+b$. The definition uses the sum instead of the difference because $\mathbb{N}$ is closed under the sum but not under difference, so using the sum $a+d=c+b$ allows us to define the relation without using the integers (which would be a problem since we are just defining them).
Comment: @monkeyking yes, this is the ZF set-theoretical definition of natural numbers by Von Neumann. While the set-theoretical definition of ordered pair (Kuratowski's definition) is: given two sets $A$ and $B$, an element $(a,b)\in A\times B$ is defined as $\{ a, \{a,b\} \}$. Thus, the element $(2,3)$ is actually $\{ 2, \{ 2,3\} \}=\{ \{1\}, \{ \{1\}, \{2\} \}  \}=...$. You can reconstruct the actual expression for $(2,3)$ by re-iterating the re-writing until you only use braces and $\emptyset$
Comment: Thank you for your help. I have heard of natural numbers being sets, e.g $0=\emptyset$,  $1=\{\emptyset\}=\{0\}$, $2=\{\emptyset,\{\emptyset\}\}=\{0,1\}$, $3=\{\emptyset,\{\emptyset,\{\emptyset\}\}\}=\{0,1,2\}$, etc. So what set would, say, $(2,3)$ be?
Answer: Equality is a type of equivalence relation, but not the only type of equivalence relation. We say a relation is an equivalence relation if it has the same properties as equality (like reflexivity, symmetry, and transitivity). But many other equivalence relations say elements are equivalent if they share a certain property that doesn't necessarily have to be equality. So yes, in your example, $(2,3)R(4,5)$, but that doesn't mean $(2,3)=(4,5)$ because $=$ is a different equivalence relation than $R$. So yes, equality on $S$ holds if and only if the coordinates are equal, and that is one of the many equivalence relations you can have on $\mathbb{N}\times\mathbb{N}$.
Here are some common examples of equivalence relations:

In $\mathbb{Z}\times(\mathbb{Z}\setminus\{0\})$ we have $(a,b)R(c,d)$ if $ad=bc$, or in other words, if $a/b=c/d$. So in this example $(2,4)R(1,2)$ but we don't have equality between these two points. In fact it's just that the fractions are equivalent. This equivalence relation is used to construct the rational numbers, and (if you've learned about this yet) fields from integral domains.
In $\mathbb{Z}$ two elements are related if they are congruent modulo $n$, and this is an equivalence relation.
In group theory, if we have a group $G$, two elements are related if they are in the same coset of a subgroup $H$.

There are so many more examples of equivalence relations beyond equality that are helpful in a variety of ways in advanced mathematics. It will help to think more broadly about what equivalence means beyond elements being equal.


Is it possible in android to add app icon to status bar?

Question: Is it possible in android to add app icon to status bar, similar to wifi/bluetooth icon? I know it can be done using Status Bar Notification, but it gets cleared when we clear notification. Can I show icon permanently on status bar?
Comment: Post the solution or the snippet of you've solved your issue
Answer: To keep the icon there until you clear it you can do the following:
<code> Notification notification = new Notification(R.drawable.icon, "", when_to_display);
 notification.flags |= Notification.FLAG_AUTO_CANCEL;
</code>
Then you must clear it. There are other flags too, all described here:
http://developer.android.com/reference/android/app/Notification.html
Comment: Thanks David for the reply. I figured it out. I am now using flag on_going so that the icon just remains in the tray
Comment: Yeah looking at my answer in hindsight shows it really didn't answer your question that flag (AUTO_CANCEL) was definitely not the one you were looking for.


Assembly binding problems in .NET

Question: I am writing a .NET library that for various reasons cannot be registered in the GAC.
This dll (let's call it SDK.dll) depends on other DLLs in order to be loaded.
When writing a program that uses this SDK.dll, I noticed that my program failed loading the dll with a FileNotFoundException thrown. This happens because although I was able to find the referenced SDK.dll, the CLR failed to load its dependencies.
The only way I found to solve the problem is to "Copy Local" the SDK.dll and all its dependencies (something I can't do because of deployment problems), or compiling my program into the same directory as SDK.dll
Is there a way to tell SDK.dll where to look for it's dependencies regardless of its location? Maybe a SDK.dll.config file can help?
Answer: You can handle this at runtime by subscribing to this event:
AppDomain.CurrentDomain.AssemblyResolve

It's fired when the runtime fails to resolve an assembly. In your event handler method, write your logic to find the assembly and load it using Assembly.LoadFrom(). It would look something like this:
public SDKClass()
{
  AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(FindAssembly);
}

private Assembly FindAssembly(object sender, ResolveEventArgs args)
{
  string assemblyPath = "c:\PathToAssembly";
  string assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
  string assemblyFullName = Path.Combine(assemblyPath, assemblyName);

  Assembly theAssembly = Assembly.Load(assemblyFullName);

  return theAssembly;
}

Answer: to register your assembly in GAC it must have be signed with a strong name.
If it depends on other assemblies, those should be in GAC to.
BeowulfOF
Answer: You can't GAC the SDK but could you GAC the dependancies?
Also Read this msdn article on assembly binding:
http://msdn.microsoft.com/en-us/library/efs781xb(VS.71).aspx
if your assemblies are strong named you can use code base, if they are not the code base has to be a child directory of your isntall which won't help.
Answer: Try to use DEVPATH env variable.
http://msdn.microsoft.com/en-us/library/cskzh7h6.aspx
Answer: Re: Snooganz
You probably mean to use LoadFile instead of Load, like so:
Assembly theAssembly = Assembly.LoadFile(assemblyFullName);

Assembly.Load will probably get you into an infinite loop =)
Comment: As long as the assembly pointed to by "assemblyFullName" exists there is no infinite loop. The AssemblyResolve event is only fired if the assembly cannot be found, so it wouldn't be fired again in that call to Assembly.Load(assemblyFullName). The sample code was simply to demonstrate how to handle the event...You should of course insert error checking where appropriate (such as checking for the assemblies existence).

Assembly binding problems in .NET


Are strong convergence of measure and almost sure convergence of a random variable related?

Question: I am studying measure theory and probability I am wondering if and how these two concepts are related.
A sequence of random variables $X_n$ defined on some probability space $(\Omega,\mathscr{A},\mu)$ converges almost surely to $X$ if $\mu\left(\{\lim_{n\rightarrow\infty}X_n=X\}\right)=1.$
A sequence of measures $\mu_n$ converges strongly to $\mu$ if $\lim_{n\rightarrow\infty}\mu_n(A)=\mu(A)$ for all measurable $A$. So $\mu$ and $\mu_n$ are defined on the same measure space $(\Omega,\mathscr{A})$.
Now, is there anyway that these two types of convergence are related?
For example, if we have $X_1,\ldots X_n,\ldots$ are $iid$ standard Gaussian, then the strong law of large numbers says that $\mu(\{\lim_{n\rightarrow\infty}\bar{X}_n=0\})=1$, where I believe $\mu$ can be written as a measure on the space $(\mathbb{R}^\infty,\mathscr{B}(\mathbb{R}^\infty))$. The space on which $\mu$ is defined is one point of confusion.
The sample mean for fixed $n$ also has a Gaussian law with variance $1/n$. We can call this measure $\mu_n$, and it can be defined on the space $(\mathbb{R},\mathscr{B}(\mathbb{R}))$.
Is $\mu_n$ a valid measure on the space of the whole sequence $(\mathbb{R}^\infty,\mathscr{B}(\mathbb{R}^\infty))$, even though it only concerns the first $n$ random variables? Can I set this problem up in a way that says $\mu_n$ converges strongly to $\mu$ ? where $\mu$ is degenerate at 0?
Answer: There was such a question: "Is there anyway that these two types of convergence are related?"
Suppose we have $X_n \to X$ almost surely.
Put $P_n (A) = P(X_n \in A)$  and $P(A) = P(X \in A)$ for all Borel set $A$. Then $P_n$, $n \ge 1$ and $P$ are probability measures on real line.
$X_n$ converges to $X$ almost surely, hence $X_n$ converges to $X$ in distribution, and a sequence of measures $P_n$ converges weakly  to the measure $P$. According to Portmanteau Theorem (see Billingsley, Convergence of probability measures, 1999, 2nd edition, pp.15-16) it follows that $P_n(A) \to P(A)$ for all Borel sets $A$ such that $P( \partial A) = 0$. The next example shows that condition  $P_n(A) \to P(A)$ holds not for all Borel sets $A$.
Consider a probability space $(\Omega, \mathcal{F}, \mu)$ where $\Omega = [0,1]$, $\mathcal{F}$ is sigma-algebra of Borel sets of $\Omega$ and $\mu$ is a standard Lebesgue measure, that is $\mu([a,b]) = b-a$. Put $\xi_n(\omega) = n \omega $ for $\omega \in [0, \frac{1}n ]$ and $\xi_n(\omega) = 0$ otherwise. In this case $P_n \sim U[0, \frac{1}{n}]$, $\xi_n \to X \equiv 0$, $P$ is Dirac measure at zero.
For $A = [ - 1, 0] $ we have $P_n(A) = 0 \nrightarrow P(A) = 1$.
As a result we get the next statement. If $X_n$ converges to $X$ almost surely then for corresponding measures $P_n$ and $P$ we have $P_n(A) \to P(A)$ for all Borel sets $A$ such that $P( \partial A) = 0$ but not for all $A$.
Now suppose we have convergence $P_n(A) \to P(A)$ for all $A$ from some sigma-algebra. If these measures are not probability measures of if these measures are not measures on $\mathbb{R}$ with Borel sigma-algebra, then there is no direct relationship between them and any random variables. Suppose that $P_n(A)$, $P(A)$ are probability measures on $\mathbb{R}$ with Borel sigma-algebra and $P_n(A) \to P(A)$ for all Borel sets $A$. Hence $P_n$ converges to $P$ weakly (Portmanteau Theorem). According to the Skorokhod's representation theorem we can construct random variables $X_n$, $X$ such that $X_n$ has distribution $P_n$, $X$ has distribution $P$, $X_n \to X$ almost surely and moreover $X_n$ and $X$ are defined of probability space $(\Omega, \mathcal{F}, \mu)$, where $\Omega = [0,1]$, $\mathcal{F}$ consists of Borel sets of $\Omega$ and $\mu$ is a standard Lebesgue measure, that is $\mu([a,b]) = b-a$.
As a result we get the next statement. If $P_n(A)$, $P(A)$ are probability measures on $\mathbb{R}$ with Borel sigma-algebra and $P_n(A) \to P(A)$ for all Borel set $A$ then there are random variables $X_n, X$ on a "simple" probability space such that $X_n$ has distribution $P_n$, $X$ has distribution $P$ and $X_n \to X$ almost surely.


Encode UTF-8 for Django form

Question: I have a contact form
class ContactForm(forms.Form):
    name = forms.CharField(required=True, max_length=100, label=_('firstname'))
    mail = forms.EmailField(required=True, max_length=150, label=_('mail'))

def display(request):
    form = ContactForm(request.POST)
    if form.is_valid():
       ...
    else:
       form = ContactForm()

    return render_to_response('contact.html', {'contact_form' : form}, context_instance=RequestContext(request))

With from django.utils.translation import gettext_lazy as _
In my template contact.html
<form action="#" method="post" >{% csrf_token %}
    {{ contact_form.as_p  }}
    <input type="submit" value="Send" />
</form>

I have this error

'ascii' codec can't encode character u'\xe9' in position 2: ordinal
  not in range(128)
Unicode error hint
The string that could not be encoded/decoded was: Prénom

The problem is _('firstname')). But it works when

I put .encode('utf8') at the end it's solved.
I use the string without the translation tool
I use another text like _('other string')
I add string at the end : _('firstname')+''
I use the translation in the view : {% trans "firstname" %}

But I don't want to do this in all attributs of my contact form (which contains more attributs).
How can I do that for name and email both ?
Thanks
Answer: THE SOLUTION is to replace gettext_lazy by ugettext_lazy because the string Prénom contains a special unicode letter é
Answer: Type on the first line:
# -*- coding: utf-8 -*-

Python recognises this line as instructions of encoding type for your entire file.
Answer: You don't specify whether you use ModelForms or not, but can you check in your template that your browser will correctly encode the submitted data with the content='text/html; charset=UTF-8' attribute in the form tag? Like:
<form action='/someurl' method='post' content='text/html; charset=UTF-8'>

Comment: If I add this content attribute, nothing change. And I use forms.Form to create my form
Comment: Can you post the code of your entire project somewhere? Then I can step through it see what causes the error.
Comment: What do you know/see exactly ? I forgot to see, all work if I display `_('firstname')` outside of form
Comment: I'd like to reproduce your error, so I can find the cause of it. At this moment, I don't have enough information - I can't run your code because I haven't got it. If it's a proprietary project which you cannot share, I'm afraid I can't help you at this moment. Alternatively, you could make a minimum Django project that illustrates the error and that _can_ be shared.
Comment: I added more explanations on the original post
Comment: Do you have enought informations @Michiel Overtoom ?
Comment: Negative, I need a minimal application which reproduces the error. I'm willing to make an effort debugging the problem, but not if I first have to try to recreate your error. I also don't know what you have in your translation files. Please supply me with something that I can readily run and shows the problem.

Encode UTF-8 for Django form


Why are my buttons differently sized and their contents differently aligned?

Question: Check this example using Bootstrap 4 and Material icons :

It seems that only the first button is correctly sized and its icon correctly aligned, plus the icons are all the same size.
I noticed that removing the following css code fixes it :
.btn-icon::after{
  content: " "  attr(title);
  letter-spacing: -1rem;
  opacity: 0;
  transition: letter-spacing 0.3s ease-out, opacity 0.3s ease-out;
}
.btn-icon:hover::after{
    letter-spacing: normal;
    opacity: 1;
}

But I need that effect. Why is this extra "ghost padding" being added on the right of the non-first buttons? And how can I fix this?
JsFiddle : https://jsfiddle.net/xpvt214o/136541/
Answer: Ok, so my previous answer had some strong points, but it wasn't correct.
I now have the correct answer for you. It's in the differences;
Your original jsFiddle;
 <button title="Button1" class="btn btn-outline-secondary btn-icon">
          file_download</button>
        <button title="Button2" class="btn btn-outline-secondary btn-icon">
          search
        </button>
        <button title="Button3" class="btn btn-outline-secondary btn-icon">
          filter_list
        </button>

This is because we are working with inline elements here. We are nesting something within the button elemenent, which means it behaves differently. In fact, it behaves differently in the sense that (and browsers don't all treat this the same, ie; Firefox creates spaces and Chrome does not) when you leave empty space within said elements. Usually you wouldn't notice, but because the :after creates content behind it, the whitespace is ineed rendered as whitespace (in firefox)
So, there are 2 ways to fix this issue;
The simple way; remove the whitespace from your code
<button title="Button1" class="btn btn-outline-secondary btn-icon">
  file_download</button>

Or the code-technically messy way but won't break if someone reformats your code so it's more stable and trustworthy way;
<button title="Button1" class="btn btn-outline-secondary btn-icon">
  file_download
  </button>
<button title="Button2" class="btn btn-outline-secondary btn-icon">
  search</button>
<button title="Button3" class="btn btn-outline-secondary btn-icon">
  filter_list</button>

This is why I prefer to use div elements and just style them as buttons, but that faces different issues. I just avoid these inline elements mostly because they get treated differently cross-browser a lot.
-- oh, and the JSFIDDLE of course!
Here is some more info on dealing with inline-block elements and their whitespaces!
Comment: The problem still shows for me in firefox, and that space had a purpose
Comment: Well that's odd. Is replacing the space with a padding a possible solution? Anyway, I'm going to check it out on firefox.
Comment: Check out my updated JSfiddle link. Works for me in firefox now. I'll update my answer with the explanation
Comment: I thank you for your time. but now that content when not hovering is blank, it no longer has a smooth animation when you "unhover" it.
Comment: @Mojimi there ya go. The problem was within the HTML and not the CSS. This means you did good and I'm proud of you, newbie. Clearly, even I didn't notice it the first 2-3 looks so, there's that... (I've been doing this for about 5 years). I hope you (and I) can learn something from this!
Comment: I had no idea white spaces were considered in html, thank you for your time and kind words
Comment: Only within certain elements like A, P and buttons (which do not allow divs inside)


Use SharePoint as a UI to a SQL table

Question: Can I use a SharePoint list as a user interface to a table in my SQL db?
Mean - the user can read form the db and write there.
Answer: Sure you can. This is a pretty good guide.
You can specify which columns to show, specify custom queries, order, filter, join...
Furthermore, you could also use the SSRS integration package to display it in a more BI-friendly manner... but if all you want is to expose SQL through a SharePoint list, the link above will do.
Hope that helps!
Comment: thanks! I make a data source, but how can I connect a list to this data source?
Comment: You do all that through SharePoint Designer. It's pretty self-intuitive.

Use SharePoint as a UI to a SQL table


How to show an error message when email val is not available in firebase database

Question: My Firebase Database is look like as bellow:

I want to show an error message when email val is not available in firebase database.
And my code is
mRef.orderByChild("email").equalTo(val).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            User user = dataSnapshot.getValue(User.class);

                textView.setText("Welcome " + user.name );
                System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                User user = dataSnapshot.getValue(User.class);
                textView.setText("Welcome " + user.name );
                System.out.println(user.name + "\n" + user.email + "\n" + user.tell);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

Comment: What's the problem? The query matches the users with `email: `. If something is not working, the problem is likely in the way you implemented `ChildEventListener`. Please provide the [minimal, complete code that reproduces the problem](http://stackoverflow.com/help/mcve) to improve the changes of getting help.
Comment: `new ChildEventListener...` is not valid Java code. Please [edit] your question to contain a [mcve] (including a minimal example data set **in text**), instead of this.
Comment: Hii  @FrankvanPuffelen , My problem is that , when i search with email if it available in firebase database then i get the data with that email and it,s working,but I also want to show a message for, If  giving email is not available on firebase then i want to show message like invalid user.
Comment: @FrankvanPuffelen , The above code is only work for if email  is available on firebase. I want to show an error message if email.  is not available on firebase. Thank You
Answer: A ChildEventListener can only detect the presence of a certain child node or when a child node is changed/removed. It cannot detect the absence of a child. To detect that there is no value, you need a ValueEventListener:
mRef.orderByChild("email").equalTo(val).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.getChildrenCount() == 0) {
            System.out.println("No user with email "+val);
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
        throw firebaseError.toException(); // don't ignore onCancelled!
    }
});

Comment: Thanks @FrankvanPuffelen, It's working. thank You..!
Answer: mQuery = databaseReference.limitToLast(1).orderByChild("email").equalTo(category);

        mQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.i(TAG, "onDataChange: "+dataSnapshot.toString());
                GenericTypeIndicator<Map<String,UserModel>> t=new GenericTypeIndicator<Map<String,UserModel>>(){};

                try{
                      Map<String,UserModel> userList=dataSnapshot.getValue(t);
                }catch(Exception exception){
                    //Error UserInfo not present in firebase
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
               //Error wile accessing database
            }
        });


How to access context in non activity classes

Question: I am writing my first Android application and have some problems with handing around context objects. A lot of methods/constructors seem to require the current context (activity) which causes me some problems in my action listeners. Instead of having all my listeners and handlers as anonymous classes in the activity class I have created classes for each event I would like to handle. For example a button buttonRegister would be initialized as:
<code>buttonRegister.setOnClickListener(new RegisterButtonClickAction());
</code>
However when doing this I have no access to the current context object inside my listener. I could hand over a current context as a constructor parameter but I am not sure whether this is the best choice. What is the "best practice" for creating handler/listeners in Android or working with context objects in general?
Thanks,
b3n
Comment: I've been using constructor parameters or anonymous inner classes without problems.
Answer: Just pass the current Context in the handler's constructor.
Tho using event handlers like these can get messy. Most of the time, when you're handling some event - like pushing a button - then you want to change the states of other variables that are in your Activity (change some data structures, UI elements like TextView, whatever). If the event handler class is outside, you also have to provide references for the objects it can modify, possibly in it's contructor.
I usually just use anonymous, or at least inner classes, I think that's much more cleaner and simpler.
Comment: Thanks, it makes sense even though I wanted to avoid huge classes with all sorts of event handling logic and split it up a little.


Read from console.log?

Question: I'm new to web development, so please excuse me if my question seems a bit silly. Is it possible to read a value FROM the console in the browser as a variable in JS. an Example :
I get a "ReferenceError: incorrect is not defined" error. i want to create an if/else statement dependent on that result. Is this possible?
EDIT:
I'm using an AJAX call that sends the data and i can see the result in the console. this is my code:
$('#RequestBut').click(function () {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json",
                    dataType: 'jsonp',
                    url: "http://www.google.com/recaptcha/api/verify",
                    data: {
                        privatekey: 'XXXXXXXXXXXXX',
                        remoteip: document.getElementById("ipaddress").innerHTML,
                        challenge: Recaptcha.get_challenge(),
                        response: Recaptcha.get_response()
                    }
                })

            });

I see the result I am looking for in the console. All I want is to retrieve it.
Comment: If you're logging it you should already have the value somewhere to store as a reference in the actual program.
Comment: In browser's console you can just create a variable with desired value
Comment: try ... catch statement around your code?

An evil approach would be to override console.log method, but I would not recommend it...
Comment: You'd benefit from a little separation of concerns (debugging / actual data storage)
Comment: what is the name of the variable you want to read? don't you have a call back method for your ajax?
Comment: callback: Recaptcha.focus_response_field. Is that my callback method? Sorry I'm new at this.
Comment: @ZlatinZlatev  what do you mean?
Comment: If only I remember what it was, four years ago... Which part of my comment you're referring to, @FourCinnamon0 ?
Comment: I don't understand the negative votes. In many cases the console throws warnings or errors that belong to third party libraries. Also, it is quite difficult to debug on mobile devices.
Answer: You can run arbitrary Javascript in the developer tools console (at least in Firefox and Chrome), but that is not the same as "reading from the console".
To enter more than one line use "shift+enter" instead of "enter" (which will run the script).
So you can write in the console:
try {   /* press shift+enter here */
   bla_bla  /* press shift+enter here */
} catch(e) { console.log(e) }   /* press enter here */

This will capture the ReferenceError exception e
Answer: If you have a leak in the pipes in your house, do you put in an order for a large number of buckets to catch the water, or do you just close the main tap?
You can catch the error at the source, and you can probably catch the error with try { } catch( e ) {}; if it's external code you are calling. You can't read what's been logged to the console, though you could probably override the logging function and catch everything that way. But that again brings you to my opening question, do you go for a broad sweeping solution or something specific to the task?
Update: You can't trap ajax calls like you want to, that's what the done and fail "Promise" callbacks are for (documentation). Something like:
            $.ajax({
                type: 'POST',
                contentType: "application/json",
                dataType: 'jsonp',
                url: "http://www.google.com/recaptcha/api/verify",
                data: {
                    privatekey: 'XXXXXXXXXXXXX',
                    remoteip: document.getElementById("ipaddress").innerHTML,
                    challenge: Recaptcha.get_challenge(),
                    response: Recaptcha.get_response()
                },
                done: function( data, statusString, jqXHR ) {
                     // do something with data here
                },
                fail: function( jqXHR, textStatus, errorThrown ) {
                     // do something with the error here
                }
            })

Comment: I've updated my answer ... would have made it easier if you had said from the start you're using `$.ajax()`.
Comment: I have tried to use try catch to solve the problem, but could not produce the result I needed.
Comment: Thank you for your reply. It seems that it skips over the success and error portions. I have inserted alerts into the AJAX call at success and error, but neither one of them got triggered. Any idea what might be causing this? And I do apologize not mentioning that it is an AJAX call. Sorry.
Comment: Sorry about that ... you should use `.done()` and `.fail()` (and `.always()`, if you need it) instead. The `success` and `error` methods I mentioned earlier are long deprecated and probably don't work with cross domain requests.
Answer: Yes, it is possible to read a variable from the browsers JavaScript console. I guess you are using chrome. You get that kind of error because the variable you are referring is not accessible. It could be that you haven't declared it as a global variable or you have failed to declare the variable. You can declare a global variable by writing

in your html file. Or just exclude the script tags if you are writing javascript.
Then in the JavaScript console, you should be able to read the value of myVariable by simply writing myVariable in the console.
Comment: I actually want to read from the console to a JS variable. Say I got a string var named error. The event listens for the error to appear in the log. As soon as it appears the var error gets a string value from from the console that contains the error string. As for the browser I need this to be cross browser compatible.

Read from console.log?


Ember -- JSON API Adapter Error Handling

Question: I want to take a specific action when an API request results in a 404 error.  I've read that the appropriated way to do this would be handling the error in the application adapter like below:
  handleResponse: function(status, headers, payload){
    if(status === 404 && payload.errors){
      //handle error
    }
    return this._super(...arguments);
  }

The problem is, as soon as I set up the adapter, it won't finish loading the page so I can handle the error on the page itself.  Instead, it automatically takes me to some error route that just says "Adapter error".  How can I stop/override this behaviour?
Answer: Turns out I needed to adjust the handleResponse hook in the application adapter to pass the new requestData parameter to the super method.
handleResponse (status, headers, payload, requestData) {
    return this._super(status, headers, payload, requestData);
},

Then I just changed the first line of the code in my question from
handleResponse: function(status, headers, payload) {

to
handleResponse: function(status, headers, payload, requestData) {

I was then able to catch and handle the error
Answer: Perhaps you could handle it on a request basis like below:
return this.get('store').find('user', userId).then((user) => {
    this.set('user', user);
}).catch((reason) => {
    var possible404 = reason.errors.filterBy('status','404');
    if(possible404.length !== 0) {
      // Handle 404 error
    }
});

Although this is not the solution that you wanted, this alternative will allow you to customize more. By the way, the automatic behavior seems to be the application-error substates kicking in on 404, so give it a read if you want to override the behavior.
Comment: Thanks, I came up with another answer awhile ago, but forgot that I had posted this.  I'll post the answer I came up with.


How to groupby certain column in a dataframe in pandas?

Question: I have the following dataframe where I have different genes, drugs ID's and citations.  I essentially need the same gene to be merged with the same drug but include both citations for that drug if it is to occur.  For example below:
pharmacogenomic
      Gene                          Drug                     ID     Cite
1  MAD1L1                       Lithium[17]           34718328     [17]
2    OAS1                       Lithium[17]           34718328     [17]
3    OAS1                       Lithium[7]            27401222      [7]

MAD1L1 has lithium and citation 17, but OAS1 has lithium and citation 17 and 7.  I would like to concat the table into something similar to below:
      Gene                          Drug                     ID     Cite
1  MAD1L1                       Lithium[17]           34718328     [17]
2    OAS1                       Lithium[17][7]        34718328     [17]

OAS1 has lithium ,but both citation are next to eachother, and MAD1L1 is unchanged as it does not share the same citation for lithium as OAS1.
Comment: What about the Cite column for Gene OSA1? Shouldn't this also contain the citations next to each other?
Comment: @VishnuNadhan I suppose it can, as I really only care about the drug and gene column, but those two citation have different ID's meaning they have different citation pertaining to them.
Answer: here is one way to do it
#use cite to group together the citations
df['cite2']=df.groupby('Gene')['Cite'].transform('sum')

#group by gene, and take the first result for each gene
df2=df.groupby('Gene').first()

#split the citation from the Drug name and append the cite2 (created above)
df2['Drug']=df2['Drug'].str.split('[', expand=True)[0] + df2['cite2']

# drop the temporary cite2 columns
df2.drop(columns='cite2', inplace=True)
df2.reset_index()

    Gene    Drug    ID  Cite
0   MAD1L1  Lithium[17]     34718328    [17]
1   OAS1    Lithium[17][7]  34718328    [17]

Answer: Remove the citation from "Drug", then groupby.agg, either as 'first' or to join the strings. Then add back the citations:
out = (df
 .assign(Drug=df['Drug'].str.extract(r'(^[^\[\]]+)', expand=False))
 .groupby(['Gene', 'Drug'], as_index=False)
 .agg({'ID': 'first', 'Cite': ''.join})
 .assign(Drug=lambda d: d['Drug']+d['Cite'])
)

Output:
     Gene            Drug        ID     Cite
0  MAD1L1     Lithium[17]  34718328     [17]
1    OAS1  Lithium[17][7]  34718328  [17][7]


Loop Through an Object's Values and Delete Falsey Values

Question: I'm looking to loop through an object and delete values that are deemed to be "falsey", ie: false, null, 0, Nan, etc.
So far, my code looks like this:
function truthyObjLoop(user) {
var falseAnswer = undefined;
for (var key in user) {
  if (user[key] === false) {
    falseAnswer += user[key];
    delete falseAnswer;
  }
}
return user;

}
I know it's bugged, but I'm having a difficult time locating and fixing the issue. I'm very new to Javascript and any help is appreciated.
Thanks.
Comment: shouldn't it be delete user[key] ??
Comment: `user[key] === false` will only be `true` if `user[key]` is indeed `false` (not any falsy value).
Answer: You were rather close in your first attempt. However, comparing === false will not always catch "falsey" values. Simply using !value on and checking for true will look for falsey values because it implicitly casts the value to boolean. At that point all that is left is to iterate and remove.
function truthyObjLoop(user){
    for(var key in user){
        if(user.hasOwnProperty(key) && !user[key]) delete user[key];
    }
    return user;
}

Comment: [It seems to be fine](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots-enumerate): *"Properties of the target object may be deleted during enumeration. A property that is deleted before it is processed by the iterator's next method is ignored. If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration. A property name will be returned by the iterator's next method at most once in any enumeration."*
Comment: I don't think there is any problem deleting the property one just visited.
Comment: @FelixKling - That wont cause side affects? Is that because they are considered to be out of order anyway? I was unsure what the internal enumerator's behavior for `for( var key in obj)` would be in that case.
Comment: I guess it does something similar than you do explicitly.
Comment: @FelixKling - Okay, thanks for the clarification. I will edit that part out of my answer then and put the shorter version in.
Answer: If you only want to catch values which are equivilant to false, null, undefined, or 0... you should use @travis j's answer. however if you want to also match NaN values, i'd suggest a minor adjustment
function truthyObjLoop(user){
for(var key in user){
    if(user.hasOwnProperty(key) && (!user[key] || isNaN(user[key]) )) delete user[key];
}
return user;
}

if you can extend it even further to include empty arrays and empty objects
function truthyObjLoop(user){
for(var key in user){
if( user.hasOwnProperty(key) && (!user[key] ||
     Number.isNaN(user[key]) ||
     (user[key] instanceof Array && !user[key].length) ||
     (user[key] instanceof Array ==false && user[key] instanceof String == false && !Number.isInteger(user[key]) && !Object.keys(user[key]).length) ))
    delete user[key];
}
return user;
}
}

Comment: You don't need the extra `isNan()` test. `NaN` values are falsy. Try this in the console: `console.log( (0/0), !!(0/0), !!false );` It will log `NaN false false`. (The `!!` converts falsy values to `false` and truthy values to `true`.)


Where is the Nightmare's key in Catfish's Maw?

Question: I have completed everything I can think of, and my map shows no more rooms with Chests in, yet I do not have the Nightmare's key.
Where is it in this dungeon?
Answer:

So whether you decided to fight gohma or not, backtrack down a screen, right, and up two screens to get back to where we first fought
  master stalfos. Continue right a screen and you'll see a staircase
  here. If we head down this staircase at this point in time and go
  through the underground sequence, we will resurface and nearby we'll
  find an owl statue that states, "Dive under where torchlight beams do
  cross…" The rest of the area leads to the same dead end that the
  stairs by Gohma led to. So, backtrack to the room just to the right of
  where we first fought Master Stalfos.

From here walk up a screen and push the central block once again before heading left a screen. Defeat or avoid the enemies and head up
  a screen. Defeat the four water tektites found in this room and then
  if you look at the walls, you'll see four torchlights. If you were to
  connect the ones on opposite sides with lines, they'll meet right in
  the center of the deep water. So just as the owl statue stated, let's
  dive underneath.
Make your way through this underwater area, defeating enemy bloopers along the way. These are another example of Mario enemies
  found within this title. Resurface on the next screen to find yourself
  in a new part of the dungeon. Use the hook shot to grab onto the latch
  and extend a bridge across. Walk over to the treasure chest and open
  it to get the Nightmare's Key. Backtrack through the underwater area.

Map Here
Comment: Boo. That's irritating. But yay, I have a key now. :)
Comment: I didnt know if you understood what I meant so there is a more elaborate description :)
Answer: Go to the room with four Water Tekites. Destroy them, dive in the dark blue water, and do the rest to get the nightmare key.


Is using a wire nut and push in connector in the same "bus" okay?

Question: I'm adding an outlet to the attic and needed to tap into the existing line circuit.
The wire nut in blue had 5 wires in it and couldn't support a 6th (which probably isn't a great idea anyway). So I split it off into a push in connector. Is this okay? Is the way I did it with a small piece of wire bridging them both perfectly fine or should I get a bigger wire nut?
Comment: Depends on the nature of the push-in connector.   Where'd you get it?   What is it?  Is it UL listed for the gauge of the wire you used it on???  (12AWG)
Comment: Totally code compliant, then. But stop stripping your wires with a knife. (Half kidding. You don't want to nick the copper when you strip. A real wire stripper costs nearly nothing and does a clean job.)
Comment: @KyleB -- you can tell that was done by a sober individual (and probably a real electrician) because the circuits have actual labels on them. And it's extremely unlikely that it's 'just one circuit' -- note the multiple bundles of neutrals.
Comment: @kyle b that looks like a possible pro job with 1 exception all of the grounds should be common and connected to the box (a code requirement since there are splices)  the plastic clamps look like raco insiders (I haven't seen these used by non pros)  I would also say there are at least 3 circuits in this box because of the neutral bundles , in whatever case it is industry standard  for this many circuits with a listed type of box,  and I can say this as a licensed sparky. Other than the lack of a common ground to the box it looks ok to me.
Comment: @KyleB Yes it is UL listed for the gauge of wire I am using (12AWG)
Comment: In terms of 'does it work' it's fine.  But personally I do not trust any 'stab' type connecter.  They just don't have the positive contact that a screwing-type connector would.  Be that a wire nut or (preferable) a bus bar.  Anyhow -- I'm not a licensed electrician but I'm an electrical engineer -- Not sure the code limits but man, that junction box has alotta branches for just one circuit.  What a rats nest mess.   Not sure I'd go adding yet another load to it.  No way that was done by an actual electrician.  At least not a sober one.
Comment: If that wiring bothers you, you can get [push-in connectors with more holes](https://www.wago.com/gb/installation-terminal-blocks-and-connectors/compact-splicing-connector/p/2273-208).
Answer: Those look like lever locks (32a listed) notice the orange handles on the back side,
if you pull those away from the body the wire can be removed.
As far as code it will probably never be challenged but a purest would say both the hot and neutral need to be the same splicing method.  that code segment is in parallel feeds not applicable in this case.
I am not a fan of backstabs. I have seen two many failures on 15 amp circuits.
The lever locks have a better contact area and almost have me changing as I have not had a lever lock failure (I have mostly used them on lighting fixtures), the other thing with a lever lock is each wire is secured and clamped I have not had a wire pull out .
So would this be code compliant? YES
If those are lever locks would I use them as a pro that hates backstabs? Yes
I think lever locks are better for non pros as each wire is individually clamped and I have never seen one assembled incorrectly, where I have seen lots of wire nuts not properly twisted or 1 wire loose (even from pros).


Why is this in 2nd Normal Form

Question: Given a table consisting of the attributes R = [U, V, W, X, Y, Z] and the functional dependencies: F = {UV->WXYZ, VW->Y, Y->Z}
I have determined that the possible candidate key for the table R is UV.
When it comes to determinig the highest normal form I think that the table is in 1st normal form. 1NF because part of a key determines a value in the table (VW -> Y). According to the answers that the teacher provided the table is in 2nf can anyone clarify why this is?
Answer: You said it yourself, part of a key has to determine another value. If your key is UV, then U or V have to determine something else to break 2NF. The fact that VW has V in it is irrelevant in the definition, since it has to be that U by itself or  V by itself have to determine something.
Good luck tomorrow!
Answer: A table in Second Normal Form is also in First Normal Form--that is one of the requirements for Second Normal Form (http://en.wikipedia.org/wiki/Second_normal_form).  If every column (W, X, Y, and Z) are all dependent on the entire composite key (U and V), then the table is in second normal form.  If one column only needed part of the key and would duplicate for the same value of that one part, regardless of the value of the second part, then the table is NOT in Second Normal Form.
Without any knowledge of the data, this is the best answer that can be provided.

Why is this in 2nd Normal Form


In Ansible, how do I execute a command via Git-bash window?

Question: Ansible v2.11, Windows 2019 target
I want to execute a command in a Git-bash window, like this, where <some_command can be anything I want to execute, e.g., ls or pwd for argument's sake.
- block:
  - name: Check if git-bash exists
    win_stat:
      path: 'c:\Program Files\Git\git-bash.exe'
    register: git_bash_st
  - name: Ensure that git-bash exists
    assert:
      that:
      - git_bash_st.stat.exists
  - name: "Check if {{ yesterdays_files }} exists"
    win_stat:
      path: "{{ yesterdays_files }}"
    register: yester_st
  - name: "Execute a command in the git-bash shell"
    win_command: "git-bash.exe ls {{ yesterdays_files }}"
    args:
      chdir: "C:\\Program Files\\Git"
    when: yester_st.stat.exists

However, the task just hangs and doesn't proceed. Any clues?
Answer: You could try the win_shell module with an extra arg ˋexecutable='c:\Program Files\Git\git-bash.exe'ˋ . You have used an extra arg ˋchdirˋ allready.
I do not know git-bash at all, but the command for git-bash might be only ˋls blaaˋ then.
Comment: I tried this and this hangs the same way as my task. Thanks


Run a jar file as a linux service

Question: I want to know how i can run a .jar file as a linux service. I am new to linux, so most of the online resources were not of much help.. Any input regarding this will be helpful..
Comment: @ manil : your question is exact duplicate of http://stackoverflow.com/questions/1311268/tool-for-creating-a-java-daemon-service-on-linux
Comment: What do you mean by run as Linux service? Can you please elaborate ?
Answer: It depends how you want to run jar.  You can always run a java program as background task.
In bash
<code>$nohup <path to java>  -classpath <classpath> classname  &
</code>
It looks like Java service wrapper  is a solution that could fit your case.
Comment: Java service wrapper is a paid service..is there a free alternative to this??
Comment: I want to run the jar as a service so that it gets started on system start up an d closes at system shut down. I would prefer running it as a service as i have complete control over the application.
Comment: @ manil did you check http://stackoverflow.com/questions/1311268/tool-for-creating-a-java-daemon-service-on-linux ; Offtopic.

Run a jar file as a linux service


Problems with audio and video Muxing

Question: I'm modifying an audio encoder example for write audio and video both. I'm trying to get video raw data from device display by MediaProjection and get audio raw data from Microphone by AudioRecord. Then I will send them to MediaCodec(I will set two Codec instance).
After that I will send the video data and audio data to MediaMux to get a mp4 file. I have any problems:

In result I get a file with perfect video track but terrible audio track. Audio track have plays with intervals at the beginning of track and without pauses but very fast at the end.
When I play video with android MXPlayer all ok, but when I play with PC players (Windows Media or Media Player Classic) audio plays like on MXPlayer but video don't plays - shows only first frame.

Sample of result video:
Part of code:
/**
* Method run of EncoderTask
*/
public void run() {
    if (mIsInitialized) {
        switch (type) {
            case ENCODE_AUDIO_FRAME:
                if (!mStopReceived) {
                    _offerAudioEncoder(mAudioData, presentationTimeNs);
                    mDrainHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mEncodingService.submit(new EncoderTask(Encoder.this, EncoderTaskType.ENCODER_VIDEO_FRAME));
                        }
                    }, DELAY_MILLIS); // 10 milliseconds
                }
                break;
            case ENCODER_VIDEO_FRAME:
                if (!mStopReceived) {
                    encoder._offerVideoEncoder();
                    mDrainHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mEncodingService.submit(new EncoderTask(Encoder.this, EncoderTaskType.ENCODE_AUDIO_FRAME));
                        }
                    }, DELAY_MILLIS); // 10 milliseconds
                }
                break;
            case FINALIZE_ENCODER:
                finalizeEncoder();
                break;

        }
        // prevent multiple execution of same task
        mIsInitialized = false;
        mEncodingServiceQueueLength -= 1;
    } else {
        Log.e(TAG, "run() called but EncoderTask not initialized");
    }
}

public void _offerVideoEncoder() {
    Log.d(TAG, "Offer video");
    if (mStopReceived) {
        closeVideoEncoder();
        Log.d(TAG, "Offer video - stop");
    } else {
        drainEncoder(mVideoEncoder, mVideoBufferInfo, mVideoTrackIndex, false, "video");
        Log.d(TAG, "Offer video - drain");
        if (mStopReceived) {
            closeVideoEncoder();
            Log.d(TAG, "Offer video - stop");
        }
    }
}

public void processAudioFrame() {
    long audioPresentationTimeNs = System.nanoTime();
    byte[] thisBuffer;
    if (mDataBuffer.isEmpty()) {
        thisBuffer = new byte[mSamplesPerFrame];
    } else {
        thisBuffer = mDataBuffer.poll();
    }

    mReadResult = mAudioRecorder.read(thisBuffer, 0, mSamplesPerFrame);
    if (VERBOSE) Log.i(TAG, "FillBuffer       real: " + String.valueOf(mBufferWriteIndex)
                + " - " + String.valueOf(mBufferWriteIndex + mReadResult - 1));

    if (mReadResult != AudioRecord.ERROR_BAD_VALUE && mReadResult != AudioRecord.ERROR_INVALID_OPERATION) {
        mBufferWriteIndex = mBufferWriteIndex + mReadResult - 1;
        mTotalFramesWritten++;
        if (mAudioEncoder != null) {
            mAudioEncoder.offerEncoder(thisBuffer, audioPresentationTimeNs);
        }

        if (!mIsRecording && mAudioRecorder != null) {
            mAudioRecorder.setRecordPositionUpdateListener(null);
            mAudioRecorder.release();
            mAudioRecorder = null;
            Log.i(TAG, "stopped");
        }
    } else {
        Log.e(TAG, "Read error");
    }
}

private void _offerAudioEncoder(byte[] input, long presentationTimeNs) {
    if (audioBytesReceived == 0) {
        mAudioStartTime = presentationTimeNs;
    }

    mTotalInputAudioFrameCount++;
    audioBytesReceived += input.length;
    if (mEosSentToAudioEncoder && mStopReceived || input == null) {
        logStatistics();
        if (mEosReceived) {
            Log.d(TAG, "EOS received in offerAudioEncoder");
            closeAudioEncoder();
            mEosSentToAudioEncoder = true;
            if (!mStopReceived) {
                prepareAudioEncoder();
            } else {
                mEncodingService.shutdown();
            }
        }
        return;
    }
    // transfer previously encoded data to muxer
    drainEncoder(mAudioEncoder, mAudioBufferInfo, mAudioTrackIndex, false, "audio");
    sendFrameToEncoder(input, presentationTimeNs);// send current frame data to encoder
}

private void sendFrameToEncoder(byte[] input, long presentationTimeNs) {
    try {
        ByteBuffer[] inputBuffers = mAudioEncoder.getInputBuffers();
        int inputBufferIndex = mAudioEncoder.dequeueInputBuffer(-1);
        if (inputBufferIndex >= 0) {
            ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
            inputBuffer.clear();
            inputBuffer.put(input);
            if (mAudioSoftwarePoller != null) {
                mAudioSoftwarePoller.recycleInputBuffer(input);
            }
            long presentationTimeUs = (presentationTimeNs - mAudioStartTime) / 1000; // in microseconds
            if (mEosReceived) {
                mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, input.length, presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                closeAudioEncoder();
                mEosSentToAudioEncoder = true;
                if (mStopReceived) {
                    mEncodingService.shutdown();
                }
            } else {
                mAudioEncoder.queueInputBuffer(inputBufferIndex, 0, input.length, presentationTimeUs, 0);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

private void drainEncoder(MediaCodec encoder, MediaCodec.BufferInfo bufferInfo, TrackIndex trackIndex, boolean endOfStream, String type) {
    final int TIMEOUT_USEC = 100;
    ByteBuffer[] encoderOutputBuffers = encoder.getOutputBuffers();
    while (true) {
        int encoderStatus = encoder.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
        if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
            if (!endOfStream) {
                if (VERBOSE) Log.d(TAG, "INFO_TRY_AGAIN_LATER " + type + " out of while");
                break;      // out of while
            } else {
                if (VERBOSE) Log.d(TAG, "no " + type + " output available, spinning to await EOS");
            }
        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            // not expected for an encoder
            if (VERBOSE) Log.d(TAG, "INFO_OUTPUT_BUFFERS_CHANGED " + type);
            encoderOutputBuffers = encoder.getOutputBuffers();

        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            // should happen before receiving buffers, and should only happen once
            if (mMuxerStarted) {
                throw new RuntimeException("format changed after muxer start");
            }
            MediaFormat newFormat = encoder.getOutputFormat();
            Log.d(TAG, "encoder output format changed: " + newFormat + ".");

            // now that we have the Magic Goodies, start the muxer
            synchronized (mMuxer) {
                trackIndex.index = mMuxer.addTrack(newFormat);
                numTracksAdded++;
                Log.d(TAG, "Added " + type + " track index: " + trackIndex.index);
                if (numTracksAdded == TOTAL_NUM_TRACKS) {
                    mMuxer.start();
                    mMuxerStarted = true;
                    Log.d(TAG, numTracksAdded + " tracks added. Muxer started");
                    break;
                }
            }
        } else if (encoderStatus < 0) {
            Log.w(TAG, "unexpected result from " + type + " encoder.dequeueOutputBuffer: " +
                    encoderStatus);
        } else {
            if (encodedData == null) {
                if (VERBOSE) Log.d(TAG, "drainEncoder(" + endOfStream + ") " + type + " encodedData == null");
                throw new RuntimeException("encoderOutputBuffer " + encoderStatus +
                        " was null");
            }
            if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                // The codec config data was pulled out and fed to the muxer when we got
                // the INFO_OUTPUT_FORMAT_CHANGED status.  Ignore it.
                if (VERBOSE) Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG");
                bufferInfo.size = 0;
            }
            if (bufferInfo.size != 0) {
                if (!mMuxerStarted) {
                    if (VERBOSE) Log.d(TAG, "drainEncoder(" + endOfStream + ") " + type + " Muxer not started");
                    throw new RuntimeException("muxer hasn't started");
                }
                // adjust the ByteBuffer values to match BufferInfo (not needed?)
                encodedData.position(bufferInfo.offset);
                encodedData.limit(bufferInfo.offset + bufferInfo.size);
                synchronized (mMuxer) {
                    mMuxer.writeSampleData(trackIndex.index, encodedData, bufferInfo);
                }
            }

            encoder.releaseOutputBuffer(encoderStatus, false);

            if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                if (!endOfStream) {
                    Log.w(TAG, "reached end of stream unexpectedly");
                } else {
                    if (VERBOSE) Log.d(TAG, "end of stream reached");
                }
                break;
            }
        }
    }
    long endTime = System.nanoTime();
}

Comment: You did not calculate the right pts for video and audio.
Answer: I think in drainEncoder function you missed
ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
before
       if (encodedData == null)

Problems with audio and video Muxing


Different behaviour of Nautilus in Unity Launcher and Gnome 3 shell

Question: Preparing for the change from Unity to Gnome Shell in Ubuntu 17.10 I have installed Ubuntu Gnome on a spare PC.  Most differences in default behaviour are either acceptable or can be modified to suit my personal taste, but I can't figure out how get the Files launcher in the Activities Dash to behave as it did under Unity in 17.04 (and before).to org.gnome.Nautilus.
Specifically, In Unity the context menu after a right click includes shortcuts to the folders listed in ~/.config/gtk-3.0/bookmarks. In Ubuntu Gnome these shortcuts don't show in the context menu.  I tried adding Actions of the form
[Desktop Action Documents]
Name=Documents
Exec=nautilus --new-window  ~/Documents

to org.gnome.Nautilus.desktop, but although they showed in the context menu, Nautilus never opened the folder.
Also I had to do this to the system file /usr/share/applications/org.gnome.Nautilus.desktop since when I put a copy in ~/.local/share/applications and modified it (so it also used a different icon) the system version was used in the Dash.  (This technique worked with Unity.)
What have I missed?
Comment: I've now installed Ubuntu 17.10 and can further clarify my question.  Launchers with context menus that I create work fine, but not if I try to use a modification of one of the launchers installed at installation---e.g. Files or Software.  I can not delete the original launcher and replace it with one of my own.  When I tried that with Files, launching nautilus just reinstalled the originally installed launcher in the Dock. Editing the desktop file in /usr/share/applications doesn't work either.  I can change the icon but the added Desktop Actions don't appear in the right click context menu.
Comment: I've been doing some more searching and I was reminded that the correct name for what I want is a quick list.  However I still haven't found how to add quick lists to desktop files in /usr/share/applications, though one in ~/.local/share/applications do work.
Answer: After some more googling with some different variations of my search terms I have found a "solution," or more likely, just a work around that may not work for everyone.  Editing copies of the desktop files from /usr/share/applications that I put in ~/.local/share/applications I changed the line
DBusActivatable=true

to
DBusActivatable=false

and now every thing works.  I must admit I don't completely understand what this does. Also, be warned I'm using an X11 session.  I'll try to test this under Wayland, but I suspect I'll have some different problems because I use gksudo to launch Synaptic and its ilk.


GeoDjango on Windows: Try setting GDAL_LIBRARY_PATH in your settings

Question: I've done this a dozen times before, but something isn't working this time..
Following the docs:
https://docs.djangoproject.com/en/1.11/ref/contrib/gis/install/#windows
I'm trying to set up GeoDjango on a Windows machine (this one is a virtual windows 10 set up on paperspace.com). There seems to be a problem with my PATH settings, but I can't figure out what it is. I've run the commands highlighted in the instructions. I've checked my PATH variables and everything seems ok. I've tried pointing them to both the 32-bit and 64-bit versions of OSGeo4Win. Regardless, I get the following output every time:
C:\Python\lib\site-packages\floppyforms\__init__.py:21: UserWarning: Unable to import floppyforms.gis, geometry widgets not available
  "Unable to import floppyforms.gis, geometry widgets not available")
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 337, in execute
    django.setup()
  File "C:\Python\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Python\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\Python\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Python\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Python\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Python\lib\site-packages\django\db\models\base.py", line 330, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Python\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Python\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python\lib\site-packages\django\db\utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python\lib\site-packages\django\db\utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Python\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Python\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 5, in <module>
    from .features import DatabaseFeatures
  File "C:\Python\lib\site-packages\django\contrib\gis\db\backends\postgis\features.py", line 1, in <module>
    from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures
  File "C:\Python\lib\site-packages\django\contrib\gis\db\backends\base\features.py", line 4, in <module>
    from django.contrib.gis.db.models import aggregates
  File "C:\Python\lib\site-packages\django\contrib\gis\db\models\__init__.py", line 3, in <module>
    from django.contrib.gis.db.models.aggregates import *  # NOQA
  File "C:\Python\lib\site-packages\django\contrib\gis\db\models\aggregates.py", line 1, in <module>
    from django.contrib.gis.db.models.fields import ExtentField
  File "C:\Python\lib\site-packages\django\contrib\gis\db\models\fields.py", line 3, in <module>
    from django.contrib.gis import forms, gdal
  File "C:\Python\lib\site-packages\django\contrib\gis\forms\__init__.py", line 3, in <module>
    from .fields import (  # NOQA
  File "C:\Python\lib\site-packages\django\contrib\gis\forms\fields.py", line 4, in <module>
    from django.contrib.gis.geos import GEOSException, GEOSGeometry
  File "C:\Python\lib\site-packages\django\contrib\gis\geos\__init__.py", line 5, in <module>
    from .collections import (  # NOQA
  File "C:\Python\lib\site-packages\django\contrib\gis\geos\collections.py", line 11, in <module>
    from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin
  File "C:\Python\lib\site-packages\django\contrib\gis\geos\geometry.py", line 11, in <module>
    from django.contrib.gis import gdal
  File "C:\Python\lib\site-packages\django\contrib\gis\gdal\__init__.py", line 28, in <module>
    from django.contrib.gis.gdal.datasource import DataSource
  File "C:\Python\lib\site-packages\django\contrib\gis\gdal\datasource.py", line 39, in <module>
    from django.contrib.gis.gdal.driver import Driver
  File "C:\Python\lib\site-packages\django\contrib\gis\gdal\driver.py", line 5, in <module>
    from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
  File "C:\Python\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module>
    from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
  File "C:\Python\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 44, in <module>
    'GDAL_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)
django.contrib.gis.gdal.error.GDALException: Could not find the GDAL library (tried "gdal111", "gdal110", "gdal19", "gdal18", "gdal17"). Try setting GDAL_LIBRARY_PATH in your settings.

Does anyone have any ideas?
UPDATE:
I went to the store and bought a new laptop and I am still running into the same issue. Could it be an versioning issue with some of the GeoDjango dependencies? I'm at a loss for what to do, but it's kind of an emergency for me.
Answer: The issue ended up being a version mismatch between Django and GDAL. Django was not searching for the correct file name (gdal202.dll in my case).
Fixing it required me to add str('gdal202') to the following file on line 26:
(Python Root)\Lib\site-packages\django\contrib\gis\gdal\libgdal.py
Note that if you are working in a Virtual Environment, then Python Root will actually be wherever that is ie: Users\YourName\Envs\project
If this issue reoccurs, you can look through your C:\OSGeo4W\bin directory to figure out which gdalxxx.dll it is that Django needs to search for.
In addition, make sure that you are using the 32-bit versions of Python and OSGeo4Win. Otherwise, you may see the same failure.
Comment: worked for me with gdal3.5.0.dll
Comment: The required filename for my case was gdal304.dll
Comment: Commenting to add that 1.11.13 only writes in up to versions ('gdal201.dll'), so I think this fix is required for all versions of 1.11
Comment: Right now this is required for Django 2.2.6 as well. The required filename as of today is `gdal204.dll`.
Answer: Adding
GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal202'

to the django settings worked for me
Comment: Keep in mind that this approach will be disruptive if you switch between Windows and Mac or Linux developing environments.
Comment: what django settings, like what file?
Comment: in my project it is located at project_folder/config/settings/base.py.
More about django settings https://docs.djangoproject.com/en/2.0/ref/settings/  https://docs.djangoproject.com/en/2.0/topics/settings/
Comment: Like @AdamStarrh mentions, this is disruptive if your application is shared within multiple OSs (developers for example). For MacOS specifically, the cause of this is likely because GDAL has been installed through homebrew, which installs libraries to its own "opt" folder. Symbolic linking this to `/usr/local/lib` fixes this issue.
Answer: In addition to the previous comments. You might have a [WinError 127] The specified procedure could not be found.
This appears due to having multiple sqlite3.dll on your system. If the path hits those first a conflict appears for gdal202.
You can extend adam starrh answers by adding also a change of working directory.
#Set working directory to actual working directoy of gdal
#This is required to prevent any conflicts with older SQLITE versions,
#f.e. in python path
#Prevents error in GDAL 202
#BASE_WORKINGDIRECTORY to change it back later if you need to
BASE_WORKDIRECTORY = os.getcwd()
os.chdir(os.path.dirname(lib_path))

# This loads the GDAL/OGR C library
lgdal = CDLL(lib_path)

Comment: this is in `Lib\site-packages\django\contrib\gis\gdal\libgdal.py`
Comment: I'm getting [WinError 127] error too, but the suggested approach does not solve the problem, unfortunately. When calling makemigrations from PyCharm, I get the error "The procedure entry point sqlite3_column_origin_name could not be located in the dynamic link library C:\OSGeo4W64\bin\gdal202.DLL". Haven't been able to find any solution for this on the net
Comment: Update: I had to do this too after installing GDAL via pip from: https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal
You're a life saver!!
Answer: I got same error.
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings.

First, insall OSGeo4W
, and then add following code in your settings.py.
import os
if os.name == 'nt':
    import platform
    OSGEO4W = r"C:\OSGeo4W"
    if '64' in platform.architecture()[0]:
        OSGEO4W += "64"
    assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W
    os.environ['OSGEO4W_ROOT'] = OSGEO4W
    os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal"
    os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj"
    os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH']

and run python manage.py check
if you got the error still, please go to C:\OSGeo4W64 or C:\OSGeo4W.
There you can find gdalxxx.dll. please rename the file name to 'gdal202' or 'gdal203' in error message.
Please run python manage.py check, That must work.
Comment: am I glad I scrolled to the end... But I don't really understand why this works and the above does not. Still, very grateful. Thx
Comment: Turns out it's down to adding `c:\osgeo4w64\bin` to the windows path. But strange that setting `GDAL_LIBRARY_PATH` to the very file doesn't work
Comment: It works because you are giving the GDAL file a name that matches the specific filename queries that Django is looking for.
Answer: I had the same problem in Django in a virtual environment. What solved my problem was:

In settings.py add the path to the gdalxxx.dll your app is trying to use, for me it was
 GDAL_LIBRARY_PATH = r'C:\Users\<User>\Documents\<proj>\Lib\site-packages\osgeo\gdal301'

This alone could possibly solve your problem, but Django may still complain about missing GEOS library, in that case:

In settings.py add the path to the geos_c.dll your app is trying to use, for me it was:
GEOS_LIBRARY_PATH = r'C:\Users\<User>\Documents\<proj>\Lib\site-packages\shapely\DLLs\geos_c'

Comment: Keep in mind that this approach will be disruptive if you switch between Windows and Mac or Linux developing environments.
Comment: Setting the path in settings worked for me as well
Answer: If you're using the Django tutorial and installing GDAL via OSGeo4W, when modifying the Windows environment, ensure you've defined the proper Python and OSGeo4W versions.
E.g., when installing 64-bit OSGeo4W, the environment path should be set:
set OSGEO4W_ROOT=C:\OSGeo4W64

and for Python 3.5.2:
set PYTHON_ROOT=C:\Python36

Be sure you're not confusing Python installations in a virtualenv with the system Python.
Only install Django after you've properly modified the environment.
Comment: ensure the path environment assignment is reflective of the Python version you'll be using in the active virtual env
Comment: Can you please elaborate on what you mean by "be sure you're not confusing Python installations in a virtualenv with the system Python"?
Answer: For me this issue was solved on Windows simply by adding the path to the osgeo python package to the Environment variables (C:\Python36\Lib\site-packages\osgeo). It seems that after doing this, django managed to find the gdal202.dll file.
Answer: Solution:

Install GDAL from pip: pip install GDAL, if does not work install
it from wheel: https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal
a) If you use virtual environment just add this code to settings.py:
os.environ["PATH"] += os.pathsep + BASE_DIR + '\\venv\\Lib\\site-packages\\osgeo'
b) Else add this code:
from distutils.sysconfig import get_python_lib
os.environ["PATH"] += os.pathsep + get_python_lib() + '\\osgeo'
Answer: When makemigretions ,it appare an issue like this
enter image description here
Maybe the dll(gdal202.dll) lib doesn't work.
so we can replace the whole GDAL lib with GDAL-whl-package from https://download.lfd.uci.edu/pythonlibs/r5uhg2lo/GDAL-2.3.2-cp36-cp36m-win_amd64.whl
download this whl package, rename it to GDAL-2.3.2-cp36-cp36m-win_amd64.whl.zip
enter image description here
extract the osgeo folder to one place (D:\ProgramData\osgeo) and modify the GDAL_DATA PROJ_LIB and path to it's subfolder
which means change Windows environment
from
set OSGEO4W_ROOT=C:\OSGeo4W
set PYTHON_ROOT=C:\Python3X
set GDAL_DATA=%OSGEO4W_ROOT%\share\gdal
set PROJ_LIB=%OSGEO4W_ROOT%\share\proj
set PATH=%PATH%;%PYTHON_ROOT%;%OSGEO4W_ROOT%\bin
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /f /d "%PATH%"
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v GDAL_DATA /t REG_EXPAND_SZ /f /d "%GDAL_DATA%"
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROJ_LIB /t REG_EXPAND_SZ /f /d "%PROJ_LIB%"

to
set OSGEO4W_ROOT=D:\ProgramData\osgeo
set PYTHON_ROOT=C:\Python3X
set GDAL_DATA=%OSGEO4W_ROOT%\data\gdal
set PROJ_LIB=%OSGEO4W_ROOT%\data\proj
set PATH=%PATH%;%PYTHON_ROOT%;%OSGEO4W_ROOT%\bin
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /f /d "%PATH%"
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v GDAL_DATA /t REG_EXPAND_SZ /f /d "%GDAL_DATA%"
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROJ_LIB /t REG_EXPAND_SZ /f /d "%PROJ_LIB%"

PS : Don't forget to rename "D:\ProgramData\osgeo\gdal203.dll" to "D:\ProgramData\osgeo\gdal202.dll"
Answer: issue has been fixed by applying the fixes in this link
Comment: Keep in mind that this approach will be disruptive if you switch between Windows and Mac or Linux developing environments.
Comment: Yes, thats why Pathlib and similar functions can help to remove such concerns especially when go to production deployment , What I have provided doesn't fix the issue completely, I have faced another issue when updating the multipolygon filed and it solved by applying updated fixes (see the updated post)


12.04 LTS on Dell PowerEdge T300 installs, but won't boot

Question: I'm trying to get 12.04 LTS 64-bit up and running on a Dell PowerEdge T300 Server with the Dell SAS 6/iR RAID controller (LSI SAS1068E chipset).
Ubuntu installs just fine, doesn't report any errors, sees the RAID mirrors as drives, everything seems normal, but fails to boot up after the installation. It reports no boot device. The /boot partition is on /dev/sda1 and is marked as bootable, and when I installed Ubuntu, I told it to install grub to the MBR.
Any suggestions for what I should check next?
Answer: I have a similar problem with a Dell PowerEdge SC440 with the Dell SAS 5 controller. I wanted to upgrade my hard disks from 2x160 GB in RAID-1 (mirroring) to 2x2TB in RAID-0 (striping). Creating the "virtual disk" worked, installing Ubuntu as well, but after rebooting the BIOS doesn't recognise the "virtual disk" as a bootable device.
So, in my case, the problem is not with OS installation, but with the SAS and BIOS "integration". In the Setup Utility, under Boot Order, you should see an entry with something like (in my case) "#0240 ID00 LUN0 Dell    VIRTUAL". If you don't see this, the problem is not with Ubuntu, but with SAS/BIOS.
I got things working by reconfiguring the drives in RAID-1. The BIOS then picked up the virtual drive and booting works.
Sorry I don't have an immediate solution for you, but I hope it helps troubleshooting your problem.
Cheers,
bert
Answer: I want to share with you my experience with ubuntu 14.04 under DELL Poweredge T110.
I have not a raid configuration, i wanted to add just more space so i added a new SAS Disc (450 GB - 15000 RTM) and evry time i connect the new disc, ubuntu won't to start (i got: initramfs)...
After weeks of searching the reason, i discovred that DELL SAS Controller is very slow to start, so ubuntu could not see the new disc properly, That was the reason.
How did i solved this ?
Simply by:
changin the rootdelay value in grub linke this:
sudo nano /etc/default/grub
GRUB_CMDLINE_LINUX="rootdelay=90"

Then update the grub:
sudo update-grub

finally, reboot.


What causes "old smell" in a clean but older house?

Question: Older homes in warmer climates seem to have a somewhat common smell to them, even after cleaning them. Does someone with experience renovating such homes know what tends to be the cause of these odors?
I am not talking about smells from plumbing, the kitchen or even pets, but the smell that you can sometimes find in wooden sheds, back-country cabins or generally homes built in the 60s and 70s. Sometimes it reminds me of rodents, but only faintly.
I am about to do some renovations, and thought that if this is something that can be included, it would be worth it. For example if this was caused by wood or insulation that somehow got wet in the walls, we could clean out that wall cavity as part of a gut renovation...
Comment: Well, for one thing,  smell is highly subjective.  Asking for help from people who smell other things doesn't get you very far.
Comment: Mold / moisture
Comment: @Carl - Not really; there is general consensus on "bad" smells (e.g. sewage) and "good" smells (e.g. roses). I've found the same to be the case with houses, where things can smell new, clean, musty, etc... I've changed the title and body to be a bit more clear.
Comment: Vote to close - too broad.
Comment: How would you improve it? The fact that it's hard to trace is exactly the problem I'm asking about.
Comment: Just found [this thread](http://diy.stackexchange.com/questions/42695/what-could-cause-my-house-to-smell-musty-after-coming-back-from-vacation?rq=1). Seems to be somewhat related. Still, is there something unique about houses built in the 60s and 70s that make them more susceptible to it and that could be corrected during a renovation?
Comment: See [this meta post](http://meta.diy.stackexchange.com/q/1012/2196) for the policy on smell questions.
Comment: I think your title is missing an "m" right before "old".   "Mold" generally rhymes with "roof or water entry problems".
Answer: Normally it's the things you can't see.
Moisture building up behind walls or creeping up through micro-fractures in the foundation will cause mold and mildew to grow fairly quickly.
A fairly cheep way to prevent this is to use a powerful dehumidifier to really dry out offending spaces.
Avoid carpet, as no matter how clean it is, will always harbor bacteria that can cause unpleasant odors.
Old insulation can also be a big source of a constant odor that, while to too offending, is incredibly pervasive.
And finally, mothballs. Some people used to use them as a "catch all" solution to pest problems, and used them so much that the very material of the home absorbed the smell, similar to the way homes that housed prolific tobacco users can smell for years after even with deep cleaning.
Comment: You forgot ghosts.
Comment: "Sometimes it reminds me of rodents, but only faintly." - You may be on to something with mothballs.


Linux Loopback UDP Sockets For IPC

Question: Currently, I have working, functioning code to pass messages between two programs I have written.  Here's the scheme I'm using:
Program A

a_tx_socket -> Send Data on 127.0.0.1, Port A
a_rx_socket -> Receive Data on 127.0.0.1, Port B

Program B

b_tx_socket -> Send Data on 127.0.0.1, Port B
b_rx_socket -> Receive Data on 127.0.0.1, Port A

Note that I call bind() on the sockets that receive data (a_rx_socket and b_rx_socket).  Each socket is created with a call to the socket() system call.
Now, for my question... is there a way to get rid of one port?  Namely can I send/receive on the loopback address using only one port?  How would I make sure that Program A/B does not receive data that it sent?  Is this worth exploring for any reason (performance/maintainability/fun/etc)?
Comment: why dont you use PORT A to send/recv by program A and PORT B to send/recv by program B ?
Answer: Only one process at a time can bind to a given socket address. Subsequent attempts to bind will get EADDRINUSE, meaning that the address is already in use.
For ip addresses, the socket address is made up of the port and the IP address. See 'man 7 ip' for details.
Therefore, you need two ports, because otherwise only one of your two programs would be able to bind (and therefore receive packets).
If your pair of programs is always going to be on the same machine, you might want to use unix domain sockets instead, as they would be more efficient for that use case.
Comment: Thanks for the quick response, that's what I was expecting to run into.

Linux Loopback UDP Sockets For IPC


Probability of getting at most 3

Question: In tossing four fair dice, what is the probability of tossing, at most one 3?
This is the beginning of the solution I have:
The number of outcomes of tossing four dice is $6 \times 6 \times 6 \times 6 =6^4$.
Outcomes of getting at most one 3 = outcomes of getting no 3 $ +$ outcomes of getting one 3.
The number of outcomes of getting no 3 is $5 \times 5 \times 5 \times 5 =5^4$.
The number of outcomes of getting one 3 is $4 \times 5^3$.
But I don't understand why it's $4\times 5^3$. Can any one assist?
Comment: There are $4$ places you might have gotten the $3$ and $5$ choices for each of the other $3$ places.
Answer: To get the number of outcomes with exactly one 3:

Choose one tossing which is going to result in a 3. This can be done in $\binom{4}{1}$ ways because there are 4 tossings in total.
Since the other tossings must not contain a 3, there are 5 numbers available for them. Since there are 3 tossings left, the number of ways is $5^3$

Using the multiplicative property you get $4 \cdot 5^3$.
Comment: Like the permutation 4 C 1?
Comment: @ErinA Yes, indeed.
Comment: @ErinA Have I answered your question?

Probability of getting at most 3


Line integral. Conservative vector field

Question: Please help me with solution of the given problem:
Let $\gamma_1$ and $\gamma_2$ be the circles of $R^2$ of radius $r=2$, centered at the points $(0,0)$ and $(8,6)$ respectively. Assume that $\gamma_1$ is clockwise oriented and that $\gamma_2$ is counterclockwise oriented. Let $F\colon R^2\setminus \{(0,0)\} \to R^2$ be a conservative vector field of class $C^1$. Denote by $C_1$ and $C_2$ the line integrals of $F$ along $\gamma_1$ and $\gamma_2$ respectively. Decide which on of the following is true:
(a) $C_1$ $\ne$ $0$ and $C_1$ = -$C_2$
(b) $C_1$ = $C_2$
(c) $C_1$ $\ne$ $0$ and $C_1$ $\ne$ $C_2$
(d) none of the other answers is correct
(e) $C_1$ $\ne$ $0$ and $C_1$ = $C_2$
Comment: Remind yourself of the definition of a *conservative* vector field. For a closed contour $\gamma$, what is the value of $\oint_\gamma \vec{v} \dot  \;\text{d}s$ if $\vec{v}$ is conservative?
Answer: As far as I can see, there's nothing in the question that rules out having $F$ be identically zero, in which case $C_1$ would be zero; that immediately rules out (a), (c), and (e). And distinguishing between (b) and (d) just requires you to recall whether the theorem on conservative vector fields holds when there's a discontinuity in the vector field.


Java test adding values from an Enum to an arrayList

Question: The arrayList politicCard of the class Player contains values from the enum Color, to test it i added three different values but it returns an error, isn't player.getPoliticCards().get(0) supposed to return the color value in position 0 that i added before?
public enum Color {
    BLUE, BLACK, JOKER
}
public class Player {
    private int id;
    private ArrayList<Color> politicCards;
    public Player(int id){
        this.setId(id);
    }
    public ArrayList<Color> getPoliticCards() {
        return politicCards;
    }
    public void setPoliticCards(ArrayList<Color> politicCards) {
        this.politicCards = politicCards;
    }

}
public class PlayerTest {
    @Test
    public void PoliticCardsTest(){
        Player player = new Player(1);
        player.getPoliticCards().add(Color.BLACK);
        player.getPoliticCards().add(Color.BLUE);
        player.getPoliticCards().add(Color.JOKER);
        assertEquals(Color.BLACK,player.getPoliticCards().get(0));
    }

}

Comment: so what is the error?
Comment: @Reimeus NullPointerException
Comment: You have to intialize your array @mpz!!! :)
Comment: Just a side node: This is not a good design, you are exposing the internals of your class to be freely edited from externally. Goolge for 'encapsulation' and you find easily some tutorials explaining the matter.
Comment: politicCards is not initialized and hence its giving NullPointerException
public Player(int id){
        this.setId(id);
this.politicCards = new ArrayList();
    }
Answer: The politicCards field is not initialized, you could add
plater.setPoliticCards(new ArrayList<Color>()); after player construction.


Tiff compression using Java ImageIO

Question: I am having issues converting a png to tiff.  The conversion goes fine, but the image is huge.  I think the issue is that I am not doing the compression correctly?  Anyone have any suggestions??
Here is the code sample
public static void test() throws IOException {

    // String fileName = "4958813_1";
    String fileName = "4848970_1";
    String inFileType = ".PNG";
    String outFileType = ".TIFF";

    ImageIO.scanForPlugins();

    File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType);
    InputStream fis = new BufferedInputStream(new FileInputStream(
            fInputFile));
    PNGImageReaderSpi spi = new PNGImageReaderSpi();
    ImageReader reader = spi.createReaderInstance();

    ImageInputStream iis = ImageIO.createImageInputStream(fis);
    reader.setInput(iis, true);
    BufferedImage bi = reader.read(0);

    TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
    ImageWriter writer = tiffspi.createWriterInstance();
    //Iterator<ImageWriter> iter =  ImageIO.getImageWritersByFormatName("TIFF");
    //ImageWriter writer = iter.next();

    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

    param.setCompressionType("LZW");
    param.setCompressionQuality(0.5f);
    File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType);
    ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile);
    writer.setOutput(ios);
    writer.write(bi);

}

Comment: Additionally, setting the compression quality only works for ZLib/Deflate and JPEG compression, not LZW. https://download.java.net/media/jai-imageio/javadoc/1.1/com/sun/media/imageio/plugins/tiff/TIFFImageWriteParam.html
Answer: Writer.getDefaultWriteParam() only creates an ImageWriteParam object, it doesn't link it back to anything else.
I don't see any mechanism in your code for your modified param object to be subsequently used in the ImageWriter.
I believe that instead of:
writer.write(bi);

you need to use:
writer.write(null, new IIOImage(bi, null, null), param);

Answer: I don't know Java IO, but generally you want to look at a few things

Can you use JPEG compression instead of LZW?
See how to set the TIFF strip size -- if small size is what you want, set it to the height of the image.

Edit: Looks like a TiffWriteParam has the following methods
tiffWriteParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
tiffWriteParam.setTiling(imageWidth, imageHeight, 0, 0);

set the imageWidth and imageHeight vars to your image's size.  The downside is that it will be slower to read out regions of the image.

Tiff compression using Java ImageIO


Xcode iOS Notability "zoom box"

Question: Notability and other note taking apps have this 'zoom box' feature where you can draw in the magnified box at the bottom. Users can also drag the box at the top to change what they want magnified at the bottom. I have tried literally everything I can think of to add this feature in my app. I have added the same document in two views but then I run into many memory issues, I've duplicated the file but again memory issues. Does anyone know a simple way to do this? Is there anyway I can just have a view that is a magnification of another view?
Answer: Create a new Cocoa Touch Class (optionally name it MagnifyView) and set it as a subclass of UIView
Add the following code in your class:
var viewToMagnify: UIView!
var touchPoint: CGPoint!

override init(frame: CGRect)
{
    super.init(frame: frame)
    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

func commonInit()
{
    // Set border color, border width and corner radius of the magnify view
    self.layer.borderColor = UIColor.lightGray.cgColor
    self.layer.borderWidth = 3
    self.layer.cornerRadius = 50
    self.layer.masksToBounds = true
}

func setTouchPoint(pt: CGPoint)
{
    touchPoint = pt
    self.center = CGPoint(x: pt.x, y: pt.y - 100)
}

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    context!.translateBy(x: 1 * (self.frame.size.width * 0.5), y: 1 * (self.frame.size.height * 0.5))
    context!.scaleBy(x: 1.5, y: 1.5) // 1.5 is the zoom scale
    context!.translateBy(x: -1 * (touchPoint.x), y: -1 * (touchPoint.y))
    self.viewToMagnify.layer.render(in: context!)
}

To use it, implement touchesBegan, touchesMoved and touchesEnd functions in View Controller which you want to have the magnifying effect.
Here is how:
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
    let point = touches.first?.location(in: self.view)
    if magnifyView == nil
    {
        magnifyView = MagnifyView.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        magnifyView.viewToMagnify = self.view
        magnifyView.setTouchPoint(pt: point!)
        self.view.addSubview(magnifyView)
    }
}

override func touchesEnded(_ touches: Set, with event: UIEvent?) {
    if magnifyView != nil
    {
        magnifyView.removeFromSuperview()
        magnifyView = nil
    }
}

override func touchesMoved(_ touches: Set, with event: UIEvent?) {
    let point = touches.first?.location(in: self.view)
    magnifyView.setTouchPoint(pt: point!)
    magnifyView.setNeedsDisplay()
}

original source here
Comment: this is the main idea behind it i recommend reading the source, to give you and idea and then you customize it as you need
Comment: and you can use a pod for that to save some work if u able to , i recommend this one https://cocoapods.org/pods/iOS-MagnifyingGlass
Comment: Thank you so replying! Thank you! When I try this on PDFkit it's 'blurry' on the magnifying view. Any thoughts?
Comment: this could be anything, might be the document it self try different one if so, try to play with the aspect ratio of the Zoom box, please upvote my answer if it was helpful thank you @JimBak
Comment: the frame rate is very low using PDF Kit... Any ideas?
Comment: This is another question and unfortunately I don't know
Comment: +1 for a good answer. @JimBak To add to this, if you are interested in doing this ONLY for PDF files, (you mentioned pdf kit), use [Core Graphic's PDF APIs](https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html#//apple_ref/doc/uid/TP30001066-CH214-TPXREF109). Specifically check `CGContextDrawPDFPage`. Use this to draw pdf content instead of just redrawing magnified version of the view in your magnification `CGContext`. This should help with the 'blurry' magnification because pdf drawing scalable (vector).

Xcode iOS Notability "zoom box"


Accidentally trashed my poke balls and incense, how do I recover discarded items?

Question: I accidentally trashed my poke balls and incense in the items. How can I recover the most important part of the game. I can't get any poke balls now!
Answer: There is no way to recover any discarded items.  You must get new items by visiting PokeStops, leveling up, or purchasing them from the shop.