Causal Inference with unconfoundedness

Question: Consider an observational study with binary treatment. I denote treatment variable as $z_i$, denote observed outcome as $y_i$, denote potential outcome as $y_i(1),y_i(0)$, and denote covariates as $x_i$. Assume the unconfoundedness $P(Z | Y,X) = P(Z|X)$ holds in this problem.
I want to inference the sample average treatment effect on treatment group, i.e. $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - Y_i(0)\right]$. A way to do this is to regress $Y(0) \sim X$ using data from control group, and directly apply the regression function $\hat{f}(X)$ to treatment group to estimate $Y_i(0)$ , finally, use $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - \hat{f}(x_i)\right]$ to estimate $\frac{1}{\left| \{i|z_i = 1\} \right|} \sum_{i,z_i = 1} \left[Y_i(1) - Y_i(0)\right]$.
The method sounds weird, I actually want to estimate $Y(0)$ on the treatment group, but I only use data from the control group in regression. How can I improve it?
Comment: Unconfoundedness here would be $P(Z|Y(z), X) = P(Z|X)$.
Answer: The units in the control group provide information about the relationship between the $X$ and $Y(0)$, because for those units, $Y$ (the observed outcome) is equal to $Y(0)$. If you want $Y(0)$ in the treated group, you can use that information to estimate it from $X$ in the treated group, just as you describe.
For the treated units, you have $Y_i(1)$ because $Y_i = Y_i(1)$ for them. It's not an estimate of $Y_i(1)$; it is $Y_i(1)$. From the treated group alone, we have half of the information required to estimate $\frac{1}{|{i|z_i=1}|} \sum_{i,z_i=1} [Y_i(1)-Y_i(0)]$, i.e., the SATT, because we have $Y_i(1)$ for $i$ where $z_i=1$ without doing any modeling. However, for these units, $Y_i(0)$ is missing. We don't know what would have happened had the treated units received control.
How could we get $Y_i(0)$ for the treated units? For those units, it's unobserved, so no modeling of just the treated units could tell you the relationship between $X$ and $Y_i(0)$. That information only exists in the control group. So even though we're interested in a quality of the treated group (i.e., the treated group SATT), we have to consult the control group because only the control group contains information that can help us fill in the other half of the estimate of the SATT.
There are, of course, other methods of estimating the SATT, including weighting and matching, that don't require you to estimate $Y_i(0)$ for each treated unit. But, because $Y_i(0)$ is only observed for the control units, we have to include them in the analysis.
Comment: Thanks for your answer! I see we **need** to include data from control group in analysis, but in fact, I want to know how can we include data from treatment group in analysis because I **only** use data from control group in the method in my question description. :)
Comment: The treated group doesn't tell us about $Y_i(0)$, so it's not useful there. We already have $Y_i(1)$ in the treated group because it's just equal to $Y_i$. So we already have exactly what we need from the treated group without performing any modeling on the treated group. I'm not sure what else you could think to do in the treated group that would give you information you don't already have.

Causal Inference with unconfoundedness


Create a new facet block from Taxonomy terms

Question: Hi I am using recruiter distribution, I have creates a new taxonomy named as trades, having few terms, Now I want to create a facet block from these taxonomy terms, could anyone please suggest me any tutorial for doing this. I already have few default facet blocks provided by recruiter distribution. I could not find any proper tutorial regarding creation of facet from taxonomy terms.
Thanks
Answer: Here is a tutorial for creating facet blocks :Faceted search using search api tutorial
To add a taxonomy term as a facet just check the fields tab to find your term field and enable it and after enabling it you have to re-index and now your facet can be rendered as a block !!!
Comment: Thats cool...!! Mark it as answered then..


R - how do we use grepl or str_detect againts vector list? c()

Question: How do we use grepl function against lists in a vector?
So what I`m trying to do is...
Campaign                 Vendor
yy                        yyxxx
yxzrr                     yxz
xxx3                      yz
xxx4                      xxx4_zh
xxx5                      xxx5_xj_78

... 100,000 more rows
Given this dataframe, I would like to find which "Vendor" are matching
against "Campaign". But since there are no exact match, I was thinking to use
grepl or grep or str_detect function to map them
and if they match, I would like to insert a new row with the Campaign in a new column
Is there way to efficiently automate this mapping process?
I tried using, something like below...
But wasn`t working properly
Campaign_list <- unique(Campaign)

ifelse(grepl(c(Campaign_list), DCM$Campaigns), "Y", "N")

Comment: So what's the desired output here?
Comment: So the desired output will be.. first row of Vendor column = "yy" second row of Vendor column = "yxz" etc.. basically if the strings of Campaign is included in "Vendor" column, make another column with that Campaign row
Answer: Function Vectorize will help:
DCM <- read.table(text = c('
  Campaign                 Vendor
  yy                        yyxxx
  yxzrr                     yxz
  xxx3                      yz
  xxx4                      xxx4_zh
  xxx5                      xxx5_xj_78'
  ), header = TRUE )

vgrepl <- Vectorize(grepl)

# rows in Vendor that match with Campaign:
vgrepl(DCM$Vendor, DCM$Campaign)
[1] FALSE  TRUE FALSE FALSE FALSE

# rows in Campaign that match with Vendor:
vgrepl(DCM$Campaign, DCM$Vendor)
[1]  TRUE FALSE FALSE  TRUE  TRUE

# Combining both:
ifelse(apply(cbind(vgrepl(DCM$Vendor, DCM$Campaign), vgrepl(DCM$Campaign, DCM$Vendor)), 1, any), 'Y', 'N')
[1] "Y" "Y" "N" "Y" "Y"

Comment: But shouldn`t the output be "Y", "Y", "N", "Y", "Y" ? because all the lists there under Campaign have strings in vendor, except third one
Comment: You can invert the comparison, but note that the string "yxzrr" is not present in "yxz". So what you need is to find what strings in Vendor are present in Campaign and also the ones in Campaign that are presented in Vendor. I updated the answer. I suggest that you update the question with your desired output, that will help users to provide other solutions.
Comment: Thank you Carlos!! This worked, is there way to vote for your comment?
Comment: No need to thank, OS users are here to help each other. If the answer helped, vote on the answer. If you also want to vote for the comment, there's an up arrow on the side of it.


Proof that $f: \mathrm{P}(X) \rightarrow \mathbb{N}$ is injective

Question: Situation:
Take $n \in \mathbb{N}$, let $X = \{0, 1,..., n-1\}$ and define map $f: \mathrm{P}(X) \rightarrow \mathbb{N}$ through $f(A) = \sum_{i \in A} 2^i$
Question 1:
Proof that $f$ is injective.
Question 2:
What is the map of $f$?
Could someone please help me with these questions?
I do understand that a function is injective if $f(x)=f(y)$ implies that $x=y$. I also found out that when you take for example $n=3$, you'll get
\begin{eqnarray}
f(\{0\}) = 2^0 &=& 1 \\
f(\{1\}) = 2^1 &=& 2 \\
f(\{0,1\}) = 2^0 + 2^1 &=& 3 \\
f(\{2\}) = 2^2 &=& 4 \\
f(\{0,2\}) = 2^0 + 2^2 &=& 5 \\
f(\{1,2\}) = 2^1 + 2^2&=& 6 \\
f(\{0,1,2\}) = 2^0 + 2^1 + 2^2 &=& 7
\end{eqnarray}
So the new result is the last one plus 1. Somehow I think this is useful in the proof.
Note: English isn't my first language. So excuse me for any grammar mistakes.
Answer: observe that you are basically just mapping the binary notation of a number to the corresponding decimal number.
for example {0,2}=5(dec)=101(bin)
or {1,2)=6(dec)=110(bin)
see that the nth digit in the binary number is 1 is n is in X, and else it's 0.
so in other words, you have to proof that you can writing a decimal number in only one way in binary
Answer: You need to show that if $f(A) = \sum_{i \in A} 2^i = \sum_{i \in B} 2^i = f(B) $, where $A,B \subset \{0,...,n-1\}$, then $A=B$.
First note that $f(A) > 0$ iff $A \neq \emptyset$. Hence if $A =\emptyset$ we must have $B=\emptyset$ and vice versa.
So, suppose that neither of $A,B$ are empty.
The essential result here is that $2^0+2^1+...+2^{k-1} = 2^{k}-1 < 2^{k}$.
Let $k_A = \max A$, $k_B = \max B$, and suppose $k_A \ge k_B$ without loss of generality. If $k_A > k_B$, then we would have $f(A) \ge 2^{k_A}$, whereas the above equality shows that $f(B) \le 2^0+2^1+...+2^{k_B} = 2^{k_B+1}-1 \le 2^{k_A} - 1 < f(A)$, a contradiction. Hence we have $k_A = k_B$.
Now let $A'=A \setminus \{k_A\}$, $B'=B \setminus \{k_A\}$ and repeat the process. This shows $A=B$.
It is clear that $A$ represents the indices of the non-zero coefficients of the binary expansion of $f(A)$, and the minimum is $f(\emptyset) = 0$ and the maximum is $f(\{1,...,n-1\}) = 2^n-1$. Since $f$ is injective, and $|{\cal P(\{1,...,n-1\})}| = 2^n $, we see that the range must be the integers $0,...,2^n-1$.
Comment: In your comment you said that if $k_A > k_B$, then $f(A) \geq 2^{k_A}$. Isn't it $f(A) \geq 2^{k_B}$? If not, could you explain this step?
Comment: $k_A$ is the maximum non-zero index, so we must have $f(A) \ge 2^{k_A}$. The $k_A > k_B$ part comes into play because we must have $k_A \ge k_B+1$, and so $2^{k_B+1} \le 2^{k_A}$.


Como faço para executar o efeito Fade-in no carregamento de uma section

Question: Queria que as divs fossem carregadas apenas quando o usuario chegasse numa determinada section e não no carregamento do body. Assim quando o usuario rola até a section o evento ja aconteceu

document.addEventListener('DOMContentLoaded', function(){
    document.querySelector('#skills')
            .classList
            .add('loaded');
  });
#skills {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;

}
.container__skills {
    display: flex;
    justify-content: space-evenly;
    flex-wrap: wrap;
}
.skills__card {
    width: 200px;
    height: 200px;
    background-color: #000000;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    position: relative;

}
.skills__card::before {
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 50%;
    padding: 2.2px;
    background:linear-gradient(45deg,rgb(255, 0, 149),rgb(0, 110, 255));
    -webkit-mask:
       linear-gradient(#fff 0 0) content-box,
       linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
            mask-composite: exclude;
  }
.skills__card img {
    width: 100px;
    filter: invert(100%) sepia(0%) saturate(0%) hue-rotate(22deg) brightness(105%) contrast(102%);
}
@keyframes fade-in {
    from { opacity: 0 }
    to   { opacity: 1 }
  }

  .skills__card {

    opacity: 0;
    animation: fade-in 3s normal forwards ease-in-out;
    animation-play-state: paused
  }

  #skills.loaded .skills__card {
    animation-play-state: running
  }

  #skills.loaded .skills__card:nth-child(2){ animation-delay: 1s }
  #skills.loaded .skills__card:nth-child(3){ animation-delay: 2s }
  #skills.loaded .skills__card:nth-child(4){ animation-delay: 3s }
  #skills.loaded .skills__card:nth-child(5){ animation-delay: 4s }

HTML

CSS

JAVASCRIPT

REACT

UI/UX

    </section
Answer: Sem script so usando o CSS funciona assim:
body {
animation: fadein 2s; /* Padrão */
-webkit-animation: fadein 2s; /* Webkit */
-moz-animation: fadein 2s; /* Firefox */
-ms-animation: fadein 2s; /* IE */
}
@keyframes fadein {
from { opacity: 0.3; }
to { opacity: 1; } /* Padrão */
}
@-moz-keyframes fadein {
from { opacity: 0.3; }
to { opacity: 1; } /* Firefox */
}
@-webkit-keyframes fadein {
from { opacity: 0.3;
to { opacity: 1; } /* Webkit */
}
@-ms-keyframes fadein {
from { opacity: 0.3; }
to { opacity: 1; } /* IE */
}


Get parameter type name of generic base repository

Question: I am not sure if even possible, but my question is: Is there a way to get the class name of the generic parameter inside a base repository implementation.
This is my base interface:
@NoRepositoryBean
public interface AclBaseRepository<T extends BaseEntity> extends QuerydslPredicateExecutor<T>, CrudRepository<T, Long> {
    List<T> findAllWithAcl(Predicate predicate);
    Page<T> findAllWithAcl(Predicate predicate, Pageable pageable);
}

And this is my implementation
@NoRepositoryBean
public class AclBaseRepositoryImpl<T extends BaseEntity> extends QuerydslJpaRepository<T, Long> implements AclBaseRepository<T> {

    @SuppressWarnings("unchecked")
    public AclBaseRepositoryImpl(JpaEntityInformation<T, Long> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
    }

    @Override
    public List<T> findAllWithAcl(Predicate predicate) {
        return findAll(predicate);
    }

    @Override
    public Page<T> findAllWithAcl(Predicate predicate, Pageable pageable) {
        return findAll(predicate, pageable);
    }
}

Example Usage:
public interface AccountRepository extends AclBaseRepository<Account> {
}

The basic idea was: Have a common base repository for all "implemented" repositories with a few new methods (e.g. findAllWithAcl). Those new methods would inject a additional predicate (QueryDsl) into the defined query predicate which basically filters the rows according to some ACL tables. For that query i would need the class name of the entity being loaded. I would be fine with passing the class name as a parameter to the constructor, but since i use this base repository as a new repositoryBaseClass (e.g. @EnableJpaRepositories(repositoryBaseClass = AclBaseRepositoryImpl.class)) and my repositories are interfaces, i have no control over the parameters.
Is this possible? Is there another/better way to do this without needing to repeat the same code multiple times?
Answer: You can get the information from the JpaEntityInformation instance you get provided in the constructor.
Since it implements JpaEntityMetadata and EntityMetadata you have access to the entity name via getEntityName() and to the domain class via getJavaType().
Also, since AclBaseRepositoryImpl inherits from QuerydslJpaRepository which inherits from SimpleJpaRepository you can simply call getDomainClass.
Comment: Thank you. So nice and simple!


Scroll page on text input focus for mobile devices?

Question: Im making a mobile optimised site with a text input which filters a list as you type. Its similar to this: http://jquerymobile.com/test/docs/lists/lists-search.html
For phones, it would be a usability benefit if when you selected the input the page scrolled down so the input was at the top of the page. That way as much of the list below would be visible as you type. Is this possible and/or does anyone have experience doing it? Thanks
Answer: Agreed - that'd be nice for usability.
If you're using jQuery, this should do the trick:
$('#id-of-text-input').on('focus', function() {
    document.body.scrollTop = $(this).offset().top;
});

Comment: Thank you! Is there any option for scrolling on the middle of the page?
Comment: document.body.scrollTop = $(this).offset() + (window.innerHeight / 2);  maybe? But you'd want to ensure an on-screen keyboard doesn't overlap the input (and you have no idea what crazy keyboard person X might use on device Y), so top is probably safer.
Comment: Is this possible to do in Angular too?
Comment: @Siyah Angular is a framework rather than a DOM library, so normally you'd use jQuery for this kind of thing anyway (or just vanilla JS: http://youmightnotneedjquery.com/#on).
Answer: A better solution would be:
$('#id-of-text-input').on('focus', function() {
   document.body.scrollTop += this.getBoundingClientRect().top - 10
});

Because offsetTop (or .offset().top if using Jquery) returns the distance from the first positioned parent, whereas you need the distance from the top of the document.
getBoundingClientRect().top returns the distance between the current viewport position to the element, u.e. if you're scrolled 300px below the element, it would return -300. So adding the distance using += would scroll to the element. -10 is optional - to allow some space at the top.
Comment: Is this possible to do in Angular too?
Comment: you are missing ); at end
Comment: Added missing `);`
Answer: $('input, textarea').focus(function () {
    $('html, body').animate({ scrollTop: ($('input, textarea').offset().top - 10) }, 1);
    return false;
});

Comment: Edit your post and use code formatting. Also consider adding any explanation to your code.


Why $\mathbb Z_+^\omega\neq\cup_{n=1}^\infty\mathbb Z_+^n$?

Question: On the one hand we know that an infinite product of countable sets is uncountable, so $\mathbb Z_+\times\mathbb Z_+\times\ldots=\mathbb Z_+^\omega$ is uncountable.
On the other hand, the finite product of countable sets is countable and the countable union of countable sets is countable, so $\displaystyle\cup_{n=1}^{\infty}\mathbb Z_+^n$, where $\mathbb Z_+^n=\mathbb Z_+\times\ldots\times\mathbb Z_+$ ($n-$times), is countable.
So this is my question: why $\mathbb Z_+^\omega\neq\cup_{n=1}^\infty\mathbb Z_+^n$?
It seems to me that, since the union's index runs to infinity, these sets should be the same.
Comment: It's like there are uncountably many decimal expansions, but only countably many with a finite number of digits.
Comment: Yes, the first means something.
Comment: @LordSharktheUnknown So there is a difference between $\cup_{n=1}^\infty$ and $\lim_{m\rightarrow\infty}\cup_{n=1}^m$?
Comment: @LordSharktheUnknown
I thought that it was mean something (the first thing). I think I got it. Thanks a lot.
Answer: There not even of the same type: $\cup_{n=1}^\infty \mathbb{Z}^n_+$ is a set of vectors that all have finite length: each $x$ in the union must be in some $\mathbb{Z}^n_+$ and is thus of the form $(a_1,\ldots, a_n)$ for that $n$. A vector has a unique length so it is in exactly one such set. While an $x \in \mathbb{Z}_+^\infty$ is by definition a sequence (countably infinite vector) of the form $(a_1, a_2 ,a_3, \ldots)$. So a member of the right hand side is never in the left hand side or vice versa. So certainly no equality of sets (where $A = B$ for sets $A,B$ by definition means that $x \in A$ iff $x \in B$).


rails nested_attributes form can't find id

Question: So i have two models : Internship and Review. I want the Review to be a nested_attributs of Internship. So that i can create an internship with a review.
My problem is that the review form integrated in the new form internship, doesn't find the id of the internship. It raise the errors 'Review internship must exist'
Internship.rb
  has_many :reviews, foreign_key: "review_internship_id"
  has_many :review_users, foreign_key: 'review_user_id', class_name:"User", through: :reviews

  accepts_nested_attributes_for :reviews, allow_destroy: true
  validates_associated :reviews

Review.rb
     belongs_to :review_user, class_name: "User"
     belongs_to :review_internship, class_name: "Internship"

Internship_controller
  def new
    @internship = Internship.new
    @internship.reviews.new
  end

def create
    @internship = Internship.new(internship_params)
    @internship.user = current_user
    @internship.reviews.first.review_user_id = current_user.id

    respond_to do |format|
      if @internship.save
        format.html { redirect_to @internship, notice: 'Expérience crée avec succès' }
        format.json { render :show, status: :created, location: @internship }
      else
        format.html { render :new }
        format.json { render json: @internship.errors, status: :unprocessable_entity }
      end
    end
  end

private

 def internship_params
      params.require(:internship).permit(:adress, :zipcode, :city, :specialty, :organization, :population, :cursus, :title, :duration, :description, :region, :remuneration, :user_id, reviews_attributes: [:title, :notation, :description, review_internship_id: params[:internship_id], review_user_id: current_user.id])
    end

The new form in internship new
<%= form_with(model: internship, local: true) do |form| %>
....

      <%= form.fields_for :reviews do |p| %>

                  <%= p.label :titre %>
                  <%= p.text_field :title, class:"form-control" %>

                  <%= p.label :note %>
                  <%= p.number_field :notation, min: 1, max: 5, class:"form-control" %>

                  <%= p.label :description %>
                  <%= p.text_area :description, class:"form-control" %>

     <% end %>

   ...
 <% end %>

So this is what i've tried in Internship controller
 @intership.reviews.review_internship_id = @internship.id

So that it can find the id of the internship. The error is "Review Internship must exist".
It did the same with "Review User", which was solved with @internship.reviews.first.review_user_id = current_user.id
Do you have any idea where the problem is, and how i can find the internship id with another way. I've also tried the params[:id]
Thanks for your help
:
Answer: You don't really need a user_id foreign key on reviews since it can get there through the interview:
class Review
  belongs_to :internship
  has_one :user, through: :interview
end

class Internship
  belongs_to :user
  has_many :reviews
end

class User
  has_many :internships
  has_many :reviews, through: :internships
end

And you definitely don't ever need to be manually assigning parent ids for nested records.
class IntershipsController < ApplicationController

  def new
    @internship = Internship.new
    @internship.reviews.new
  end

  def create
    @internship = Internship.new(internship_params) do |i|
      i.user = current_user
    end

    respond_to do |format|
      if @internship.save
        format.html { redirect_to @internship, notice: 'Expérience crée avec succès' }
        format.json { render :show, status: :created, location: @internship }
      else
        format.html { render :new }
        format.json { render json: @internship.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def internship_params
    #  use some line-breaks!
    params.require(:internship)
          .permit(
            :adress, :zipcode, :city, :specialty,
            :organization, :population, :cursus,
            :title, :duration, :description,
            :region, :remuneration, :user_id,
            reviews_attributes: [
              :id, :title, :notation, :description
            ]
          )
  end
end

Comment: It doesn't work, it keeps searching for the internship_id in Review... Anyway, thanks for trying
Comment: It does work. You just have a strange and wonky review_internship_id column that you should rename to interview_id. I don't get why you're prefixing in the first place.
Comment: You can also provide the options to use a nonstandard fk. But I would just fix the table instead.
Comment: ok i understand. I learned that it's better to use class name in that situation, that's why i used the 'review_internship' for internship class. I don't known if that makes sense. I'm new to rails so i could be wrong, thank you for your help ;)
Comment: Prefixing the columns with the name of the class does not make sense at all in rails - its a convention over configuration driven framework. IMHO it does not really make sense anywhere else either and is mostly done by people who write horrible sloppy SQL.


How to show X is in the co-finite topology

Question: This might be kind of a silly question but I can't fully grasp why the set X on which the cofinite topology is defined would be contained in the Topology.
I know that the closure of all open sets U belonging to the topology will equal X; and what if X is not a finite set ?
Comment: What is your definition of the co-finite topology?
Comment: $T_{\text cofinitnite}$ := { U $\subset$ X : X\U is finite} $\cup$ {$\emptyset$}
Answer: The complement of $X$ is the empty set, which is finite.


Extract json data with php doesnt works

Question: I have json data like this:

{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}

I need to extract from json only keywords. I try without success with code:

$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';

foreach ($json['result'] as $keywords)
{
    echo $keywords['result']['keyword'];
}
Comment: When you say "without success" could you edit your question to include what you do see? What is the output of this example?
Comment: DaveyDaveDavem result was zero - blank screen.
Answer: Seems, you forgot to decode the string with json_decode. In addition, your likely would to loop over [result][hits] and not just [result]
$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
$json = json_decode($json, true);

foreach ($json['result']['hits'] as $hit)
{
    echo $hit['keyword'];
}

Comment: Thank you very much, Philipp, works.
Answer: TRY
    $json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
    $jsonp =json_decode($json,TRUE);

    foreach ($jsonp['result'] as $val)
    {
        if(is_array($val) ){
        foreach ($val as $k)
        {
            echo  $k['keyword'];

        }
        }

    }

Comment: Thanks, safin chacko, your code also works.

Extract json data with php doesnt works


Ignore non compatible character sets

Question: I am getting an error while trying to restore data from a dump file.
# mysql  < /tmp/Dump20200101.sql
ERROR 1273 (HY000) at line 1: Unknown collation: 'utf8mb4_0900_ai_ci'

I can edit the dump file and change the character set.

CREATE DATABASE  IF NOT EXISTS somedb_25122019 /*!40100 DEFAULT
  CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci / /!80016 DEFAULT
  ENCRYPTION='N' */;

What is the correct way to handle this error in mysql?
Answer: based on this article, the mysql8.0 collation utf8mb4_0900_ai_ci isn't supported in your destination database.
So replace it as you are importing it:
sed -e 's/COLLATE utf8mb4_0900_ai_ci/COLLATE utf8mb4_unicode_520_ci/g' /tmp/Dump20200101.sql | mysql

Comment: mysql-dump command correctly adds comment clause for character set. If mysql does not follow the hint while restoring data, then it defeats the purpose of adding extra characters in the create database statement in the first place.
Comment: note the comment - not version 4.0.1 around the entire character set and collation.assume you aren't restoring to this version, however it would of been useful to put the actual destination version into the question. You can write a bug, or patch for MySQL and they'd appreciate it more than if you didn't (https://bugs.mysql.com/).

Ignore non compatible character sets


Overflow hidden is not working in Internet Explorer 11

Question: I need to display image as round shaped in my site so i used overflow:hidden in my css code it works fine in other browsers but not in IE11.
above image is the output i got in ie
and my css code is
img-block {
/* position: relative; */
/* background-color: #f4f4f4; */
height: 200px;
overflow: hidden;
width: 100%;
text-align: center;
display: table;
font-size: 20px;

and my HTML code is

Comment: Thanks for providing your CSS, but can you please provide the relevant HTML as well? It's rather difficult to answer this question without being able to see how your existing page is rendered. It would help if you could update your question to list **all** relevant code in a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve). If your HTML is generated server-side, could you please post the **output**. For further information, please refer to the help article regarding [**how to ask good questions**](http://stackoverflow.com/help/how-to-ask) :)
Answer: Add this style
img {
    border-radius: 50%;
}

You need to add border-radius in order to make the image a round shape.


Print view field direct in views-view-fields.html.twig

Question: Is it posible to print all view field direct in views-view-fields.html.twig and sciping to use views-view-field.html.twig?
In my blog view I have a lot views-view-field.html.twig for every field type and this is just one view.
So is this posible and is this recomend?
Answer: Yes, that is possible, this is the most basic fields twig:
<code>{% for field in fields -%}
    {{ field.content }}
{%- endfor %}
</code>
Then you loose most field configuration from views and can put in your own html structure.
You don't need to skip the field twigs for single fields, simply delete you own twigs and let the core twigs take over again.
Comment: If you only want to print single fields like `{{ fields.field1 }}` and don't want to print all fields, then you don't need the `{% for %}` loop at all.
Comment: Ok. I understend. And if I want to have my own html structure, can I write somethink like {{ field.field_image.content }} Would drupal know to print only image field and not other field who are add in view?
Comment: Thank you a lot. With you help, experimentally and this article http://redcrackle.com/blog/drupal-8/theme-views-templates I learn.. :)


Com preencher um spinner com um campo de um objeto

Question: Tenho um Spinner na minha Activity, preciso fazer com que seus itens sejam os nomes (campo) de um ArrayList de objetos, e que quando selecionado, me seja retornado o id do mesmo para poder realizar uma nova operação.
Por exemplo:
Meu objeto contato
public class Contato {

    String nome;
    int id;
    //getters e setters
}

Tentei fazer da seguinte forma, porém no Spinner é exibido somente o endereço do objeto na memória do aplicativo.
Como posso fazer com que seja exibido o nome obtido de cada objeto no Spinner e seja retornado o id do mesmo?
// Uma lista contendo os objetos
ArrayList<Contact> contactlist= new ArrayList<Contact>();
contactlist.add("Gabe");
contactlist.add("Mark");
contactlist.add("Bill");
contactlist.add("Steve");

// Array Adapter que é definido como adapter do spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, contactlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

Answer: A forma ideal será escrever um Adapter para o efeito.
Não querendo ter esse "trabalho" e usando o ArrayAdapter, uma forma expedita é tirar partido de como o ArrayAdapter funciona.
O ArrayAdapter usa o método toString() da classe usada como item do ArrayList para obter o valor a apresentar.
O valor que o método toString() retornar é aquele que o Spinner apresentará.
Na classe Contato faça o Override do método toString() de forma a retornar o campo nome:
public class Contato {

    String nome;
    int id;
    //getters e setters

    @Override
    public String toString()
    {
        return nome;
    }
}

Para obter o id do Contato selecionado faça:
Contato contato = (Contato)spinner.getSelectedItem();
int id = contato.id;

Ou de forma mais directa:
int id = ((Contato)spinner.getSelectedItem()).id;

Comment: Muito obrigado! Funcionou perfeitamente.


Free product not abelian

Question: If $(G_i)$, $i \in I$ with $|I| > 1$ and $|G_i| > 1$ is the free product $G$ of $(G_i)$,$i \in I$ always not-commutative? The free product of a family of groups $(G_i)$, $i \in I$ is defined
by a tuple $(G, (\phi_i)_{i \in I})$ where $G$ is a group and $\phi_i : G_i \rightarrow G$ are homomorphisms, with the following property:
For every tuple $(U, (g_i)_{i \in I})$ where $U$ is a group and $g_i : G_i \to U$ are homomorphisms, there exists a unique homomorphism $f : G \to U$ with $g_i = f \circ \phi_i$ for all $i \in I$.
I thought that since $|G_i| > 1$ and $|I| > 1$ I can choose
$a_i \in G_i$ and $a_j \in G_j$ with $i \neq j$, $a_i \neq e_i $ with $a_j \neq e_j$. I wanted to show this by contraposition assuming $\phi_i(a_i) \phi_j(a_j) = \phi_j(a_j) \phi_i(a_i)$ for all $i \neq j$ and wanted to show that $a_i = e_i$ or $a_j = e_j$ but I can't really come to this conclusion since all Groups $G_i$ can be commutative and the only think that comes in my mind is that $G$ is generated by
\begin{equation}
\bigcup_{i \in I}{\phi_i(G_i)}
\end{equation}
which doesn't really help.
I would be thankful for every hint I can get.
Comment: It seems you are familiar with the universal property of free products. Are you familiar with any construction (i.e., not by the universal property) of a free product of groups?
Comment: There is an additional restriction. If two consecutive letters are from the same $G_i$ (we can assume the groups are disjoint), then we reduce the word by removing both letters and substituting their product in $G_i$ if it's not identity.
Comment: I think of it as the free group is generated from (reduced) words  $\phi_j(a_j) \ldots \phi_i(a_i)$ where $a_j \in G_j$ for $j \in I$.
Comment: So $\phi_i(a)\phi_i(b) = \phi_i(ab) \sim \phi_i(c)$ with $a,b,c \in G_i$ for all $i \in I$. So the group $G$ is under the assumption that $G$ is commutative generated by words $\phi_i(a_i)\ldots \phi_j(a_j)$ where $a_i \neq e_i$ for $i \in I$ and the empty word $e$.
Comment: No, there is not any commutativity assumption, neither in the definition of free products using the universal property, nor in constructions of free products.
Comment: I meant for the proof through contraposition I assumed that $G$ is commutative and I wanted to show that this leads to a contradiction.
Answer: An argument directly from the universal property:
Let $A$ be an "almost-disjoint union" of the $G_i$s, sharing a single identity element for all of them:
$$ A = \{0\} ~\cup~ \{ (i,x) \mid i\in I, x\in G_i, x\ne 0_{G_i}\} $$
Let $U$ be the group of permutations of $A$. Each $G_i$ acts on itself by left multiplication, which transfers in the natural way to an action on $A$ (namely, one that always fixes the elements that come from the other groups). This can be represented as homomorphisms $\phi_i: G_i \to U$.
Now, whenever we have nontrivial $x\in G_i$ and $y\in G_j$ with $i\ne j$, the two permutations $\phi_i(x)$ and $\phi_j(y)$ do not commute: $\phi_i(x)\phi_j(y)(0) = (j,y)$ whereas $\phi_j(y)\phi_i(x)(0) = (i,x)$.
Therefore when we apply the universal property to our $\phi_i$s, we get an $f$ with
$$ f(g_i(x)g_j(y)) = \phi_i(x)\phi_j(y) \ne \phi_j(y)\phi_i(x) = f(g_j(y)g_i(x)) $$
so $g_i(x)g_j(y)$ and $g_j(y)g_i(x)$ must be different elements of the free product.
Answer: One construction of a free product of groups is that it is the set of all words
$$
\phi_i(a_i) \cdots \phi_j(a_j)
$$
where

Every pair of consecutive letters are from different $G_i$ and not identity,
Each $\phi_i$ is an embedding of $G_i$, and
The pairwise images of $\phi_i$ and $\phi_j$ intersect only at the empty word when $i \neq j$.

These words are considered reduced, and the operation is concatenation followed by reduction until the word satisfies the first condition.
If $a$ and $b$ are two nonidentity elements from $G_i$ and $G_j$ where $i \neq j,$ then $\phi_i(a) \phi_j(b) \phi_i(a)^{-1} \phi_j(b)^{-1}$ is a reduced word (it satisfies the first condition), but it is not the empty word.
Thus,
$$
\phi_i(a) \phi_j(b) \neq \phi_j(b) \phi_i(a),
$$
and the free product is not abelian. Of course, this depends on the fact that there are at least two nontrivial groups which are factors in the free product.

Free product not abelian


Can't get mongoid working with Rails 4

Question: I followed the official tutorial.
I have sqlite3 commented out in my Gemfile as well as the following lines:
gem 'mongoid', '~> 4', github: 'mongoid/mongoid'
gem 'bson_ext'

However, I keep receiving the
Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem "sqlite3" to your Gemfile.
Reason seems to be that the database.yml still lists sqlite as the database. How am I supposed to get Rails to use the generated mongoid.yml? Replacing database.yml's contents with mongoid.yml doesn't seem to do the trick - I get the
ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter error.
Is it not compatible with Rails 4 or am I missing something simple?
Edit: I think I'm getting warmer. I've added the adapter as 'mongoid'. Here's the contents of my database.yml now:
development:
  adapter: 'mongoid'
  # Configure available database sessions. (required)
  sessions:
    # Defines the default session. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: xboxie
      # Provides the hosts the default session can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - localhost:27017
      options:
        # Change whether the session persists in safe mode by default.
        # (default: false)
        # safe: false

        # Change the default consistency model to :eventual or :strong.
        # :eventual will send reads to secondaries, :strong sends everything
        # to master. (default: :eventual)
        # consistency: :eventual

        # How many times Moped should attempt to retry an operation after
        # failure. (default: 30)
        # max_retries: 30

        # The time in seconds that Moped should wait before retrying an
        # operation on failure. (default: 1)
        # retry_interval: 1
  # Configure Mongoid specific options. (optional)
  options:
    #
test:
  sessions:
    default:
      database: xboxie_test
      hosts:
        - localhost:27017
      options:
        consistency: :strong
        # In the test environment we lower the retries and retry interval to
        # low amounts for fast failures.
        max_retries: 1
        retry_interval: 0

# # SQLite version 3.x
# #   gem install sqlite3
# #
# #   Ensure the SQLite 3 gem is defined in your Gemfile
# #   gem 'sqlite3'
# development:
#   adapter: sqlite3
#   database: db/development.sqlite3
#   pool: 5
#   timeout: 5000

# # Warning: The database defined as "test" will be erased and
# # re-generated from your development database when you run "rake".
# # Do not set this db to the same as development or production.
# test:
#   adapter: sqlite3
#   database: db/test.sqlite3
#   pool: 5
#   timeout: 5000

# production:
#   adapter: sqlite3
#   database: db/production.sqlite3
#   pool: 5
#   timeout: 5000

Produces the error:
LoadError: Could not load 'active_record/connection_adapters/mongoid_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.
Answer: I've solved this by adding:
Mongoid.load!(Rails.root.join("/config/mongoid.yml"))

to config/intializers/mongoid.rb, as per the tutorial.
Also you'll need to change the following line in your config/application.rb file from:
require 'rails/all'

to (in Rails 3.x):
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# require "sprockets/railtie" # Uncomment this line for Rails 3.1+

or (in Rails 4.x):
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"

Answer: I had similar issues. All was resolved by recreating my app without ActiveRecord...
rails new app_name --skip-active-record

adding Gems as above and getting my mongoid.yml right...
Answer: This issue happens when using mongo. Basically mongo does not go well with active record . So generate your application using the command,
rails g myApp --skip-active-record
Works well in my case
Answer: Check your config/database.yml. You probably specified sqlite3 there.
Comment: Yes I have. However, if I change it to mongoid I have a whole mongoid.yml configuration file and a database.yml configuration file and I'm not sure how to swap the two
Comment: At the end of tutorial that you linked, they were talking about how to remove database.yml isn't it?
Answer: In my case, I was receiving a similar error coming from puma. I realised then that on config/puma.rb I had:
on_worker_boot do
  # worker specific setup
  ActiveSupport.on_load(:active_record) do
    config = ActiveRecord::Base.configurations[Rails.env] ||
        Rails.application.config.database_configuration[Rails.env]
    config['pool'] = ENV['MAX_THREADS'] || 16
    ActiveRecord::Base.establish_connection(config)
  end
end

I had to replace everything inside on_worker_boot with the content of config/initializers/mongoid.rb
In general, I think a good way of debugging this is to search for any reference to active_record on the code.
Answer: I was also getting the same error as
"Could not load active_record/connection_adapters/mongoid_adapter".

I could solve it by commenting
    "config.active_record.migration_error = :page_load" in deveopment.rb and
    "config.active_record.raise_in_transactional_callbacks = true" in application.rb. Also make sure that in database.yml, database is not specified at sqlite3 but mongoid.
You will also need to remove "require 'rails/all'" from application.rb and replace it with
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"

as mentioned in above comments.

Can't get mongoid working with Rails 4


how to pass data from my controller to the view in laravel 8

Question: am trying to retrieve data from the controller and send it through and email to student but it not working .i have tried it but it not going
public function test(){

        $welcome = DB::table('results')
        ->select('studentinfos_id','marks','subject_code','name','email','rollid','classname','classnumber','image_path')
        ->join('studentinfos','studentinfos.id','=','results.studentinfos_id')
        ->join('subjects','subjects.id','=','results.subjects_id')
        ->join('addclasses','addclasses.id','=','results.addclasses_id')

        ->where('studentinfos.id',1)
        ->orderBy('subject_code','ASC')
        ->get();

        Mail::to('serge@gmaile','divine')->cc('leade@gmail')->send(new mytestmail($welcome));

    echo 'check ur inbox';

   }

how do i get all the result from the $welcome in my view.blade.php
i was hopping that i will send and email that contains student info and result of there marks and subject through email

 Result for {{ $classname }} student

        CLASS
        {{ $welcome->classname  }} {{ $welcome->classnumber }}

        FULL NAME
        : {{ $welcome->name }}

        EMAIL
        : {{ $welcome->email }}

        ENROLLMENT
        : {{ $welcome->enrollment }}

  image)  }}"

       alt="Card image cap">

            no
            subject
            marks

        <?php $num=1;
        $total = 0;
        $name;
        ?>
        @foreach($welcome as $see)

            {{ $num++ }}
            {{ $see->subject_code }}
            {{ $see->marks }}

<?php

$total += $see->marks  ?>
        @endforeach

          total marks
          {{ $total }}

          Download

                <form action="/print" method="get">
                    <input type="hidden" value="{{$studnet}}" name='id' >
                    <button class="btn btn-info">Download</button>
                </form>

@stop

Answer: you have to pass the welcome variable to your view.
In the controller method add the data when displaying your view:
return view('view', ['welcome' => $welcome]);

https://laravel.com/docs/8.x/views#passing-data-to-views


Why Datetime.DayOfWeek is wrong?

Question: Consider this simple piece of code
var date = new DateTime(1307, 10, 13);
Console.WriteLine(date.DayOfWeek);

it outputs:

Thursday

BUT,
wikipedia (french version) says that this date is a Friday :

L'affaire débute au matin du vendredi 13 octobre 1307

Who is right?
My guess is that .Net doesn't take julien/gregorian calendar change into account.
Comment: @HereticMonkey: I suspect the Sunday part was back when the OP was using a date in November...
Comment: Here's a site that says it was Thursday: https://www.dayoftheweek.org/?m=October&d=13&y=1307&go=Go.
Comment: @HereticMonkey: From that page: "The day of the week for October 13, 1307 under the old Julian calendar was Friday. Did you notice the difference with the Gregorian calendar?"
Comment: @JonSkeet Yeah, and the paragraph above that ends with "The day of the week was *Thursday*." I know all about the Julian/Gregorian change over and all that fun stuff (having done some research into George Washington's birthday). Just thought it was funny that this site said it was Thursday, not Sunday. Goes to show that you should take things you read on the internet with a big grain of salt.
Answer:
my guess is that .Net doesn't take julien/gregorian calendar change into account

Indeed, as documented (emphasis mine):

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Note that it couldn't take the Julian/Gregorian cut-over into account without more information, as that occurred on different dates in different places.
If you know you want to represent a date in the Julian calendar, I suggest you use the JulianCalendar class.
using System;
using System.Globalization;
using static System.FormattableString;

public class Program
{
    public static void Main()
    {
        var julianCalendar = new JulianCalendar();
        var date = new DateTime(1307, 10, 13, julianCalendar);

        Console.WriteLine(Invariant($"Gregorian: {date:yyyy-MM-dd}"));
        Console.WriteLine(date.DayOfWeek);
    }
}

Output:
Gregorian: 1307-10-21
Friday

Comment: @phuzi: No, it does it exactly the same way as .NET, defaulting to a proleptic Gregorian calendar. If you use `new LocalDate(1307, 10, 13, CalendarSystem.Julian).DayOfWeek` it prints Friday. The only difference is that the `LocalDate` retains its knowledge of the original calendar system, so it's still 1307-10-13 Julian, rather than 1307-10-21 (implicitly Gregorian) like the DateTime is.
Comment: I guess NodaTime does this a little differently - `new NodaTime.LocalDate(1307, 10, 13).DayOfWeek` gives Thursday.

Why Datetime.DayOfWeek is wrong?


UITableView - Dados da tabela desaparecendo

Question: Possuo uma UITableView simples. Ela é carregada a partir de um .nib e adicionada como uma subview, ela aparece, carrega os dados, apresenta os mesmos tudo corretamente, porém a partir do momento que eu seleciono uma célula, os dados simplesmente somem.
Atualmente estou utilizando Swift, porém ja tive este mesmo problema com Objective-C, que foi resolvido sem nenhuma alteração de código, porém agora não esta mais sendo resolvido.
Segue o código de criação da UITableView:
override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        listObjectsToList = ["String 1","String 2","String 3"]

    self.view.frame.size = CGSizeMake(300, 110)
    self.view.layer.cornerRadius = 5
    self.view.layer.masksToBounds = true

    self.tableView.scrollEnabled = false
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listObjectsToList.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
    cell.textLabel.text = listObjectsToList.objectAtIndex(indexPath.row) as? String
    return cell
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 40
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    let objectSelected: AnyObject = listObjectsToList.objectAtIndex(indexPath.row)
    object.type = objectSelected as String
    self.view.removeFromSuperview()
}

Código de adição como subview:
var listTypeTableViewController = NSBundle.mainBundle().loadNibNamed("TableViewTypeScheduling", owner: self, options: nil)[0] as ListTypeTableViewController
listTypeTableViewController.view.frame = CGRectMake(10, 80, 300, 130)
self.view.addSubview(listTypeTableViewController.view)

Vale ressaltar que o método didSelectRowAtIndexPath não é chamado
Comment: Por que você afirma que o método `didSelectRowAtIndexPath` não é chamado? Não será chamado caso você não tenha definido o *delegate* da tabela, foi isso? Porque nesse método você está removendo toda a view (e nela contém a tabela), que seria exatamente o problema.
Comment: Eu coloquei um breakpoint, ele não é chamado e a view não é removida da tela. A classe é uma UITableViewController
Answer: Ok, cheguei ao entendimento do que você pretende fazer, e com isso, você não consegue simplesmente "extrair" a UITableView de dentro do seu controller para colocar em outra view.
Você vai precisar também incluir a UITableViewController como "filho" desta que vai recebê-la. Alterei a forma como é adicionado, ficou assim:
var listTypeTableViewController = ListTypeTableViewController(nibName: "TableViewTypeScheduling", bundle: nil)
listTypeTableViewController.view.frame = CGRectMake(10, 80, 300, 130)
addChildViewController(listTypeTableViewController)
view.addSubview(listTypeTableViewController.view)

O grande ponto é o método addChildViewController, que adicionar o controller antes de adicionar a view que está dentro dela.
Comment: Obrigado! Nas outras vezes que fiz o mesmo procedimento eu não tinha adicionado ela como "filha", e ainda sim havia dado certo.


Solution to non-linear PDE

Question: I think I have found a solution for a PDE of the form

$u_t + g(u)u_x = 0$
where $u(x, 0) = g^{-1}(x)$

The solution is  $u(x,y) = g^{-1}\left(\frac x{t+1}\right)$
This solution satisfies 1 and 2 under the assumption that $\forall z, g\left(g(z)^{-1}\right) = z$
However I am worried about the effects of discontinuities in $g$ or its inverse, and issues where the function is not 1-1.
What sort of problems should I watch out for and how can I get around them?
Comment: The tag [tag:differential-equations] is intended for questions about ordinary differential equations, there is a separate tag for [tag:pde]s; see the [tag-wiki](http://math.stackexchange.com/tags/differential-equations/info) and the tag-excerpt. (The tag-excerpt is also shown when you are adding a tag to a question.)
Comment: The original place I found it had $g(x) = e^x$ which gave an answer $u(x,y) = ln(\frac x{t+1})$ But as far as I know the solution would hold for any smooth function with an inverse, that is what I am trying to determine.
Answer: This equation you are dealing with, although it looks simple, it is a very problematic one: it is a nonlinear conservation law. These equation DO NOT have smooth solutions for all $t>0$. Their solution break down after a short time and the develop "shock waves" - discontinuous weak solutions.
The simpler such equation is Burger's Equation ($g(u)=u$)
$$
u_t+uu_x=0,
$$
and there is a written about it as it is the simplest model for shock formation.
Comment: In the present case, the classical solution does not break down at positive times (cf. my answer).
Answer: The classical solution $$
u(x,t) = g^{-1}\left(\frac{x}{t+1}\right)
$$
follows from the method of characteristics, which requires that the solutions remains smooth along the characteristic curve as time increases. Smoothness is lost at the breaking time $$
t_b = \inf \frac{-1}{(g\circ g^{-1})'(x)} = -1 \, .
$$
This can be seen in the solution's denominator which vanishes at $t=-1$. Therefore, if only positive times are considered, no shock wave will form!
Now, if there are some discontinuities in $g$ or $g^{-1}$, the problem statement makes little sense as $g$ is no longer invertible over its whole domain of definition.

Solution to non-linear PDE


On AWS Elastic Beanstalk, with Docker, when do ebextensions get run relative to Docker RUN and CMD entries?

Question: I can't find any documentation on the startup order (probably I'm just not looking in the right places).
On the Docker side there's all the stuff in the Dockerfile which gets executed together and then the CMD entry which is run after to actually start the server.
What I want to know is when do commands in ebextensions get run relative to this?
Is it before any of the Dockerfile stuff happens? after the bulk of the Dockerfile stuff but before CMD or after all of it?
Answer: This page is useful: Customizing Software on Linux Servers | AWS Elastic Beanstalk
Under "Commands" it says "run before the application and web server are set up and the application version file is extracted"
Under "Container Commands" it says "run after the application and web server have been set up and the application version archive has been extracted, but before the application version is deployed."
From experimenting I think it goes like this:

Run ebextensions Commands
Build Docker image as 'aws_beanstalk/staging-app'
Run ebextensions Container Commands
Rename the image to aws_beanstalk/current-app
Start the image

I can successfully call run on the staging-app image from container commands, which is what I was after.


SQL server autogrowth failure

Question: I just ran into an SQL Server database (2005 or 2008, I'm not sure) which had autogrowth set to "By 10 percent, unrestricted growth" on the primary data file.  It had no free space, and inserts were failing because of lack of free space.
The drive had over 100 GB free, and the data file was about 15 GB.  I wish I had kept the error message, but it was something about "insufficient free space on PRIMARY".  It was not a timeout exception like I've seen on a few occasions with 2000, where it could take long periods of time to resize.
I increased the "Initial Size" setting by about 5 GB, and it completed instantly, and everything started working again after that.
Why does SQL Server sometimes not autogrow when it should?
Answer: How did you verify and change the file size and auto-growth? Via T-SQL, or via the Management Studio? SSMS had a number of bugs on which it displayed and set erroneous auto-growth rates on data files, see Attaching a database increases autogrowth % to 12800.
Comment: It's the value displayed in management studio.  I'm trying to get results from sp_helpdb, and see if they're different.
Comment: BTW, You see immediate failure and immediate growth because the system has Instant File Initialization enabled, see http://msdn.microsoft.com/en-us/library/ms175935.aspx
Comment: To view current size and growth, check `sys.database_files`: http://technet.microsoft.com/en-us/library/ms174397.aspx
Comment: I finally got the results, and they match what's shown in Management Studio.  Max size -1, growth 10, is_percent_growth 1.
Answer: Try setting the auto grow option to a smaller value: 300 - 500 MB. Allocation of 1,5 GB (10% out of 15 GB data file) could have caused the insert queries to timeout waiting for the space to be allocated. What was the timeout set for? The default value in SQL is 600 sec but if the queries where run from a third-party application the timeout can be a lot smaller.
Comment: I specifically pointed out that it's not a timeout.  I've seen situations where it times out on the resize, and in those situations, doing a resize manually takes 5-10 minutes, and all inserts result in a timeout.  In this situation, the commands fail instantly with no free space, the manual resize completes instantly, and the inserts immediately start working after the resize.

SQL server autogrowth failure


Simular outro ambiente ao utilizar o comando `composer update`

Question: Possuo um projeto Symfony2 com dependências geridas pelo composer, com seus respectivos arquivos composer.json e composer.lock sincronizados entre minha máquina local e o servidor de produção através do git.
É sabido que ao rodar o comando composer update, algumas verificações das configurações da máquina são feitas antes que as versões de dependências sejam escolhidas, já que em alguns casos existem versões diferentes de um mesmo pacote compatíveis com ambientes diferentes.
Um exemplo de pacote com várias versões é o symfony/icu, responsável pela internacionalização do Symfony2. A versão escolhida pelo composer para esse pacote difere entre 1.0.0 e 1.2.0 dependendo da existência ou ausência da biblioteca lib-icu na máquina.
Caso 1 - Rodar composer update na máquina local
Quando rodo composer update em minha  máquina local, que possui a biblioteca de internacionalização lib-icu, é criado um arquivo composer.lock que referencia a versão v.1.2.0 do pacote symfony/icu.
Problema: o servidor de produção não possui a biblioteca lib-icu, então quando eu executo composer install a partir do composer.lock gerado anteriormente é retornado um erro referente à ausência dessa biblioteca.
Caso 2 - Rodar composer update no servidor de produção
Se, por outro lado, eu executo o composer update no meu servidor de produção, a dependência automaticamente escolhida do symfony/icu é a versão v1.0.0 (que funciona sem o lib-icu). Nessa situação, ao executar composer install tudo funciona certinho, tanto no servidor de produção quanto em minha máquina local.
Como simular o ambiente do servidor de produção?
Minha pergunta é: existe alguma maneira de eu executar o composer update na minha máquina local forçando que o composer utilize a versão v1.0.0 do pacote symfony/icu, em vez de utilizar a versão v1.2.0 baseada na configuração da minha máquina? Isto é, quero executar o composer update na minha máquina local, e obter o mesmo resultado que eu obteria se executasse no servidor remoto, como se em minha máquina local não existisse a biblioteca lib-icu.
Meu composer.json
{
    "name": "symfony/framework-standard-edition",
    "license": "MIT",
    "type": "project",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": {
            "": "src/",
            "Application": "app/"
        }
    },
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.3.*",
        "doctrine/orm": ">=2.2.3,<2.4-dev",
        "doctrine/doctrine-bundle": "1.2.*",
        "twig/extensions": "1.0.*",
        "symfony/assetic-bundle": "2.3.*",
        "symfony/swiftmailer-bundle": "2.3.*",
        "symfony/monolog-bundle": "2.3.*",
        "sensio/distribution-bundle": "2.3.*",
        "sensio/framework-extra-bundle": "2.3.*",
        "sensio/generator-bundle": "2.3.*",
        "incenteev/composer-parameter-handler": "~2.0",
        "sonata-project/admin-bundle": "2.2.7",
        "sonata-project/doctrine-orm-admin-bundle": "2.2.4",
        "sonata-project/easy-extends-bundle": "2.1.3",
        "sonata-project/user-bundle": "2.2.0"
    },
    "scripts": {
        "post-install-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ],
        "post-update-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ]
    },
    "config": {
        "bin-dir": "bin"
    },
    "minimum-stability": "stable",
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": {
            "dev-master": "2.3-dev"
        }
    }
}

Comment: Então, o detalhe é que o pacote em questão não tá explícito no meu composer.json. Vou postar ele na pergunta.
Comment: Acredito que o `symfony/icu` seja uma dependência do próprio `symfony/symfony`, então não sei como exigir uma versão específica para este caso.
Comment: Ah, entendi. Eu tentaria incluir esse pacote explicitamente, passando a versão desejada. Capaz que isso tenha prioridade sobre a cadeia de dependências que o composer está usando.
Comment: Hmmm, boa ideia! Vou testar, e aviso aqui se funcionar. Talvez o `symfony/symfony` continue "pedindo" pela versão 1.2.0 da dependência, aí vamos ver como o composer vai resolver isso. Bem, valeu! Vou testar aqui.
Comment: @bfavaretto Sugestão simples e eficaz! Simplesmente adicionei "symfony/icu": "v1.0.0" dentro do bloco "require" do composer.json e meu problema foi resolvido. Escreva isso como resposta que eu marco como aceita.
Comment: @rodrigorigotti Por que a troca da tag? A outra tem wiki, e segue os pardos que definimos: http://meta.pt.stackoverflow.com/questions/310/como-tratar-tags-em-arvore, http://meta.pt.stackoverflow.com/questions/443/precisamos-de-padronizacao-para-tags-com-mais-de-uma-palavra
Comment: @bfavaretto porque o certo é "symfony", e não "symphony". o ideal é que troquemos as tags da wiki também, porque as pessoas procurarão pelo nome certo, concorda?
Comment: @rodrigorigotti Ok, eu não tinha reparado no erro de grafia. Neste caso o hífen antes do 2 fica ou não? É tanto número de versão quanto parte do nome do produto... Dê uma olhada nas discussões do meta que linkei.
Comment: @bfavaretto é verdade, bem notado. eu havia deixado `symfony2` porque é uma grafia bem comum para o framework, então agora fiquei na dúvida. por outro lado, vou alterar a tag para ficar dentro do padrão do Stack Overflow :) valeu!
Answer: Eu tentaria incluir esse pacote explicitamente, passando a versão desejada. É bem possível que isso tenha prioridade sobre a cadeia de dependências que o composer está usando. Acredito que quem pede o symfony/icu deve estar pedindo uma versão mínima, usando um coringa (*) no número da versão, ou especificando >= X.
Portanto, inclua na sua chave require:
"symfony/icu": "1.0.0" // ou 1.0.*


Como colocar botão ao lado de dois campos de texto

Question: Estou querendo por o botão ao lado dos edit text, já fiz varias tentativas com layout_toleftof e layout weight mas o botão acaba sumindo, ou fica no mesmo lugar.
Meu xml ta assim:
<?xml version="1.0" encoding="utf-8"?>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:digits="1234567890.,"
    android:ems="10"
    android:id="@+id/editTextComercial"
    android:hint="Diametro Comercial"
    android:maxLines="1" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="3dp"
    android:inputType="numberDecimal"
    android:digits="1234567890.,"
    android:ems="10"
    android:id="@+id/editTextVC"
    android:hint="Velocidade de Corte"
    android:maxLines="1" />

<Button
    android:text="Calcular "
    android:layout_marginTop="5dp"
    android:layout_height="wrap_content"
    android:id="@+id/buttonCalc"
    android:layout_width="match_parent"/>

<TextView
    android:text="TextView"
    android:visibility="invisible"
    android:gravity="center"
    android:textSize="16dp"
    android:textStyle="bold"
    android:layout_marginTop="5dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textViewResultRPM" />

Comment: Use LinearLayout
Answer: Se o que deseja é fazer da seguinte maneira:

Tenho duas soluções, uma com Linear outro com relative layour, segue a do Linear, nele criei outros layouts dentro, um com orientação vertical para colocar os Edit text , e outro horizontal para separar esse layout dos Edit text com o do botão por weight.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        >
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:digits="1234567890.,"
            android:ems="10"
            android:id="@+id/editTextComercial"
            android:hint="Diametro Comercial"

            android:maxLines="1" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:inputType="numberDecimal"
            android:digits="1234567890.,"
            android:ems="10"
            android:id="@+id/editTextVC"
            android:hint="Velocidade de Corte"
            android:maxLines="1" />

    </LinearLayout>
    <Button
        android:text="Calcular "
        android:layout_marginTop="5dp"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/buttonCalc"
        android:layout_weight="2"

        />
</LinearLayout>

<TextView
    android:text="TextView"
    android:visibility="invisible"
    android:gravity="center"
    android:textSize="16dp"
    android:textStyle="bold"
    android:layout_marginTop="5dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textViewResultRPM" />

No relative layout foi um pouco mais complicado, contudo a solução é mais simples, basta adicionar: android:layout_toEndOf="@id/editTextComercial"
android:layout_alignBottom="@id/editTextVC" para poder alinha o botão ao final do width e do bottom do Edit text , claro que deve ser adicionado um valor no width dos Edit text.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:digits="1234567890.,"
    android:ems="10"
    android:id="@+id/editTextComercial"
    android:hint="Diametro Comercial"
    android:maxLines="1"
    android:layout_marginTop="10dp"
    android:layout_alignParentStart="true" />

<TextView
    android:text="TextView"
    android:visibility="invisible"
    android:gravity="center"
    android:textSize="16dp"
    android:textStyle="bold"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:id="@+id/textViewResultRPM"
    android:layout_below="@+id/editTextVC"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"
    android:digits="1234567890.,"
    android:ems="10"
    android:id="@+id/editTextVC"
    android:hint="Velocidade de Corte"
    android:maxLines="1"
    android:layout_below="@+id/editTextComercial"
    android:layout_alignParentStart="true" />

<Button
    android:text="Calcular "
    android:layout_height="wrap_content"
    android:id="@+id/buttonCalc"
    android:layout_width="match_parent"
    android:layout_toEndOf="@id/editTextComercial"
    android:layout_alignBottom="@id/editTextVC"
    android:layout_alignTop="@+id/editTextComercial" />

Comment: funcionou, estava usando linear, mas n pensei nisso de criar varios linear um dentro do outro, preciso estudar mais xml. vlw
Comment: Qualquer coisa, estamos ai para ajudar


Meaning of a fingering marking

Question: Henle's edition of Isaac Albéniz's Tango has these two bars:

What does the line connecting the two 2s across the bar line mean?
Comment: It means that you should slide the same finger to the right, rather than growing a second index finger :-)  But seriously, this notation seems redundant, and perhaps only there as a sort of "[sic]" saying "yes, the second 2 is  not a misprint".
Comment: Also of interest is 'which finger does the1st F# get played with?'
Answer: I think it simply emphasises the suggested fingering, in which finger 2 is used for successive notes, so you have to slide your finger down onto the white key. The motivation for this fingering, rather than the obvious 2-3-4-5 is probably to avoid the akwardness when combined with the thumb on D.

Meaning of a fingering marking


How to add image to Facebook post without getting the image twice in the feed?

Question: I am trying to make a post to a Facebook page using the Graph API that includes an image. I have successfully done it with a two step process:

Post to 'https://graph.facebook.com/PAGE_ID/photos?url=IMAGE_URL&access_token=ACCESS_TOKEN'
Taking the image id from the return data from the post and making another post to 'https://graph.facebook.com/PAGE_ID/feed?published=true&message=MESSAGE_TEXT&object_attachment=IMAGE_ID&fields=permalink_url&access_token=ACCESS_TOKEN'

However, when I do that, FB posts the image to the page first and then posts the message with the image in it. Not ideal; I only want a single post with message and image.
I then tried keeping the image unpublished (adding &published=false to my image post). That worked to keep the image from posting on the page and I got an OK message with the image id back from FB. However, I received an error code (1 - "An unknown error occurred") from the FB API when I went to post the message with image.
I also tried to keep the image unpublished and flag that as temporary (adding &published=false&temporary=true to my image post) with the same result.
Anyone know how to post a message with image to a page without first posting the image to the FB page?
Comment: Try the `no_story` parameter, see https://developers.facebook.com/docs/graph-api/reference/photo#Creating
Comment: Thanks, CBroe. That did the trick.
Answer: The no_story parameter can be used to suppress the automatic creation of a feed story for the photo upload.
https://developers.facebook.com/docs/graph-api/reference/photo#Creating:

no_story
  boolean
  If set to true, this will suppress the News Feed story that is automatically generated on a profile when people upload a photo using your app. Useful for adding old photos where you may not want to generate a story
Answer: You can add a caption to your image post.
Or add the image as form data while creating the post.
Which Framework do you use?
Comment: The caption was not what I was looking for. CBroe's suggestion of "no_story" in the comments above worked. I will have to play around with adding the image as form data. For now, though, it is a relief to get it working. I appreciate your help and time, Norbert.


$3.\lim_{n\to\infty}\langle x,e_n\rangle=?$

Question: given that $\{e_i\}_{n=1}^{\infty}$ is an orthonormal sequence in a hilbert space $H$, and $x\ne 0\in H$. Then could any one tell me which of the following is true?
$1.\lim_{n\to\infty}\langle x,e_n\rangle$ does not exist
$2.\lim_{n\to\infty}\langle x,e_n\rangle=\|x\|$
$3.\lim_{n\to\infty}\langle x,e_n\rangle=1$
$4.\lim_{n\to\infty}\langle x,e_n\rangle=0$
I just know one relations about orthonormal sequence in Hilbert space
 $\sum_{n=1}^{\infty}|\langle x,e_i\rangle|^2\le \|x\|^2$. Thank you for help.
Comment: You have a convergent series. What is the limit of the main term?
Comment: what is main term boss?
Comment: The term $|\left|^2$.
Comment: i dont know :( :(
Comment: Just call that term $c_n$. You know that the infinite series $\sum_n c_n$ converges; what can you conclude about $\lim_{n\to\infty} c_n$?
Comment: :-ooooooooooooo yes the limit will be zot
Answer: By Bessel's ineqaulity
$$
\sum_n|\langle x,e_n\rangle|^2\leq \Vert x\Vert^2
$$
so the series $\sum_i|\langle x,e_i\rangle|^2$ converges. Hence its terms tend to zero, and so does $\langle x,e_n\rangle$.
Comment: @Cm7F7Bb, fixed


Mapping subspaces of dimension $2$ to subspaces of dimension $2$

Question: Setting. Let $V$ be a vector space over some field $F$ with $\dim(V) \geq 3$. A map $\phi : V \to V$ is called flat if the image of any subspace of dimension $2$ is again a subspace of dimension $2$.
Question. Is the implication
$$f \text{ flat} \implies f \text{ injective}$$
always true?
Motivation. In the case of a finite field $F = \mathbb F_q$, the answer is "yes": Assume that $\phi(v) = \phi(w)$ for two distinct vectors $v,w\in V$. Let $U$ be a subspace of dimension $2$ containing $v$ and $w$. Then $\#U = q^2$, but $\#\phi(U) \leq q^2 - 1$, which is a contradiction.
Clarifications.

The map $\phi$ is not assumed to be linear! (For linear maps $\phi$, it is not hard to see that the answer is "yes".)
The term "subspace" means "vector subspace" (and not "affine subspace").
Comment: @GerryMyerson Many thanks for your pointers. Yes, there is some relation to your first pair of links, in the sense that they explore the outskirts of the fundamental theorem of projective geometry (the one which states that every collineation of a projective Desarguesian geometry of dimension $\geq 2$ is induced by a semilinear map). But I don't see how they should help making progress here. Concerning the mathoverflow-Link: Admittedly, that one is a bit scary to me :) But yes, maybe it is related. I'd not be too surprised if in the end, the property depends on the axiom of choice...
Comment: @GerryMyerson I'm not sure I see how the MO post is related. The words flat and injective mean completely different things in that question.
Comment: This seems to be related: https://math.stackexchange.com/questions/2035208/is-a-map-that-preserves-lines-and-fixes-the-origin-necessarily-linear also https://math.stackexchange.com/questions/3985327/is-lines-remain-lines-sufficient-to-characterise-linearity-in-mathbb-r2
Comment: Possibly https://mathoverflow.net/questions/163923/properties-of-vector-spaces-without-ac is related.
Comment: Concerning the 2 links to MSE: of course, I immediately thought of this "[fundamental theorem of affine geometry](https://fr.wikipedia.org/wiki/Th%C3%A9or%C3%A8me_fondamental_de_la_g%C3%A9om%C3%A9trie_affine)". But the difficulty lies in proving that if planes remain planes then lines remain lines. As for the link to MO: I cannot see how it could be related.
Comment: Right, I humbly retract my comment. +1 for the interesting question.
Answer: Assuming subspace means vector subspace and not affine subspace, and with $V$ over $\mathbb{R}$, take some $v \ne 0$, map $kv$ for $k \in [2, \infty)$ to $(k - 1) v$ and map everything else by identity. Then the image of every line is itself, so the image of every plane is itself.
Comment: @Shinrin-Yoku Consider an affine plane through $2v$ which does not contain the origin. This particular map will take such a plane to a punctured plane and an isolated point.
Comment: thank you! I think your are right. Seems that I was thinking too complicated...
Comment: What goes wrong with assuming affine subspace?


Step-by-step derivative of $\left ( \frac{c_1 x}{c_2 x + c_3 + c_4 \sqrt{c_5 x}} \right)^{c_6x + c_7 + c_8 \sqrt{c_9 x}}$

Question: Can someone please walk step by step on how to calculate the derivative
$\left ( \frac{c_1 x}{c_2 x + c_3 + c_4 \sqrt{c_5 x}} \right)^{c_6x + c_7 + c_8 \sqrt{c_9 x}}$
Where the $c_i$ are constants, which are positive.
Answer: For this kind of monsters, logarithmic differentiation could be your best friend.
Making the problem more general, consider $$y=\left(\frac{f(x)}{g(x)}\right)^{h(x)}\implies \log(y)=h(x)\left( \log(f(x))-\log(g(x))\right)$$ Differentiate both sides $$\frac {y'}y=h(x) \left(\frac{f'(x)}{f(x)}-\frac{g'(x)}{g(x)}\right)+h'(x)\log\left(\frac{f(x)}{g(x)} \right)$$ Now, use $$y'=y\times \frac {y'}y$$
Answer: Define
$$
 f(x) = g(x)^{h(x)} = e^{h(x)\ln g(x)}
$$
Compute
$$
 f'(x) = e^{h(x)\ln g(x)} \left(
\frac{h(x)g'(x)}{g(x)} + h'(x) \ln g(x)
\right)
$$

Define
$$
\begin{align}
 \alpha(x) &= c_{2} + c_{3} x + c_{4} \sqrt{c_{5}x} \\[2pt]
  g(x) &= \frac{c_{1}x}{\alpha(x)} \\[2pt]
  h(x) &= c_{6} + c_{7} x + c_{8} \sqrt{c_{9} x}
\end{align}
$$
Derivatives
$$
\begin{align}
  \alpha'(x) &= c_{3} + \frac{c_{4}c_{5}}{2\sqrt{c_{5}x}} \\
  g'(x) &= \frac{c_{1} \left(\alpha( x)- x \alpha'(x)\right)}{\alpha(x)^2} \\[3pt]
  h'(x) &= c_{7}+\frac{c_{8} c_{9}}{2 \sqrt{c_{1} x}}
\end{align}
$$

Final answer
$$
 f'(x) = \left(\frac{c_{1} x}{c_{2}+c_{3} x+c_{4} \sqrt{c_{5} x}}\right)^{c_{6}+c_{7} x+c_{8} \sqrt{c_{9} x}} \left(\left(c_{7}+\frac{c_{8} c_{9}}{2 \sqrt{c_{9} x}}\right) \log \left(\frac{c_{1} x}{c_{2}+c_{3} x+c_{4} \sqrt{c_{5} x}}\right)+\frac{c_{5} \left(2 c_{2} \sqrt{c_{5} x}+c_{4} c_{5} x\right) \left(c_{6}+c_{7} x+c_{8} \sqrt{c_{9} x}\right)}{2 (c_{5} x)^{3/2} \left(c_{2}+c_{3} x+c_{4} \sqrt{c_{5} x}\right)}\right)
$$


How to position the background image to fill the screen?

Question: Hi I am trying to have a background image to fill the screen and it doesn't go to the top of the screen whatever simulator / real device I use it always leaves a blank space, I have used the auto layout with constraints to the top and every possible constraint and haven't solved the problem, note that I am using an add banner with takes up the blank spot whet it is running. This is the code I have been using
override func viewDidLoad() {
        super.viewDidLoad()
        let yourImage = UIImage(named: "fond320x480.png")
        let imageview = UIImageView(image: yourImage)
        self.view.addSubview(imageview)
        self.view.sendSubviewToBack(imageview)

Answer: If you want your imageview to fill the screen then:
imageview.frame = self.view.bounds
self.view.addSubview(imageview)

But if you want yourimage to fill your imageview then you should set content mode of imageview to fill:
imageview.contentMode = UIViewContentMode.ScaleAspectFill

and then of course add your image and add view as subview
Comment: Thanks for your answer @Superian007 , I used this but it has now covered everything else (buttons labels etc ) and it is still placed correctly in the document outline when I am in the main storyboard
Comment: I am not sure if I understand you correctly. So you don't want to fill the screen with your image?
Comment: Yes, I want it to fill the screen but it as a background image so I want all the buttons , labels etc to be on top of it
Comment: Then you have to insert your view with image under views you just mentioned.

Take a look here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/insertSubview:belowSubview:
Answer: Please try this code, Hope it will work for you.
set UIImageView contentMode to UIViewContentModeScaleToFill as below :
imageview.contentMode = UIViewContentMode.ScaleToFill


Regex em um switch case

Question: Sobre
Tenho um switch que cuida da ativação dos meus menus a partir do endereço deles no site.
        switch($location.path()){
                case '/perfil':
                    $scope.menuAtivo.perfil = 'active';
                    break;
                case '/perfil/editar/1':
                    $scope.menuAtivo.perfil = 'active';
                    break;
        }

Problema
Quando ele acessa o '/perfil/editar/1' quero que ele pegue qualquer numero ali onde tem o '1' pois minha url é '/perfil/editar/:id', tentei utilizando regex mas nao tive muito sucesso. Alguém teria alguma ideia?
Answer: switch em Javascript só funciona com constantes. Para testar contra padrões você teria que usar ifs mesmo, ainda mais porque é preciso ser explícito quanto à ordem em que os testes serão feitos..
var path = $location.path();
var m;
if((m = path.match(/^\/perfil\/$/)){
    //nesse caso nao precisa de regex pra falar a verdade
}else if((m = path.match(/^\/perfil\/editar\/(\d+)$/))){
    var id = m[1];
}

Lembre-se que pra usar regex vc precisa escapar as barras e usar ^ e $ para garantir que você está testando contra a string inteira.

Dito isso, é bem possível que já tenha alguma funcionalidade pronta no Angular pra fazer esse roteamento de URLs. Minha resposta foi feita assumindo Javascript puro.

Regex em um switch case


combine multiple dataframes to a list by storing variables in r

Question: I have 3 dataframes:
df1 <- read.table(text = "ID V1 V2 V3 V4
A 1 2 3 4
B 5 6 7 8
C 9 10 11 12", stringsAsFactors = FALSE, header = TRUE)

df2 <- read.table(text = "ID V1 V2 V3 V4
D 13 14 15 16
E 17 18 19 20
F 21 22 23 24", stringsAsFactors = FALSE, header = TRUE)

df3 <- read.table(text = "ID V1 V2 V3 V4
G 25 26 27 28
H 29 30 31 32
I 33 34 35 35", stringsAsFactors = FALSE, header = TRUE)

How can I combine these three dataframes into a list, not just using list function to combine them, but storing the variables.
When I look up a certain variable, I except to see them separated by dataframes I inputed, like if my list is called test:
test[[ID]]
df1 df2 df3
A D G
B E H
C F I

test[[V1]]
df1 df2 df3
1 13 25
5 17 29
9 21 33

Comment: It's difficult to see why you would want to store the data in this way; it is not a very "R-like" solution. It would be more usual to store each data frame as a list item, or to combine the data frames into one with a column to identify the originals.
Comment: I'm not entirely sure what you want - do you mean like `Map(data.frame, df1=df1, df2=df2, df3=df3)` ?
Comment: Problem solved, I will re consider my data structure, thanks a lot @neilfws
Answer: I concur with @neilfws' sentiment in that this seems to be an unusual structure you would want. Perhaps you should take a step back and rethink what it is that you'd like to do with the data downstream and whether there is a better structure to work towards that goal.
That aside, you can generate such a structure in the following way
First off, store the individual data.frames in a named list.
lst <- list(df1 = df1, df2 = df2, df3 = df3)

Then the following reproduces your expected output
setNames(
    lapply(seq_along(lst[[1]]), function(idx) sapply(lst, function(x) x[, idx])),
    names(lst[[1]]))
#$ID
#     df1 df2 df3
#[1,] "A" "D" "G"
#[2,] "B" "E" "H"
#[3,] "C" "F" "I"
#
#$V1
#     df1 df2 df3
#[1,]   1  13  25
#[2,]   5  17  29
#[3,]   9  21  33
#
#$V2
#     df1 df2 df3
#[1,]   2  14  26
#[2,]   6  18  30
#[3,]  10  22  34
#
#$V3
#     df1 df2 df3
#[1,]   3  15  27
#[2,]   7  19  31
#[3,]  11  23  35
#
#$V4
#     df1 df2 df3
#[1,]   4  16  28
#[2,]   8  20  32
#[3,]  12  24  35

This assumes that all data.frames have an identical column structure.
Comment: Thanks you very much, I will re-consider my purpose


How does a $y(t)=$plot of this exponential function looks like?

Question: I've tried to plot the y(t) function, but there are complex numbers and I don't know how to plot it. I've been looking for hyperbolic functions transformation, but I didn't figured how to do this. My question is how to transform this in hyperbolic functions and plot it in the y vs t axes.
y(t)=(0.62*exp(-0.564*t)+1)*((-1.62+0.0749*i)/(exp((0.0510+0.24*i)*t))
Answer: Explore it with Wolfram Alpha
Comment: Ok thanks, but how would i do to plot in a wider range  such as 0 to 50 in the time  and 0 to 100 in the y ?
Answer: You can expand the complex exponential:  $\exp((0.510+0.24i)t)=\exp(0.510t)\exp(0.24it)=\exp(0.510t)(\cos(0.24t)+i\sin(0.24t))$.  Then if you multiply the numerator and denominator by $\cos(0.24t)-i\sin(0.24t)$ the denominator becomes real.  You can then calculate the real and imaginary parts in a spreadsheet over whatever range you want and graph them.
Answer: I found this to be what you might be looking for. But the results does not render anything knowledgeable when y -> {0,100}, but here is the plot anyways.

Plot of y(t)

Here is the plot for only t -> {0,50}:

Plot of y(t)


How to use derivatives of a function to better estimate its variance over the domain?

Question: How to use derivatives of a function to better estimate its variance over the domain?
I have a scalar smooth function $f(x)$ and a multivariate random variable $x$ with known distribution (e.g. multivariate standard normal with large diagonal sigma). I know that the function f is very peaky in a sense that for majority of x'es its value rarely deviate from the mean, but on a small subset of x'es it attains extreme values. I need a finite sample estimate of the variance of this function over the domain of X. I can sample x, compute f(x) and use a standard formula, but it seems to be not very efficient since the domain of X is large and high dimensional (hundreds of dimensions) and I know that it is mostly constant.
Intuitively, if I encounter a region with low curvature and "close to the mean" value of f(x), I can "mark" it as "not interesting" and explore the rest of X.
Is there a formal way of doing this? Assume for simplicity that f is antisimmetric so f(x) = -f(-x) so we only need to look for maximas of x. One could probably do something like a variational approximation q such that x' ~ q(x'|x) maximizes expectation of f(x') while being not too far from the standard normal, but this way we have a significant chance of greatly underestimating the variance.
Comment: I don't think I understand the question but it sounds like a direct application of the $\delta$-method.
Comment: @AdamO it is indeed related and the [Taylor expansions for the moments of functions of random variables](https://en.wikipedia.org/wiki/Taylor_expansions_for_the_moments_of_functions_of_random_variables) seems even more related, but uses an estimate of gradients only at the mean of $X$. I wonder if there's a generalization that 1) uses gradients and values of a function at multiple points $\{x_1, \dots, x_n\}$ 2) says how to choose the next point $x_{n+1}$ to evaluate the gradient and the value of $f(x)$.
Comment: For example, if the function $f(x)$ is fairly flat near $x=0$ but has peaks around $x = \pm \frac{1}{2}$ then delta method would give a bad estimate of $var[f(X)]$ (or it's better to say that the remainder term would be non-negligible because $|| f^{(n)} ||_{\infty}$ are large for large $n$s). The question then is whether we can combine estimates of gradients and values from multiple points to get a better estimate of $var[f(X)]$ and how to choose these points.
Answer: Apparently I was looking for a variant of a SGLD or some other MCMC algorithm that takes gradients into consideration to approximate expectation of a function $f(x)$ when $x \sim P(x)$. I am still not sure how to perform integration when $f(x)$ is complicated, but $P(x)$ is not, I will update the answer when I figure this out.