LINQ Query to match a part (fraction) of a string

Question: I want to dynamically update a DataGridView based on a user entering in search terms in a text box, using LINQ.
In order to do this, I want what they enter to not have to perfectly match the string in the database, but for example if the company is 'Telexperts' and they type in 'Tele' in the text box, then it will return all companies that has 'Tele' in their name.
Here is some rough psuedocode:
Dim CompaniesSortedByTextBox = (From c As Company In db.Companies
                                Where c.CompanyName Contains SortByNameTextBox.Value
                                Select c).ToList

Edit: Glad to see this question took off with a good response.  I've been following the answers provided, and right now I am using the Contains method, but am finding it to be very slow.  I am changing the datasource based on when the textbox is changed, as follows:
Private Sub FilterDataGridView(sender As System.Object, e As System.EventArgs)
                                          Handles FilterByCityBox.TextChanged
DataGridViewElements = (From c As Company In db.Companies Select c).ToList 'Reset it.
If (FilterByCityBox.Text <> "") Then
    CompanyInfos = (From c As Company in db.Companies Where c.City.Contains(FilterByCityBox.Text)).ToList
End If
PUCOCompanyRegistry.DataSource = CompanyInfos

It works, but is very slow.  It requires the user waiting a good amount of time (about a half a second) after every keystroke in the textbox.
Comment: Contains is case sensitive (in C# anyway, not sure on VB.NET), so you may want to look into IndexOf >= 0
Comment: Wait... which language are you asking this in?  C# or VB.NET?
Comment: VB.Net is case-insensitive, so 'c.cOmPaNyNaMe.cOnTains' is perfectly valid. However, it should be avoided.
Comment: from the `Dim` and lack of `()` after ToList, it seems to be VB.Net
Comment: @Xiaoy312: That's true for the identifiers, but the `Contains` function checks for case when comparing strings, no?
Comment: @Xiaoy312, they are the same method in both languages.. you're checking the value of the string aka char array.. "C" is not "c" in any format for obvious reasons..
Comment: The `Contains` method from the .net framework certainly functions in a case-sensitive way. I was commenting on the language itself. Sorry, I totally missed the real question.
Comment: @Musicode Your edit is totally unrelated to your first problem. You should post a different question.
Answer: You have a couple alternatives:

String.StartsWith is translatable to SQL:

From c As Company In db.Companies
Where c.CompanyName.StartsWith(SortByNameTextBox.Value)
Select c

So is String.Contains:

From c As Company In db.Companies
Where c.CompanyName.Contains(SortByNameTextBox.Value)
Select c

SqlMethods.Like implements SQL's LIKE construct:

From c As Company In db.Companies
Where SqlMethods.Like(c.CompanyName, "%" + SortByNameTextBox.Value + "%")
Select c

And since you're doing VB, I believe it has a Like operator:

From c As Company In db.Companies
Where c.CompanyName Like ("*" + SortByNameTextBox.Value + "*")
Select c

Here are some docs about string mapping.
Comment: Where does the `SqlMethods` come from?
Comment: @OneFineDay It's a helper class made specifically for this purpose. [Here are the docs](http://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods.aspx).
Comment: Very nice @Lucas Trzesniewski! +1
Comment: This is the correct answer, although you should give the full namespace in this snippets: System.Data.Linq.SqlMethods.Like .. also.. I would avoid using the VB.NET Like operator in a linq expression, as it doesn't derive from the linq assembly, so it will probably just encapsulate the same functionality, but have to make the determination that it is being used in a linq expression first..
Comment: @Brett the `Like` operator won't ever be executed on a linq-to-sql expression, as it's not executable code but an expression tree. This is evidenced by the [`SqlMethods.Like` implementation](http://referencesource.microsoft.com/#System.Data.Linq/DLinq/Dlinq/SqlClient/SqlMethods.cs#567). And [here's the relevant translation code](http://referencesource.microsoft.com/#System.Data.Linq/DLinq/Dlinq/SqlClient/Query/SqlMethodCallConverter.cs#936) for the `Like` operator ([second part](http://referencesource.microsoft.com/#System.Data.Linq/DLinq/Dlinq/SqlClient/Query/SqlMethodCallConverter.cs#2467)).
Comment: haha.. exactly.. you see that part at the end: `return sql.Like(mc.Arguments[0], pattern, escape, source)` it means everything above the line that calls on the helper is unneccessary if you just call on the helper in the first place
Comment: but even before that point.. there was an evaluation made on the part of the framework to say, we want to return an expression here.. the question then becomes, is it done at compile time, or runtime.. I'm guessing.. runtime
Comment: @Brett I don't get your point. This is an `Expression>`, and your guess is wrong, expressions in this case are immutable objects and are constructed at compile time as static fields, then referenced at runtime. It it the compiler that creates the expression tree. [See this answer](http://stackoverflow.com/a/793584/3764814). Besides, the `sql` variable you're talking about is of type `SqlFactory`, which is internal to the `System.Data.Linq.SqlClient` assembly, so you can't call it directly. Just don't say `PostBindDotNetConverter` is unnecessary :)
Comment: interesting.. I was working with a misconception there.. thanks for the reference and clarification.. Although it doesn't seem to be a particular issue now, my point was simple and it's actually still valid.. it's an unneccessary translation.
Answer: //should be Filtered not Sorted
Dim CompaniesSortedByTextBox = (From c As Company In db.Companies
                                Where c.CompanyName.Contains(SortByNameTextBox.Value)
                                Select c).ToList

Answer: I have one more suggestion, If you have a list of keywords and expecting that, CompanyName can be one of the value from list, you can do it like this.
 Dim lst As New List(Of String) ' assuming c.CompanyName can be = comp1 or comp2 or comp 3
 lst.Add("comp1") : lst.Add("comp3") : lst.Add("comp2")
 Dim CompaniesSortedByTextBox = (From c As Company In db.Companies
                                        Where lst.Contains(c.CompanyName)
                                        Select c).ToList

Comment: what is the point in the colons? `list.AddRange({"comp1","comp2","comp3"})`
Comment: Thanks for info, since i am acquainted with the earlier one, i used  that, ":" is used in vb.net to make in multi statement to single, This is basically a helper method/statements , for example.


Value of $x$ for a probability game to be fair

Question: To make it clear, I am not asking the following question, though it is related.
My question is instead the following.

A person pays $k$  dollars to play a game. In the game, they roll a single 6-sided die. If it lands anywhere from $1$ to $5$ inclusive, they win exactly that many dollars. If they land on $6$, then the game terminates.
What is the value of $x$ so that the game is fair?

I am stuck for the following reason. It is clear that the expected number of rolls to land on a specific value is $6$. However, my concern is the journey it took to finally land on that $6$ to terminate the sequence. The money won for a $(1,1,1,6)$ journey is very different from the money won on a $(5,5,5,6)$ journey.
I know that we want the expectation to be zero, but I am not sure what to define as the random variable $X$, much less so how to compute $E(X)$.
Comment: Think recursively.  Either the game ends on the first toss or it doesn't, in which case you'd have picked up some cash and you'd still expect $x$ more going forward.
Comment: If we disregard the entry fee and focus on just the winnings, then $E(X)=?+5/6E(X)$. I am not entirely sure what goes in place of the question mark. Am I on the right track?
Answer: Let $N$ denote the number of rolls needed to arrive at result $6$ and let $X_i$ denote the gain at the $i$-th roll. Then the total gain can be expressed as:$$X=X_1+\cdots+X_{N-1}$$Here: $$\mathbb EX_i=\frac16[1+2+3+4+5]=\frac52$$
Then for positive integer $n$: $$\mathbb E[X\mid N=n]=\mathbb E[X_1+\cdots+X_n]=\frac{5n}2$$
Applying the law of total expectation we find:$$\mathbb EX=\sum_{n=1}^{\infty}P(N=n)\mathbb E[X\mid N=n]=\sum_{n=1}^{\infty}P(N=n)\frac52n=\frac52\mathbb EN=\frac52\cdot6=15$$

Another route (suggested by @lulu).
If $\mu$ denotes $\mathbb EX$ then:$$\mu=\frac16\cdot0+\sum_{j=1}^5\frac16(j+\mu)=\frac52+\frac56\mu$$telling us directly that $\mu=15$.


O que há de errado no meu Ajax?

Question: Meu código não tem retorno e não consigo descobrir o por que.
index.php
<form id="login" method="POST">
        <input type="text" name="username" placeholder="Usuário ou email" />
        <input type="text" name="password" placeholder="Senha" />
        <button onclick="enviar()" type="submit">Entrar</button>
</form>

Enviar.php
<?php
$resposta = 1;
echo (json_encode($resposta));

Comment: ,o que você está querendo dizer com "minha função não tem retorno?",o retorno seria entrar em algum "if",ou retornar "falso"?,explique um pouco mais do seu problema
Comment: Ele deveria estar alertando 'OK', já que estou retornando 1
Comment: acabei de testar aqui e funcionou perfeitamente, talvez o problema seja no seu arquivo do "jQuery",você tem certeza que está nesse local?
Comment: Já viu o console do navegador? Será que a ordem que o carregamento do jQuery e a falta do `$(document).ready` não pode ser o problema?
Comment: Tente retirar o `json_encode`, deixe apenas `echo $resposta;`. Apenas objetos e arrays devem ser transformados para json.
Comment: Cancele o `submit`normal, e chame sua função no `onSubmit` assim: ``
Answer: Tu estás utilizando "dateType", sendo que o correto é "dataType".

O que há de errado no meu Ajax?


Debugging Sitecore 6 with Visual Studio 2008

Question: I'm trying to debug Sitecore 6 ASP.NET code using Visual Studio 2008 (Windows Server 2003 OS). I am trying to get breakpoints to work.  I tried setting the breakpoint and then on VS, debug -> attach to process.. -> IIS web server process, but nothing happens when I browse to a certain .aspx page where a breakpoint is located at the beginning of the Sitecore.Web.UI.WebControl.DoRender method.
I tried checking both client-side and server-side debugging settings on the website's properties -> configuration -> debugging but nothing changes. I tried stopping the website, recycling the appPool and restarting, re-attaching the debugger and nothing happens.
Does anyone have a better idea?
Answer: Make sure you are trying to attach to the correct process. It is called w3wp.exe in IIS 6+.
Comment: that was it! i was attaching to mmc (IIS manager) but i didn't read the 'manager' part. thanks!
Answer: On a page, on the code behinde call the command the Page OnLoad
Debug.Fail();

or
Debug.Assert(false);

then open this page, and wait for the Message from Debuger to appear and attach to visual studio.  If not appear then its means that you are on release mode and you need to modify your web.config
If you have some error with your www service, then restart the iis-admin service and not only the www. With the iisAdmin www restarts also but some times debugger not attach with only www restart.
Hope this help you.


Mac OS X Lion Python Ctype CDLL error lib.so.6 : image not found

Question: I am a beginner in Python. When I tried the following Python sample code with type library on Mac OS X Lion:
#hello.py
from ctypes import *
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
message_string = "Hello World! Hello Python!\n"
libc.printf("Testing :%s",message_string)
//

An error occurred as following:
Traceback (most recent call last):
File "cprintf.py", line 2, in <module>
cdll.LoadLibrary("libc.so.6")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: dlopen(libc.so.6, 6): image not found

Can anyone tell me what's the matter? BTW, I tried this on Windows and Linux; it worked well.
Need I make some configuration for ctype.
Thanks very much,
Ricky
Answer: Shared libraries on Mac OS X tend to have the extension .dylib instead of .so.  In this case, /usr/lib/libc.dylib is what you want so load libc.dylib.
Answer: OS X uses ".dylib" for the extension of its shared objects, so you need to use "libc.dylib" instead.
Answer: A cross platform solution would be to use something like this:
import platform
import ctypes

libc = ctypes.cdll.LoadLibrary("libc.{}".format("so.6" if platform.uname()[0] != "Darwin" else "dylib"))
# or ctypes.CDLL("libc.{}".format("so.6" if platform.uname()[0] != "Darwin" else "dylib"))

Not quite sure what the difference is between these alternatives, as both seem to work nicely!


How to set default active element in SlickJS slider

Question: I have slick slider witch displays elements sorted by date and i want to preselect the last one (current month) to be default element.
For example if i have
[01 2015, 02 2015, 03 2015, 04 2015, 05 2015, 06 2015]
i want to display 06 2015 and when you swipe backwards to get older mounts.
Answer: Basically what you want to do here is to set the initial slide to the current month. The solution is more or less straight forward. Executable example right below:

$('.myslider').slick({
    initialSlide: ((new Date).getMonth())
});
/* Slider */
.slick-slider
{
    position: relative;

    display: block;

    -moz-box-sizing: border-box;
         box-sizing: border-box;

    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;

    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -ms-touch-action: pan-y;
        touch-action: pan-y;
    -webkit-tap-highlight-color: transparent;
}

.slick-list
{
    position: relative;

    display: block;
    overflow: hidden;

    margin: 0;
    padding: 0;
}
.slick-list:focus
{
    outline: none;
}
.slick-list.dragging
{
    cursor: pointer;
    cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list
{
    -webkit-transform: translate3d(0, 0, 0);
       -moz-transform: translate3d(0, 0, 0);
        -ms-transform: translate3d(0, 0, 0);
         -o-transform: translate3d(0, 0, 0);
            transform: translate3d(0, 0, 0);
}

.slick-track
{
    position: relative;
    top: 0;
    left: 0;

    display: block;
}
.slick-track:before,
.slick-track:after
{
    display: table;

    content: '';
}
.slick-track:after
{
    clear: both;
}
.slick-loading .slick-track
{
    visibility: hidden;
}

.slick-slide
{
    display: none;
    float: left;

    height: 100%;
    min-height: 1px;
}
[dir='rtl'] .slick-slide
{
    float: right;
}
.slick-slide img
{
    display: block;
}
.slick-slide.slick-loading img
{
    display: none;
}
.slick-slide.dragging img
{
    pointer-events: none;
}
.slick-initialized .slick-slide
{
    display: block;
}
.slick-loading .slick-slide
{
    visibility: hidden;
}
.slick-vertical .slick-slide
{
    display: block;

    height: auto;

    border: 1px solid transparent;
}

@charset 'UTF-8';
/* Slider */
.slick-loading .slick-list
{
    background: #fff url('./ajax-loader.gif') center center no-repeat;
}

/* Icons */
@font-face
{
    font-family: 'slick';
    font-weight: normal;
    font-style: normal;

    src: url('./fonts/slick.eot');
    src: url('./fonts/slick.eot?#iefix') format('embedded-opentype'), url('./fonts/slick.woff') format('woff'), url('./fonts/slick.ttf') format('truetype'), url('./fonts/slick.svg#slick') format('svg');
}
/* Arrows */
.slick-prev,
.slick-next
{
    font-size: 0;
    line-height: 0;

    position: absolute;
    top: 50%;

    display: block;

    width: 20px;
    height: 20px;
    margin-top: -10px;
    padding: 0;

    cursor: pointer;

    color: transparent;
    border: none;
    outline: none;
    background: transparent;
}
.slick-prev:hover,
.slick-prev:focus,
.slick-next:hover,
.slick-next:focus
{
    color: transparent;
    outline: none;
    background: transparent;
}
.slick-prev:hover:before,
.slick-prev:focus:before,
.slick-next:hover:before,
.slick-next:focus:before
{
    opacity: 1;
}
.slick-prev.slick-disabled:before,
.slick-next.slick-disabled:before
{
    opacity: .25;
}

.slick-prev:before,
.slick-next:before
{
    font-family: 'slick';
    font-size: 20px;
    line-height: 1;

    opacity: .75;
    color: white;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.slick-prev
{
    left: -25px;
}
[dir='rtl'] .slick-prev
{
    right: -25px;
    left: auto;
}
.slick-prev:before
{
    content: '←';
}
[dir='rtl'] .slick-prev:before
{
    content: '→';
}

.slick-next
{
    right: -25px;
}
[dir='rtl'] .slick-next
{
    right: auto;
    left: -25px;
}
.slick-next:before
{
    content: '→';
}
[dir='rtl'] .slick-next:before
{
    content: '←';
}

/* Dots */
.slick-slider
{
    margin-bottom: 30px;
}

.slick-dots
{
    position: absolute;
    bottom: -45px;

    display: block;

    width: 100%;
    padding: 0;

    list-style: none;

    text-align: center;
}
.slick-dots li
{
    position: relative;

    display: inline-block;

    width: 20px;
    height: 20px;
    margin: 0 5px;
    padding: 0;

    cursor: pointer;
}
.slick-dots li button
{
    font-size: 0;
    line-height: 0;

    display: block;

    width: 20px;
    height: 20px;
    padding: 5px;

    cursor: pointer;

    color: transparent;
    border: 0;
    outline: none;
    background: transparent;
}
.slick-dots li button:hover,
.slick-dots li button:focus
{
    outline: none;
}
.slick-dots li button:hover:before,
.slick-dots li button:focus:before
{
    opacity: 1;
}
.slick-dots li button:before
{
    font-family: 'slick';
    font-size: 6px;
    line-height: 20px;

    position: absolute;
    top: 0;
    left: 0;

    width: 20px;
    height: 20px;

    content: '•';
    text-align: center;

    opacity: .25;
    color: black;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.slick-dots li.slick-active button:before
{
    opacity: .75;
    color: black;
}

/* Custom */
.slide {
    display: block;
    width: 150px;
    height: 100px;
    background-color: tomato;
    color: white;
}

Slide 1A

Slide 2B

Slide 3C

Slide 4D

Slide 5E

Slide 6F

Comment: Thanks a lot, i know about initial slide but seems like i have a older version of slick library and now when i update it, its fine.


What can be said about ROC of binary classifier trained for data with inverted class labels when we know ROC of classifier for original class labels?

Question: In some domains we have negative/positive class well defined (assigned).
In general binary classification problem we can assign class labels in two ways.
When we have model trained for the original label assignment (its ROC), what can we infer about ROC (AUC especially) for model trained for inverted class assignment (using the same algorithm)?
Answer: If you invert the labels, you have
$$\mathrm{TPR}_1 = \mathrm{TNR}_{\text{inv}} = 1-\mathrm{FPR}_{\text{inv}}$$
and
$$\mathrm{FPR}_1= \mathrm{FNR}_{\text{inv}} = 1-\mathrm{TPR}_{\text{inv}},$$
where by $X_1$ I mean a property before inverting, and by $X_{\text{inv}}$ a property after inverting.
AUC plots TPR vs FPR, so inverting the labels will just flip your diagram: your new diagram will plot $\mathrm{TPR}_{\text{inv}} = 1-\mathrm{FPR}_1$ vs. $\mathrm{FPR}_{\text{inv}}=1-\mathrm{TPR}_1$. AUC will be unchanged. (AUC measures discriminative performance, so it would be worrying if it would change when inverting the labels. It is also known to be relatively unaffected by label imbalance, i.e., $P(Y=1)$, which you will also invert when inverting the labels)
Notice that in practice, results may still differ slightly due to randomness and / or model training implementation details.
Comment: @MLearner Hmm... so assuming you are using standard log loss / cross-entropy, the cost function will actually not change at all when flipping the labels (assuming the classification model to be symmetric wrt the labels), and so one would assume the optimization to converge to the same optimum (just inverted). Or am I missing something?
Comment: How do we know that after inverting labels, when we fit algorithm (from the scratch) to the input we get symmetrical result, eg. ${TP}_{\text{inv}}= TN_{\text{1}}$ ? It seems to me that $TP_{\text{inv}}= TP_{\text{1}} + c$ (and $FP_{\text{inv}}= FP_{\text{1}} + d$) for some appropriate c,d integers.
Comment: Indeed, if the model is fitted optimally for initial label assignment we can use it with flipped labels. Then the TP and FP rates are as you mentioned. It seems to me that it holds for every cost function that equally penalizes the estimated probability for both positive and negative actual/target class.


Can Scala method that returns a trait returns method with the same type as trait?

Question: I'm trying to write something that looks like this:
trait interface {
   getA(a:_): trA
}

trait trA extends (x => y)

and the trait is implemented like:
object obX extends interface {
   override def getA(a:_): x => y = X => ???
}

However, I get error
Overriding type a => x => y does not conform to base type a => trA

Even though trA takes in x => y. Is there a way to go around this? is my only option to modify trait interface like:
 trait interface {
   getA(a:_): x => y
}

Thanks in advance!
Comment: I'd recommend that you read a bit more about inheritance. Also maybe provide some concrete code so that we understand your goal in the end. Here `trA` doesn't bring any value for instance.
Answer:
Even though trA takes in x => y.

This is false. A trA is a x => y but the opposite is not true: x => y is not a trA. A trA cannot be built from a x => y.
Your defining your obX with a wider return type than your interface allows.
Answer: For example your code would compile if you could make trA not extend x => y but be it
type trA = x => y

Otherwise you can introduce a type
trait interface {
  type Out >: trA
  def getA(a: _): Out
}

object obX extends interface {
  type Out = x => y
  override def getA(a: _): x => y = X => ???
}


Functional Maximization

Question: So how do we solve a problem like this:
Find the function $s(x)$ such that $s(x)$ maximizes
$$\int_0^{s^{-1}(k)} s(x) dx $$
where  $x\in[0,10]$, $s(x)\in[0,1]$, and $k\in[0,1]$ ($k$ is a constant).
Thanks a lot guys. (So sry for my previous typos)
Comment: How can $x$ appear in both the integral and the upper limit? What is $g$? What space does $s$ lie in?
Comment: @copper.hat: Yea that's right, x is there in the limit of the integral. It's not a typo. I just add the characterization of g() in the question:)
Comment: Monoton increasing or decreasing?
Comment: increasing, sry for the confusion.
Comment: and it's strictly increasing actually
Comment: Then take $s(x) =1$ everywhere to get $g(1)$? I don't understand what you mean by making sure $x \in [0,10]$.
Comment: That's quite a change to the question. It invalidates all of the above.
Comment: @copper.hat Sry I was a bit confused. The problem should look like the one right now. I took it from a more complicated problem and that confused me. My bad.
Comment: Yea, and not sure if that's gonna be helpful: we can assume s(x) is strictly increasing if we need.
Comment: What do you mean by $x \in [0,10]$? $x$ is just a dummy variable of integration. Do you mean that the domain of $s$ is $[0,10]$? Also what do we do with $k$? For each function $s(x)$ do we take the maximal $k$?
Comment: @Soke: sry for the confusion. x∈[0,10] is just by its definition. It's like the domain of x is [0,10], and the limits of the integral are a subset of [0,10], which is already true since s(x)∈[0,1]. So I think we can simply ignore this extra condition. Also, for k, it's just a fixed constant, whose value is given. We don't choose k (and we CANNOT choose k since it's already fixed). Instead, we want to choose the optimal function s(x).
Comment: @larrybr So is $s$ also a function of $k$? Otherwise isn't that implicitly assuming that there is some function $s(x)$ for which every other function is lesser than it for every value of $k$?
Comment: @Soke: the inverse of s is a function of k. In other words, s(x) takes an x in 0 to 10 as its argument and maps it to a number between 0 and 1. For example, s(x)=0.1x, then s^(-1)(y)=10y. So if k=0.5, then s^(-1)(0.5)=5. For the same fixed k, different s^(-1) maps it to a different number in [0,10]. Does that make it clear?
Comment: Oh okay... though I'm still confused how it's possible to maximize this integral for $s$ when we're given a constant whose value we do not know. Surely the answer will be different if $k = 0$ versus if $k = 1$?
Comment: @Soke: Yea. I think the answer should depend on the k.
Answer: It seems to me that, if $s(x)$ is strictly increasing then for $x$ between 0 and $s^{-1}(k)$, we have $0<s(x)<k$.
Therefore:
$$\int_0^{s^{-1}(k)}s(x)dx < \int_0^{s^{-1}(k)}kdx = k*s^{-1}(k) <= k*10$$
let $s_n(x)$, for $n\in\{1,2,..\}$ be a sequence of functions with:
$$s_n(x) = k+(x-10)/n$$
Then $\int_0^{s^{-1}(k)}s(x)dx$ goes to 10*k when n goes to infinity.
So we should say there is no such strictly increasing s(x). But we can say that sup of this integral should be 10*k.
Comment: this is my first time using this system. I didn't mean to provide an answer, I only meant to add a comment.

Functional Maximization


Adding numbers in a object array

Question: var numbers = [{grades:[100,100,100]}];
var result = 0;

for (var i=0;i<numbers.length;i++){
    for (var p in numbers.grades[i]);

    result+=p+":"+numbers[i][p];
    //console.log(p+":"+numbers[i][p])
    console.log(result);
}

this is what i have so far. I know how to get all the numbers in the .grades but i want them all added up in a very simple way.
Answer: The problem you have is numbers.length is only 1. You want
numbers[0].grades.length; // 3

This should sum the grades for you
for (var i=0, sum=0; i<numbers[0].grades.length; i++) {
  sum += numbers[0].grades[i];
}

sum; // 300

If you have access to Array.prototype.reduce, you could use this
var sum = numbers[0].grades.reduce(function(a, b) { return a +  b; }, 0);

sum; // 300

Note .reduce requires ECMAScript >= 5 and will not work in IE <= 8
Comment: Great solution!  In this scenario it is safe to assume numbers[0], but we should wrap the reduce in a numbers.forEach function to enable any future development.
Answer: You almost had it
var numbers = [{grades:[100,100,100]}];
var result = 0;

for (var i=0;i<numbers.length;i++){
    for (var g=0; g<numbers[i].grades.length; g++) {

    result = result+numbers[i].grades[g];
    console.log(result);
    }
}

As discussed, if it does support ES5, you can write it like this:
var numbers = [{grades:[100,100,100]}];
var result = 0;

numbers.forEach( function(val) {
    result = result + val.grades.reduce( function (previousValue, currentValue, index, array) {
        return previousValue + currentValue;
    })
});

just remember that you need to loop through the numbers array, instead of giving it a default value of '0' // numbers[0]grades etc
Answer: or you can try:
for(var j=0; j<numbers.length;j++)
{
  for (var i=0, sum=0; i<numbers[j].grades.length; i++) {
    sum += numbers[j].grades[i];
  }
}
console.log(sum);

Answer: The list you want to loop through is :
var list = numbers[0].grades;

Then, inside the loop :
result += list[i];

That's it :)

How to browse a javascript array :
var a = ['I', 'need', 'the', 'basics'];
console.log(a[0]); // "I"
console.log(a[3]); // "basics"
console.log(a[a.length - 1]); // "basics"

How to browse a javascript object :
var o = { a: 'I', b: 'need', c: 'the', d: 'basics' };
console.log(o.a); // "I"
console.log(o.d); // "basics"
console.log(o['d']); // "basics"

All together :
var mixed = [{ a: 'foo' }, { b: 'bar' }, { c: ['baz'] }];
console.log(mixed[0].a); // "foo"
console.log(mixed[1].b); // "bar"
console.log(mixed[2].c[0]); // "baz"

To add up all grades :
var grades, i, j;
var sum = 0;
var list = [
    { grades: [1, 2, 3] },
    { grades: [4, 5, 6] }
];

for (i = 0; i < list.length; i++) {
    grades = list[i].grades;
    for (j = 0; j < grades.length; j++) {
        sum += grades[j];
    }
}

console.log(sum); // 21

Comment: @user3079589 Great :D But you should rather express your enthusiasm by voting or by accepting your favorite answer : http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235. Keep enjoying :D
Answer: A more functional/javascript approach would be to use array.reduce():
var sum = numbers[0].grades.reduce(function(previousValue, currentValue, index, array){
    return previousValue + currentValue;
});

console.log(sum);

Adding numbers in a object array


retornar mensagem ao usuário

Question: Como posso trocar a mensagem de "Faça o seu login" para "Bem Vindo, Usuário X". Na página index.html.
na index. html está assim

Faça o seu login!

após os dados digitados são passados para a valida
<form class="form-signin" method="POST" action="valida.php">

e na valida esta assim se caso o login der certo :
if(isset($resultado)){
            $_SESSION['usuarioId'] = $resultado['id'];
            $_SESSION['usuarioNome'] = $resultado['nome'];
            //$_SESSION['usuarioNiveisAcessoId'] = $resultado['niveis_acesso_id'];
            $_SESSION['usuarioEmail'] = $resultado['email'];
                        if($_SESSION['usuarioId'] == $resultado['id']){
                header("Location: index.php");
            }

Answer: Inicialmente o seu index deverá ser .php para conseguir fazer a mudança que irei dar como exemplo.
No index você coloca um if para verificar se existe uma session caso existir mostra uma div caso contrario mostra a de login. Exemplo:
index.php
if (isset($_SESSION['usuarioNome'])) {
   echo '
Bem Vindo, Usuário '.$_SESSION['usuarioNome'].'
';
}
else{
   echo '
Faça o seu login!
';
}

Comment: Vale ressaltar que o `session_start();` deve estar antes de qualquer saída do php para o navegador (geralmente nas primeiras do arquivo logo após a tag `
Comment: já tem o session_start() no seu projeto?
Comment: não vou testar agora com o session_start();
Comment: coloca ele antes da seguinte linha-> $_SESSION['usuarioId'] = $resultado['id'];
Comment: Muito obrigada, deu certo esse código que você me passou. Eu testei aqui, primeiro faço o meu login, depois aparece o nome do usuario que eu loguei apenas. Deus te abençoe pela ajuda!
Comment: De nada. Por gentileza marque a resposta como aceita.

retornar mensagem ao usuário


How to use choice on MULE to see if a database is up before sending message?

Question: On every message i receive on mule i log it into a database and route the message, but if the database is down for some reason it just stop routing the service, is it possible to check the database with choise, like if it is possible to connect before sending the message?
code:
<code><jdbc:connector name="jdbcConnector" dataSource-ref="WSA" validateConnections="false" queryTimeout="10" pollingFrequency="10000" doc:name="Database">
    <jdbc:query key="wsadb" value="insert into inbound_messages (payload, timestamp, agent, ip_from, endpoint, soap_operation) values ('', now(), #[groovy: return message.getInboundProperty('user-agent').toString()], #[groovy: return message.getInboundProperty('MULE_REMOTE_CLIENT_ADDRESS').toString()], #[groovy: return message.getInboundProperty('http.request').toString()], '');"></jdbc:query>
</jdbc:connector>

<flow name="log-request" doc:name="log-request">
    <vm:inbound-endpoint path="log-request.in" doc:name="VM"></vm:inbound-endpoint>
    <logger message="#[groovy: return message.getInboundProperty('user-agent').toString()], #[groovy: return message.getInboundProperty('MULE_REMOTE_CLIENT_ADDRESS').toString()], #[groovy: return message.getInboundProperty('http.request').toString()]" level="INFO" doc:name="Logger"></logger>
    <!--choice doc:name="Choice"-->
        <jdbc:outbound-endpoint exchange-pattern="one-way" queryKey="wsadb" responseTimeout="10000" queryTimeout="-1" connector-ref="jdbcConnector" doc:name="Persist raw message"></jdbc:outbound-endpoint>
    <!--/choice-->
</flow>
</code>
Answer: Consider using the until successful router:
http://www.mulesoft.org/documentation/display/current/Routing+Message+Processors#RoutingMessageProcessors-UntilSuccessful
Comment: That works too, the way ive found was just to change the queryTimeout="-1" to queryTimeout="10" so it doesnt stop working waiting for an answer :)


Atribuir valor a propriedade de um objeto por uma lista de objetos

Question: Tenho uma lista de objetos: List. Bem, esse objeto tem três propriedades, digamos, cnpj, acao e novaacao. Fiz um linq ou lambda e me trouxe todos os resultados, digamos duas linhas. Faço um foreach no resultado da linq ou lambda e como agora eu atribuo a cada propriedade do meu objeto através da lista desse objeto? Assim:
List<pdv> lista = new List<pdv>();
var resultado = (from ...).ToList();

foreach(var r in resultado)
{
   lista.Add(r.cnpj);//ISSO DÁ ERRO
}

Dessa forma, eu mostro apenas um cnpj, sendo que há dois. Sempre o último. novo é do tipo PDV criado antes.
if (resultadoPdv.Count > 0 && resultadoAcao.Count > 0)
            {
                foreach (var r in resultadoPdv)
                {
                    novo.cnpj = r.Cnpj;
                    lista.Add(novo);
                }

                foreach (var r in resultadoAcao)
                {
                    novo.acao = r.acao;
                    novo.proximaAcao = r.proximaacao;
                    lista.Add(novo);
                }
            }

            return lista;

Nesse código, eu consigo ter dois registros, ou seja, a lista tem duas linhas, mas com o mesmo cnpj e eu tenho dois cnpj diferentes.
foreach (var r in resultadoAcao)
                {
                    novo.acao = r.acao;
                    novo.proximaAcao = r.proximaacao;
                }

                foreach (var r in resultadoPdv)
                {
                    novo.cnpj = r.Cnpj;
                    lista.Add(novo);
                }

Veja como fica o xml de retorno do web service
<ArrayOfPdvNovo xmlns="http://schemas.datacontract.org/2004/07/V99SuporteTecnicoContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<PdvNovo>
<acao>Visita Técnica</acao>
<cnpj>03146478000112</cnpj>
<proximaAcao>Agendamento de Visita Técnica Parceiro</proximaAcao>
</PdvNovo>
<PdvNovo>
<acao>Visita Técnica</acao>
<cnpj>03146478000112</cnpj>
<proximaAcao>Agendamento de Visita Técnica Parceiro</proximaAcao>
</PdvNovo>
</ArrayOfPdvNovo>

Pela resposta do Harry, alterei e ficou assim:
PdvNovo novo = new PdvNovo();

            if (resultadoPdv.Count > 0 && resultadoAcao.Count > 0)
            {
                foreach (var r in resultadoAcao)
                {
                    novo.acao = r.acao;
                    novo.proximaAcao = r.proximaacao;
                    //lista.Add(novo);
                }

                foreach (var r in resultadoPdv)
                {
                    PdvNovo _cnpj = new PdvNovo();
                    _cnpj.cnpj = r.Cnpj;
                    _cnpj.acao = novo.acao;
                    _cnpj.proximaAcao = novo.proximaAcao;
                    lista.Add(_cnpj);
                }
            }

Comment: Estou perguntando isso, porque se eu retorno o tipo pdv e se eu tiver dois cnpj, ele só mostra um, o último, claro. E preciso que ele me liste todos os cnpj na questão.
Comment: Dá erro porque a List é tipada (pdv) e você ta passando texto, eu acho que isso você já sabe?
Comment: `novo` ta instanciado fora do for?
Comment: Sim, está usando a mesma instância! coloque dentro do for que ele criara para cada item da lista um instância diferente, por isso há repetição no seu arquivo. Olha no meu exemplo eu postei a solução!
Answer:
Assim:
List<pdv> lista = new List<pdv>();
var resultado = (from ...).ToList();

foreach(var r in resultado)
{
   pdv _item = new pdv(); // instancie dentro do for!
   _item.cnpj = r.cnpj; // da um enter aqui e vai colocando os outros campos ...
   lista.Add(_item);
}


Android: How to fit GridView automatically to all screensizes?

Question: I've written a little app, it is my first android app. It's an infrared TV remote app, I developed using a Samsung Galaxy S4, where everything seems to be running fine.
This is how it looks on my Galaxsy S4: Screenshot Samsung Galaxy S4
But since I've published to play store I got another screenshot from a Galaxy Note 2 user where it looks really messed up and does not fit to his screen: Screenshot Samsung Galaxy Note 2
This is my fragment's layout code,
fragment_page1.xml
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<GridLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical"
    android:rowCount="7"
    android:columnCount="5"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true">

    // POWER

    <ImageButton
        android:onClick="pressPowerButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:id="@+id/power"
        android:layout_row="0"
        android:layout_column="0"
        android:src="@drawable/stand_by"
        android:layout_marginTop="1.5dp"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="SLEEP"
        android:id="@+id/sleep"
        android:textColor="#2299bb"
        android:textSize="12dp"
        android:layout_row="0"
        android:layout_column="1"
        android:layout_marginTop="1.5dp"
        />

    // VOLUME

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Vol +"
        android:id="@+id/volUp"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:layout_row="1"
        android:layout_column="0"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Vol -"
        android:id="@+id/volDown"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:layout_row="2"
        android:layout_column="0"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Mute"
        android:id="@+id/mute"
        android:textColor="#2299bb"
        android:layout_row="3"
        android:layout_column="0"
        />

    // PROGRAM
    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Ch +"
        android:id="@+id/progUp"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:layout_row="1"
        android:layout_column="4"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Ch -"
        android:id="@+id/progDown"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:layout_row="2"
        android:layout_column="4"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="CH LIST"
        android:id="@+id/chList"
        android:textColor="#2299bb"
        android:textSize="12dp"
        android:layout_marginTop="-2dp"
        android:layout_row="3"
        android:layout_column="4"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Info"
        android:id="@+id/info"
        android:textColor="#2299bb"
        android:layout_row="2"
        android:layout_column="3"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Guide"
        android:id="@+id/guide"
        android:textColor="#2299bb"
        android:layout_row="1"
        android:layout_column="3"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="A"
        android:id="@+id/red"
        android:textColor="#cc2200"
        android:textStyle="bold"
        android:layout_row="3"
        android:layout_column="3"
        />

    // MENU

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Menu"
        android:id="@+id/menu"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-1.5dp"
        android:layout_row="1"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Internet\n\@TV"
        android:id="@+id/internet"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-9.5dp"
        android:layout_row="1"
        android:layout_column="2"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Media\nPlay"
        android:id="@+id/media"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-9dp"
        android:layout_row="2"
        android:layout_column="2"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Tools"
        android:id="@+id/tools"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-2dp"
        android:layout_row="2"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Source"
        android:id="@+id/source"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-2dp"
        android:layout_row="3"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="Content"
        android:id="@+id/content"
        android:textColor="#777777"
        android:textSize="12dp"
        android:layout_marginTop="-2.5dp"
        android:layout_row="3"
        android:layout_column="2"
        />

    // NAVIGATE

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25b2"
        android:id="@+id/up"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_marginTop="-4.5dp"
        android:layout_row="4"
        android:layout_column="2"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25bc"
        android:id="@+id/down"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_row="6"
        android:layout_column="2"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25c0"
        android:id="@+id/left"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_row="5"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u23ea"
        android:id="@+id/rewind"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="15dp"
        android:layout_marginTop="-2.5dp"
        android:layout_row="5"
        android:layout_column="0"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u23e9"
        android:id="@+id/forward"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="15dp"
        android:layout_marginTop="-2.5dp"
        android:layout_row="5"
        android:layout_column="4"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25b7"
        android:id="@+id/play"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="30dp"
        android:layout_marginTop="-1dp"
        android:layout_row="4"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="II"
        android:id="@+id/pause"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_marginTop="-4dp"
        android:layout_row="4"
        android:layout_column="3"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25a0"
        android:id="@+id/stop"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_row="6"
        android:layout_column="3"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="EXIT"
        android:id="@+id/exit"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="12dp"
        android:layout_marginTop="-4dp"
        android:layout_row="6"
        android:layout_column="4"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25cf"
        android:id="@+id/record"
        android:textColor="#777777"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_row="6"
        android:layout_column="1"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="\u25b6"
        android:id="@+id/right"
        android:textColor="#2299bb"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_row="5"
        android:layout_column="3"
        />

    <Button
        android:onClick="pressButton"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="ENTER"
        android:id="@+id/ok"
        android:textColor="#118844"
        android:textStyle="bold"
        android:textSize="12dp"
        android:layout_marginTop="-3dp"
        android:layout_row="5"
        android:layout_column="2"
        />

    <Button
        android:onClick="pressButton"
        android:clickable="true"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text="RETURN\u21b6"
        android:id="@+id/back"
        android:textColor="#cc2200"
        android:textStyle="bold"
        android:textSize="12dp"
        android:layout_marginTop="-14dp"
        android:layout_row="4"
        android:layout_column="4"
        />

// PLACEHOLDER

    <Button
        android:clickable="false"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text=""
        android:id="@+id/placeHolder1"
        android:textSize="8dp"
        android:layout_row="0"
        android:layout_column="2"
        />

    <Button
        android:clickable="false"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text=""
        android:id="@+id/placeHolder2"
        android:textSize="8dp"
        android:layout_row="0"
        android:layout_column="3"
        />

    <Button
        android:clickable="false"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:id="@+id/placeHolder3"
        android:textSize="8dp"
        android:layout_row="0"
        android:layout_column="4"
        />

    <Button
        android:clickable="false"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text=""
        android:id="@+id/placeHolder4"
        android:textSize="12dp"
        android:layout_row="4"
        android:layout_column="0"
        android:layout_marginTop="-7dp"
        />

    <Button
        android:clickable="false"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:text=""
        android:id="@+id/placeHolder5"
        android:textSize="12dp"
        android:layout_row="6"
        android:layout_column="0"
        android:layout_marginTop="-4dp"
        />
</GridLayout>

</RelativeLayout>

This is from
MainActivity.java
public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener

{
/* swipe view */
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private android.app.ActionBar actionBar;

// tab titles
private String[] tabs = { "Basic", "Advanced", "Settings"};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /* init swipe views */
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(mAdapter);

    actionBar = getActionBar();
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    for (String tabName : tabs)
        actionBar.addTab(actionBar.newTab().setText(tabName).setTabListener(this));

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

}
So how can I improve this?
I've read articles and other post about it but nothing did work for me so far. I've tried combinations of fill_parent and match_parent, wrap_content for GridView, RelativeLayout tried other elements like GridLayout, LinearLayout and TableLayout, but I still don't get it :(
I know I use some bad workarounds like android:layout_marginTop="-2dp", without such workarounds I dont manage to display it correctly on my Galaxy S4. How to get rid of margins?
So what I'm ultimatively looking for is an automatically scaling GridView with 5 columns and 7 rows that displays all buttons correctly also on larger screens.
Do I need to do this programmatically or is there a solution using the layout file only?
I'd be so happy if somebody can help me out of trouble!
Comment: If somebody wants to download a copy, its already avaible on Play Store: https://play.google.com/store/apps/details?id=org.tzapp.smote
Comment: you just need to create multiple xml's and check if screen height/width is greater than, equal to and less than
and in all three cases mention number of grid different
Comment: Also when you are going to inflate xml inside the .java class there you inflate xml of which case it meet the criteria.
Comment: Ok, still dont get it. Can you give an example please? Multiple xml's for what kind of elements?
Comment: **Does anybody have another solution please?**
Answer: You need to adjust the height and width of grid item cell dynamically.
First you need to decide how many cell you want to show in grid row.
Set grid of cell 3 in xml.
Let's suppose you have Three cell for grid for each screen.
In your YourActivity.java file
Dynamically calculate width of screen.
Then decide the aspect ratio with how much width you want what height.
Algorithm :
expectedWidth = (screenWidth/number of cell) - ((padding or marjin between one cell to other)* (number of cell +1)  )
expectedHeight = expectedWidth*aspect ratio

you can adjust Aspect ratio for your proper height


Does detaching a div and appending it increase memory?

Question: I would like to know if detaching a div on load and appending that same div on a click will increase memory? When you detach a div (filled with images) is the div and image information kept in memory?
For example:

 var divContainingImage = $("#divContain-one").detach();

$("button").click(function(){
      $("#divContain-two").append(divContainingImage);
});

Comment: The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time. So if the elements are detached, they should still be in memory and available to be re-attached in the DOM, pending browser compatibility.
Comment: The answer probably depends 100% on how the particular browser/JS engine decides to handle it.
Answer: It shouldn't increase memory usage significantly. The variable simply contains a reference to same memory that held the DOM element, and any related jQuery data, before it was detached. All that has happened is that the DOM itself no longer has a reference to that memory.
When you append it, you don't increase the memory, either. It simply adds a reference to the same object to the new location in the DOM, it doesn't make a copy.
The information has to be kept in memory -- how else could it know what to add to the DOM when you append?
One caveat: the act of calling $("#divContainingImage") creates a jQuery object that wraps around the DOM element, and the variable contains a reference to this object, not just the DOM element. This does increase memory usage, independent of what .detach() does.
Comment: @Tamango It's the same memory they used before they were detached. So if he has a million elements in the DOM, and detaches them, the memory doesn't increase due to detaching. But it also doesn't decrease, since there are variables keeping them from being GCed.
Comment: I totally agree that memory usage is not significant in this case. But maybe author uses it for hudnreds of elements so he is interested if it will affect memory in such situation.
Answer: According to jquery documentaion detach method keeps all data associated with the removed element.
So, yes, especially taking the fact that you declared a variable and assigned returned data from detach method to it - data is definitely stored in memory. Anyway, keep in mind, that such memory usage is not significant if we are not talking about hundreds or thousands of elements.
Answer: You also need to consider if there are event listeners attached to the DOM object.
If you remove an object from the page then the memory can eventually be cleaned once there are no more references to it.
If you remove a  and the  has a click listener then that  can continue to sit in memory indefinitely. Remove the listeners first then remove the DOM object. That way the DOM object can be removed from memory eventually.


Pagination with neo4j (Graph DB)

Question: Currently am working in NEO4J and iam new in graph db. Now i need to paginate the records from graph db. And i created the following query
MATCH (n:Question)<-[r1:HAS_QUESTION]-(c:Chapter)
MATCH (c)-[r2:HAS_CHILD]->(t:Topic)-[r3:HAS_QUESTION]->(qstn:Question)
WHERE ID(c)=330
WITH n,qstn WHERE NOT(n:Removed) AND NOT(qstn:Removed)
WITH n,qstn
RETURN n as Question,qstn

In this query i got 13 question nodes. But when i add skip and limit to that query , i got only 7 nodes instead of 10. The querys is
MATCH (n:Question)<-[r1:HAS_QUESTION]-(c:Chapter)
MATCH (c)-[r2:HAS_CHILD]->(t:Topic)-[r3:HAS_QUESTION]->(qstn:Question)
WHERE id(c)=330 WITH n,qstn
WHERE NOT(n:Removed) AND NOT(qstn:Removed)
WITH n,qstn
RETURN n as Question,qstn
SKIP 0 LIMIT 10;

Somebody please explain what is happening with this query. Is there any idea to get the 10 nodes.
The query for the sample graph is the following.
CREATE (c:Chapter {chapter_name:"Biodiversity and Conservation"})

CREATE (t:Topic {topic_name:"Biodiversity Conservation"})
CREATE (q:Question {content: "first question"})

CREATE (t1:Topic {topic_name:"Biodiversity"})
CREATE (q1:Question {content: "second question"})

CREATE (q0:Question {content: "third question"})
CREATE (q01:Question {content: "fourth question"})
CREATE (q2:Question {content: "fifth question"})
CREATE (q3:Question {content: "sixth question"})
CREATE (q4:Question {content: "seventh question"})
CREATE (q5:Question {content: "eighth question"})
CREATE (q6:Question {content: "nineth question"})
CREATE (q7:Question {content: "tenth question"})
CREATE (q8:Question {content: "eleventh question"})
CREATE (q9:Question {content: "twelfth question"})
CREATE (q10:Question {content: "thirteenth question"})
CREATE (q11:Question {content: "fourteenth question"})
CREATE (q12:Question {content: "fifteenth question"})
CREATE (q13:Question {content: "sixteenth question"})

CREATE (c)-[r:HAS_TOPIC]->(t)
CREATE (c)-[r1:HAS_TOPIC]->(t1)

CREATE (t)-[r2:HAS_QUESTION]->(q)
CREATE (t1)-[r3:HAS_QUESTION]->(q1)

CREATE (c)-[r4:HAS_QUESTION]->(q0)
CREATE (c)-[r5:HAS_QUESTION]->(q01)
CREATE (c)-[r6:HAS_QUESTION]->(q2)
CREATE (c)-[r7:HAS_QUESTION]->(q3)
CREATE (c)-[r8:HAS_QUESTION]->(q4)
CREATE (c)-[r9:HAS_QUESTION]->(q5)
CREATE (c)-[r0:HAS_QUESTION]->(q6)
CREATE (c)-[r11:HAS_QUESTION]->(q7)
CREATE (c)-[r12:HAS_QUESTION]->(q8)
CREATE (c)-[r13:HAS_QUESTION]->(q9)
CREATE (c)-[r14:HAS_QUESTION]->(q10)
CREATE (c)-[r15:HAS_QUESTION]->(q11)
CREATE (c)-[r16:HAS_QUESTION]->(q12)
CREATE (c)-[r17:HAS_QUESTION]->(q13)

return c,t,t1,q0,q01,q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11,q12,q13,r,r1,r2,r3,r4,r5,r6,r7,r8,r9,r0,r11,
r12,r13,r14,r15,r16,r17

Answer: Which version do you use?
Can you share your graph so that we can reproduce the issue?
I simplified your query, could you try this one?
MATCH (n:Question)<-[:HAS_QUESTION]-(c:Chapter)
WHERE id(c)=330 AND NOT(n:Removed)
MATCH (c)-[:HAS_CHILD]->(t:Topic)-[:HAS_QUESTION]->(qstn:Question)
WHERE NOT(qstn:Removed)
RETURN n,qstn
SKIP 0 LIMIT 10;

Comment: And your graph structure is not enough, please provide the full cypher statement to create your sample graph.
Comment: My version is Neo4j 2.2.0
Comment: Graph structure is the following : Chapter-[:HAS_CHILD]->Topic .Question node is a child of both Chapter and Topic node. Then i need to get all the active question nodes under that chapter.
Comment: The above query returns the same answer.
Comment: Is pagination is possible with graph db? (Not for a single node. When there is multiple relations it is not working properly in my case.)
Comment: Sure, it is. It is a basic functionality, it rather seems you ran into a bug.
Comment: Could you try to prefix your query with "PLANNER RULE "
Comment: Sorry for the late reply.The query for the sample graph is given with the question now.
Answer: I simplified my query in the following way.. Now it is working without any problem
START c = node({chapter_id})
OPTIONAL MATCH c-[r*..2]->(n:Question)
WHERE NOT(n:Removed)
RETURN DISTINCT n SKIP 0 LIMIT 10;

Pagination with neo4j (Graph DB)


update user's profile field from another form

Question: Here is what I need to achieve:

There is field "linkedIn url" in user's profile entity.
There is Event registration form on the website.
In the Event Registration form I would like to render field "linkedIn url" with value from the user's profile entity.
When user submits the Event Registration I want to save a value of the field to the database (to user profile entity of course).

Any suggestions? thx!

EDIT:
I implemented this functionality.
For those interested, complete source code is below:
(Note that I'm saving data to profile2!)
/**
*
* Implements hook_form_alter
*
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id == 'registration_form') {
            $profile = profile2_load_by_user($user->uid); // Load profile2 data
            if ($profile['main']->field_linkedin_url) {
                $linkedin_url = $profile['main']->field_linkedin_url['und'][0]['value'];
            }
            $form['linkedin_url'] = array( // Add field to form
                '#type' => 'textfield',
                '#title' => t('Your LinkedIn profile'),
                '#default_value' => isset($linkedin_url) ? $linkedin_url : '',
                '#maxlength' => 255,
                '#size' => 60,
                '#description' => t('Please enter your LinkedIn profile URL'),
                '#weight' => 10,
            );
            $form['#submit'][] = 'entity_registration_custom_registration_form_submit'; // Call custom submit handler

    }
}

/**
*
* Custom Form Submit Handler
*
*/
function  MYMODULE_MYFORM_submit($form, &$form_state){
    global $user;
    $profile = profile2_load_by_user($user->uid); // Load profile2 data
    $profile['main']->field_linkedin_url['und'][0]['value'] =  $form_state['values']['linkedin_url']; // Set new value for Profile2 field
    profile2_save($profile['main']);
    drupal_set_message(t('Submit handler works!'));
}

Comment: Anyone to help with this one?
Answer: You have to modify your form in a hook_form_alter : and the linked_in url will appear in the event registration form
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){

      // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $form['linkedin_url']['und'][0]['url']['#default_value'] = $user->linkedin_url['und'][0]['url'];
   }
}

If you don't want to expose the linked_in field during the form do this :
function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){
     // Hide your field
     $form['linkedin_url'][und]['#access']  = false;
     //Add another submit function
      $form['actions']['submit']['#validate'][] = 'mymodule_eventregistration_validate_form_alter';
   }
}

// Your submit function
function mymodule_eventregistration_validate_form_alter($form, $form_alter){

     // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $linkedin_url = $user->linkedin_url['und'][0]['url'];

    form_set_value($form['linkedin_url'], array('und' => array(0 => array('url' => $linkedin_url))), $form_state);
}

Comment: In this case, use the second example and add not a 'validate' function, but a 'submit' function. Il this submit function, load the user ($account = user_load($user->uid)) and add the linked_in url from the form value ($account-> linkedin_url['und'][0]['url'] = $form_state['values']['linkedin_url']['und'][0]['url']), and save the user (user_save($account));
Comment: that's great! Thx for pointing me in the right direction. As far as I understand, the above's example saves the linkedin_url to the event node, but I want linkedin_url to be saved to User entity instead. What hook can I use for that? Also how can I avoid saving linkedin_url to event node? THX!
Comment: That's it! Thank you bobylapointe! You are the man! :)


Open source antivirus/antispam/web filtering gateway

Question:
Possible Duplicate:
Open Source Unified Threat Management Software Options

I want to install firewall which have following features Antispam, Anti Virus, Webfiltering, Userwise access, Intrusion prevention etc. is any product from open source )(ie untangle/ipcop) any other solution for the above implementation if any one can help me with this.
Comment: This is similar to this other question: http://serverfault.com/questions/27570/open-source-unified-threat-management-software-options/27584#27584
Comment: Don't forget the paradox of defense in depth -- which is that the more security products you layer into your perimeter, the more you increase your chances that one of those products will itself have a security vulnerability that will open your network to compromise. Have you thought through exactly what security features you need and why?
Answer: Pfsense can do most of this if you add extra packages which are easily installable inside the distribution. It is also very stable and intuitive to use.
Answer: Look at Endian Firewall
Endian Download

The Endian Firewall is an open source Linux distribution that specializes on Routing/Firewalling and Unified Threat Management


AIC for nested models: is the AIC of a smaller model A always smaller than that of the nesting model B?

Question: Is it true that if models A and B are such that the covariates of B are a subset of A, the AIC of model A is always smaller than that of model B? Why?
Comment: And to state the obvious: AIC does not need nested models.
Answer: No, it is not true. The penalty term $2p$ may give you a worse AIC for the model with more parameters.
Answer: To add on F. Tusell's answer: the AIC (but also other model selection criteria, such as the BIC or the HQC) contains two terms:

A likelihood term, which measures the ability of the model to explain the observed data;
A regularization term, which penalizes the complexity of the model (i.e. its number of free parameters).

The point of the latter term is precisely to avoid overfitting and to allow that the selected model will generalize well to unobserved data, i.e. to avoid that the more complicated model will be necessarily selected. This can be interpreted as a form of Occam's razor: if two models explain the data equally well, the simpler one should be favored.


Form groups with must-include and must-exclude constraints

Question: Given a set of vertices $V$, and for each $v \in V$, two sets of vertices $Y_v$ and $N_v$ where $Y_v \subseteq V$ and $N_v \subseteq V$.
Determine if it is possible to form one or more subsets of $V$ so that each vertex is used exactly once (can't reuse; and each $v$ must be in some subset of $V$), and for each $v'$ in each subset $S$, $\forall y_{v'}\in Y_{v'}, y_{v'} \in S$ (all vertices in must-include list of any vertex must exist in the same subset as that vertex) and $\forall n_{v'}\in N_{v'}, n_{v'} \notin S$ (all vertices in must-exclude list of any vertex must not exist in the same subset as that vertex).
Answer: Hint:

Define $v \rhd u \iff u \in Y_v$ and let $v \diamond u$ be its reflexive, symmetric, transitive closure.
Check if $[v]_\diamond$, the equivalence class of $v$ with regard to $\diamond$ satisfies $[v]_\diamond \cap N_v = \varnothing$ for every $v \in V$.

I hope this helps $\ddot\smile$


The abc conjecture and the existence of finite number of solutions for the Beal's problem

Question: In this page, I am not interested on the Beal conjecture itself. But I am interested on the following problem:

The author claimed:
The  abc conjecture would imply that there are at most finitely many counterexamples to Beal's conjecture.

My question is: Is there are a proof for this claim.
Comment: Really?  How about start with the statement of Beal's conjecture and abc conjecture.  Do you not see an obvious choice for a, b and c?
Comment: Can you please explain where you get stuck?  Do you understand the statement of abc?  For instance, it is pretty clear that $\text{rad}(A^x B^y C^z) \le ABC$.
Comment: @ErickWong: Yes, but I cannot continue with this.
Comment: You wrote "I have no idea to start".
Comment: @ErickWong: Yes removed.
Comment: @ErickWong: If the abc conjecture is true then there exist a finite number of solutions for the Beal's problem.
Comment: Yes, there is a proof for this claim.
Answer: In fact, for any positive $\epsilon < 1/12$ the inequality given in the $abc$-conjecture
$$
rad(abc) > c_{\epsilon}c^{1-\epsilon}
$$
with an explicit value of $c_{\epsilon}>0$ yields
an explicit upper bound on $x^p, y^q, z^r$ in any counterexample to Beal's conjecture. By the $abc$-conjecture, there are only finitely many such $(a,b,c)$-triples.


Find the sum of squares of the real solutions to $\sqrt[3]{5x - 2} = \frac{1}{5}(x^3 + 2)$

Question:
Find the sum of squares of the real solutions to $\sqrt[3]{5x - 2} = \frac{1}{5}(x^3 + 2)$

I tried applying Viete's formulas after raising everything to the third power, however computing $\sum_{k = 1}^9 x_k^2$ also includes complex solutions, yet the problem only asks us for real solutions.
One can easily spot that $x_1 = 2$ is a solution, and Wolfram Alpha states the other two solutions are $x_2 = \sqrt{2} - 1$ and $x_3 = -\sqrt{2} - 1$, therefore the sum should be 10. However, how could I prove this mathematically?
Thank you very much for your help!
Answer: $\sqrt[{\mathrm{3}}]{\mathrm{5}{x}−\mathrm{2}}=\frac{\mathrm{1}}{\mathrm{5}}\left({x}^{\mathrm{3}} +\mathrm{2}\right) \\ $
$\Leftrightarrow\mathrm{5}\sqrt[{\mathrm{3}}]{\mathrm{5}{x}−\mathrm{2}}={x}^{\mathrm{3}} +\mathrm{2} \\ $
$\mathrm{Let}:\:{a}=\sqrt[{\mathrm{3}}]{\mathrm{5}{x}−\mathrm{2}}\Rightarrow{a}^{\mathrm{3}} =\mathrm{5}{x}−\mathrm{2} \\ $
$\mathrm{From}\:\mathrm{the}\:\mathrm{given}\:\mathrm{equation}\:\mathrm{we}\:\mathrm{have} \\ $
$\begin{cases}{\mathrm{5}{a}={x}^{\mathrm{3}} +\mathrm{2}}\\{\mathrm{5}{x}={a}^{\mathrm{3}} +\mathrm{2}}\end{cases} \\ $
$\Rightarrow\mathrm{5}\left({a}−{x}\right)={x}^{\mathrm{3}} −{a}^{\mathrm{3}} =\left({x}−{a}\right)\left({x}^{\mathrm{2}} +{ax}+{a}^{\mathrm{2}} \right) \\ $
$\Leftrightarrow\left({a}−{x}\right)\left({x}^{\mathrm{2}} +{ax}+{a}^{\mathrm{2}} +\mathrm{5}\right)=\mathrm{0} \\ $
$\Leftrightarrow{a}={x}\:\mathrm{or}\:{x}^{\mathrm{2}} +{ax}+{a}^{\mathrm{2}} +\mathrm{5}=\mathrm{0} \\ $
$\mathrm{But}:\:{x}^{\mathrm{2}} +{ax}+{a}^{\mathrm{2}} +\mathrm{5}=\left({x}+\frac{{a}}{\mathrm{2}}\right)^{\mathrm{2}} +\frac{\mathrm{3}{a}^{\mathrm{2}} }{\mathrm{4}}+\mathrm{5}\neq\mathrm{0} \\ $
$\Rightarrow{a}={x}\Leftrightarrow{x}^{\mathrm{3}} =\mathrm{5}{x}−\mathrm{2}\Leftrightarrow{x}^{\mathrm{3}} −\mathrm{5}{x}+\mathrm{2}=\mathrm{0} \\ $
$\Leftrightarrow{x}=\mathrm{2},{x}=−\mathrm{1}\pm\sqrt{\mathrm{2}}\Rightarrow\mathrm{Sum}\:\mathrm{of}\:\mathrm{squares}=\mathrm{10} \\ $
Answer: Here $\displaystyle f(x)=\frac{x^3+2}{5}.$ Then $\displaystyle f^{-1}(x)=(5x-2)^{\frac{1}{3}}$
So we have to find number of solution of $\displaystyle f(x)=f^{-1}(x)$
Which equals $f(x)=x\Longrightarrow x^3+2=5x$
(Because inverse function is symmetrical about $y=x$ line)
So $\displaystyle x^3-5x+2=0\Longrightarrow x=2\,\ ,-1\pm \sqrt{2}$
Comment: @nonuser if $f(x)$ is continuous and increasing over the domain then only $ f(x) =x$ is the solution of $f(x)=f^{-1}(x)$.  Here $f(x)$ is increasing over the entire domain, hence it works.
Comment: @SamarKamboj, For more details have a look at this Note by Ng Wee Leng and Ho Foo Him which I barrow the example from: https://www.atm.org.uk/journal/archive/mt228files/atm-mt228-39-42.pdf
Comment: $f(x)=f^{-1}(x) \implies f(f(x))= x$ not $f(x)=x$
Comment: @SamarKamboj And?
Comment: Your method works here but it will not work everywhere. For instance if $f(x)=\sqrt{7-3x}$, then $f^{-1}(x)=(7-x^2)/3$ and solving $f(x)=x$ only gives us the solution $x=(-3+\sqrt{37})/2$ but we have other solutions like $x=1$ or $x=2$.
Comment: @SamarKamboj, Well, considering the other inverses in other domains does not get all the answers necessarily . The problem with your argument in looking for answers of $f(x)=x$ instead of $f(x)=f^{-1}(x)$, is that you assume that $f$ and $f^{-1}$ intersects only on the line $y=x$, but actually it is the case only if they have some fixed points in their domain. Now if we look at the example $f(x)=\sqrt{7-3x}$ with $f^{-1}=(7-x^2)/3$, we see that $x=1$ is a solution for $f(x)=f^{-1}(x)$ but it is not a fixed point.
Comment: @DyakoSoltanian Thanks for the clarification.


a functional inequality (positive functions on circle)

Question:
I am trying to prove the following inequality but have no idea at all. Does anyone have any idea how to tackle it or know some related sources?
$$\frac{\int_0^{2\pi}(\frac{1}{2}\frac{f^2}{g}\frac{dg}{ds}+3f\frac{df}{ds})^2g+v(-\frac{1}{v}f^3g+\frac{d^2f}{ds^2})^2+kvf^6g\ ds}{\int_0^{2\pi}f^4g+v(\frac{df}{ds})^2\ ds}\geq \min(1,kv)$$
where $f,g$ are smooth positive periodic functions, $\int_0^{2\pi}f\ ds=2\pi$, and $k,v$ are positive constants.

It arises from a geometric problem. It is controlled by $1$ if let $g$ tends to the zero function, while controlled by $kv$ if $f=1$. I have tried some examples in python and it does seem that $min(1,kv)$ should be a valid bound. Indeed any bound independent of $f,g$ would be useful for my purpose, $min(1,kv)$ is my conjectured optimal bound. Any help would be appreciated.
Some updates:
A counterexample is already given by @abacaba below, but I still wonder if some other bound might exist (could depend on k,v, but not on f,g).
If we change the term $(\frac{1}{2}\frac{f^2}{g}\frac{dg}{ds}+3f\frac{df}{ds})^2g$ in the numerator to $(\frac{1}{2}\frac{f^2}{g}\frac{dg}{ds}+\alpha f\frac{df}{ds})^2g$ for any $\alpha\in (-\infty,\frac{3}{2}),$ then a valid bound would be $$\sup_{\epsilon\in(0,\frac{1}{2\pi}),\rho\in\mathbb{R}^+}\min(\frac{(1-\sqrt{2\pi\epsilon})^6}{(1+\sqrt{2\pi\epsilon})^4}kv,\frac{\delta}{\rho+1},\sqrt{\frac{2\delta\rho\epsilon kv}{\pi}}),$$ where $\delta=min(\frac{3}{2}-\alpha,1).$
On the other hand, for $f$ very close to a constant function, in the sense that $\sup_{x\in[0,2\pi]} |\frac{df}{ds}|^2(x)<\mu$, where $\mu$ is some small constant only depends on $v$, a valid bound would be $$\min(\frac{(1-2\pi\sqrt{\frac{\mu}{v}})^6}{(1+2\pi\sqrt{\frac{\mu}{v}})^4}kv,1)-10\frac{(1+2\pi\sqrt{\frac{\mu}{v}})^2}{(1-2\pi\sqrt{\frac{\mu}{v}})^4}\frac{\mu}{v}.$$ Notice that for $\mu$ small enough, the above bound is always positive.
Comment: How about $g = 1$, $f = s + 1 - \pi$, $v = 500$ and $k = 1/500$?
Comment: Sorry I forgot to add that $f,g$ are smooth @RiverLi. The geometric context is that they are smooth functions on a circle. Otherwise the basic inequality $\frac{\int (\frac{d^2f}{ds^2})^2}{\int (\frac{df}{ds})^2}\geq 1$ would not hold.
Comment: @Richard Something is weird. The quantity $kv$ is homogeneous on the right hand side but not on the left hand side.
Comment: @mathworker21 Yes, but it seems that the inequality should still hold. Actually if let $k=0$, then LHS could get arbitrarily small. So we need $k>0$ to get a nontrivial bound.
Answer: I think this inequality might not be true.
First take $g = f^{-6}$ and $kv = 1$. Then the first term in the numerator vanishes, so we are left with
$$\int_0^{2\pi} v\left(-\frac{1}{v} f^{-3} + \frac{d^2 f}{ds^2}\right)^2 + 1 ds \geq \int_0^{2\pi} f^{-2} + v\left(\frac{df}{ds}\right)^2 ds.$$
Then we can take say $f = 1 + 0.5\cos s$. This ensures that the integral of $(df/ds)^2$ and $(d^2 f / ds^2)^2$ are the same, so the inequality becomes
$$\int_0^{2\pi} \frac{1}{v}f^6 -2f^{-3}\frac{d^2 f}{ds^2} + 1 ds \geq \int_0^{2\pi} f^{-2} ds.$$
You can check that
$$ \int_0^{2\pi} f^{-3}\frac{d^2 f}{ds^2} ds = 3\int_0^{2\pi} f^{-4} \left(\frac{d f}{ds}\right)^2 ds \geq 0.$$
On the other hand, by C-S we have
$$\int_0^{2\pi} f^{-2} ds > 2\pi.$$
So when $v \to \infty$, the inequality cannot hold.


programmatically collapse or expand selected groups in reporting services

Question: I need to write a report that on startup shows specific groups expanded while other remains collapsed. I've been searching for a property like "collapsed" or "expanded" or similar at the group level, but I found none.
The only way I've found to do something similar is through the "hidden" properties of the detail. But this way the +/- mark to the side of the group works in the opposite way: it shows '-' when the group is collapsed and '+' when it is expanded.
Is there a better way to expand or collapse a group based on a programmed condition?
Answer: To solve the +/- mark problem, go to the Properties of the Element which contains the +/- symbol, and set the property "InitialToggleState" using an expression.
Comment: it works! I wrote a conditional expression for the hidden property of the detail and then I wrote the negated version of the same expression for the group.


Is it advisable to cover and uncover the clarinet mouthpiece to play each note?

Question: I took clarinet lessons only for 4 months and my teacher told me that I must cover and uncover the mouthpiece with the tongue between note and note. I find it difficult and I think I prefer to simply cut off the air flow and blow again, but I don't know if this is the right technique.
Comment: You must **absolutely** keep the air pressure up throughout the passage!
Answer: I am not really sure what you mean by cover and uncover. But as a clarinet player with nearly 30 years under my belt I would say there are three (four) ways of articulation.

Legato(Slur): You keep the air flow going, just change the fingering. This is shown by the arc over the notes.
Staccato: You stop the reed with your tongue and restart the tone by synchronized airflow and release of the reed by your tongue (the "Te-Te" tonguing). This is denoted as dots over or under the notes.
Portato/Tenuto: The more gentle stop, done with more a De-De tonguing. Shown by dots and arcs (Portato) or small bars (Tenuto).

The answer to "Should I always.." really depends on what's in the notes. I do not have my Baermann at hand, but I will check later and update. The clarinet school of Baermann is imho the Gold Standard for this questions.
Comment: @OldBrixtonian That's called double tonguing and is considered an advanced technique. But it does exist for clarinet and is used.
I am German and therefore I was taught, clarinet wise, in a strong tradition that is quite different from the rest of the world. We have a different mechanic, different cut for reeds and therefore mouthpieces, different bore, different tonal ideal. We also don't do vibrato and don't double tonguing, but that's us.
Comment: @OldBrixtonian Thank you for pointing out those sloppy mistakes. I am by no means a native english speaker or writer.
Comment: I'm sorry. I thought you *were* a native speaker. They were **tiny** mistakes. I've deleted that comment. Do delete yours if you'd like to.
Comment: Excellent answer! Do clarinettists also use Te-Ke and De-Ke in fast passages? I think flautists do.
Comment: @OldBrixtonian  Double-tonguing is possible but rarely sounds "clean."
Comment: @Oliver  clarinet vibrato is certainly acceptable in jazz/swing, of course!  It's slowly gaining acceptance for some 'classical' music.
Comment: @CarlWitthoft I totally agree. And I like to do it to give a sustaining note a bit more substance. But as I said, it is neither wanted, nor taught in the german, classical, tradition. And the whole system is not tailored to that sound, either. The first time, I played a Boehm mouthpiece with a french cut reed, I was shocked, how much pitchbending is possible with that setup. That's the reason, why you normally won't the a jazz clarinetist playing a german Oehler mechanic, and if so, I would bet, he uses a special mouthpiece with french cut reeds.
Comment: What's the "*(four)*" about?  Is that where you stop the airflow using the back of your throat?  (Possibly the "Ke" that @OldBrixtonian was referring to?)
Comment: Additional air control    4. Using one's throat to make a "glottal uh-uh"    to control the airstream before it hits the mouthpiece and reed.
Comment: @Oliver You don't use double tongueing? How do you tongue fast passages?
Comment: @OldBrixtonian We have fast tongues.. I could could same saying about woodwind players, but I might collide with etiquette.
To be honest, I guess most players will go for some kind of double tonguing, as they do for some kind of vibrato. I have a textbook teaching it. But that is university level stuff.
Comment: @Oliver Ha! Fast tongues would make you good salesmen! I didn't know about the Oehler system, but it explains the so-called 'veiled' tone of German woodwind sections. Weber certainly liked the sound, didn't he? Glancing at my score of the Oberon overture, I see that solo is a clarinet in A: *Maximum* veiling! Brightness is great, but I'm glad Bb trumpets have survived along with C ones. I've never heard a G trombone, though plenty of trombonists get misty-eyed when they remember the sound of them.
Comment: @OldBrixtonian The Oehler Mechanics is the "complete" german mechanic. It is easy recognizable by the one "closed" hole instead of a ring. You might call the german sound veiled. It would call it more centric, but it definitively has a more earthy, darker timbre. That is especially true for a clarinet in A. While a clarinet in C already sounds strange.. funny, how much different that is. How naive young me was, thinking, the different tuning is only for easy fingering.. I have to admit, It's fun talking to you. It's not often, you meet someone relishing such subtle differences.
Answer: I guess your teacher was trying to get you to tongue each and every note. It's a better way than merely blowing to start each note - the result is more uniform and clearer, with a controlled start to the note, and more even playing.
Once you get into producing notes more clearly - especially their attack, you'll find that you can slur one note into another by simply changing fingers, but carry on with the blow. This makes moving from one note to the next smoother - somewhat reflecting the way we put words together in phrases and sentences.
Obviously, placing the tongue back on the reed after playing a note will stop it sounding, so again, teacher gave you more control over the end of each note too, which for a beginner makes it sound tidier.
Answer: Yes, tonguing is a necessary technique.    There's hard tonguing, soft tonguing and many degrees in-between.  Starting a note with minimal or no tonguing is also a valid technique, but it would be a big mistake and very restrictive to try to make it the ONLY technique you use.
Try playing this without tonguing.   See what I mean?
(ENDING a note with the tongue is generally frowned upon. 'Taa...'  is a pleasing sound.  'Tu...t' isn't.)
Comment: Not always:  in any string of short or staccato notes, the tongue *should* be used to terminate each note.  For legato, the tongue simultaneously ends the old note and starts the new one.   The last note in a phrase, as you suggest, should not be cut off with the tongue
Answer: Maybe lost in translation, but you shouldn't be using your tongue to cover/uncover as if to block the air flow. It's just a light touch of the tongue against the reed to stop the reed vibration. Like when you ring a bell, then touch your finger against it to silence the ringing. It may feel unusual at first, but try lighter or stronger pressure against the reed until it feel right to you. Good luck with your music study!
Comment: This is incorrect.  Proper tonguing does in fact stop the airflow entirely


A woman has n keys

Question: A woman has n keys, of which one will open her door. After trying one she discards it and tries again if it does not work. What is the expected number of attempts needed?
Its straight forward to see that the probability of opening it on any go is $1/n$. Does this mean that, as $p$ is constant, the expected number is $\frac{1}{\frac{1}{n}}=n$.
This seems counter intuitive though as I would have expected it to be more like $n/2$
Answer: Probability that the woman opens the door on the $1^{st}$ attempt is $\dfrac1n$.
Probability that the woman opens the door on the $2^{nd}$ attempt is $\dfrac{n-1}n \cdot \dfrac1{n-1} = \dfrac1n$.
Probability that the woman opens the door on the $3^{rd}$ attempt is $\dfrac{n-1}n \cdot \dfrac{n-2}{n-1} \cdot \dfrac1{n-2} = \dfrac1n$.
Hence, in general the probability that she opens the door on the $k^{th}$ attempt is $\dfrac1n$.
Hence, the expected number of attempts is
$$\sum_{k=1}^n k \cdot \dfrac1n = \dfrac{n+1}2$$
Answer: Suppose she rather compulsively tries all the keys, even after finding the one that works.  On average, she will try as many keys before the right key as after the right key; since there are $n-1$ wrong keys, the average number for both is $(n-1)/2$.  That plus the correct key yields the average number of attempts as $(n-1)/2 + 1/2 = (n+1)/2$.

A woman has n keys


Border personalizado para determinadas colunas em table

Question: Então, eu tenho uma página com uma tabela que compara uma quantidade de itens previstos com uma quantidade de itens realizados mês a mês.
É desse jeito atualmente:

Me pediram pra colocar uma linha depois de cada coluna dessas de realizado pra ficar mais separadinho, mas eu não faço ideia se é possível e como fazer isso.
Ficaria assim:

E esse é o código que gera essa tabela:
<?php

                            require 'conn.php';

                            //Conexão e consulta ao Mysql
                            $qry = mysqli_query($lnk, "select * from qualite");

                            //Pegando os nomes dos campos
                            $num_fields = mysqli_num_fields($qry);//Obtém o número de campos do resultado

                            for($i = 0;$i<$num_fields; $i++){//Pega o nome dos campos
                                $fields[] = mysqli_fetch_field_direct($qry,$i)->name;
                            }

                            //Montando o cabeçalho da tabela
                            $table = '

';

                            for($i = 0;$i < $num_fields; $i++){
                                $table .= ''.$fields[$i].'	';
                            }

                            //Montando o corpo da tabela
                            $table .= '
';
                            while($r = mysqli_fetch_array($qry)){
                                $table .= '
';
                                for($i = 0;$i < $num_fields; $i++){
                                    $table .= ''.$r[$fields[$i]].'	';
                                }

                                // Adicionando botão de edição

                                $table .= '<form action="qualite-edicao.php" method="post">';
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="KPI" value="'.$r['KPI'].'">';
                                $table .= '<input type="hidden" name="PILOTE" value="'.$r['PILOTE'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN_PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN_REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV_PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV_REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR_PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR_REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR_PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR_REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI_PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI_REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN_PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN_REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL_PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL_REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO_PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO_REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET_PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET_REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT_PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT_REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV_PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV_REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ_PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ_REAL'].'">';
                                $table .= '<button class="btn btn-primary"> Editar </button>'; //
                                $table .= '</form>	';

                                //MODAL COM O GRÁFICO
                                $table .= '<form action="graf-qualite.php" method="post">';
                                $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
                                $table .= '<input type="hidden" name="KPI" value="'.$r['KPI'].'">';
                                $table .= '<input type="hidden" name="PILOTE" value="'.$r['PILOTE'].'">';
                                $table .= '<input type="hidden" name="JAN PREV" value="'.$r['JAN PREV'].'">';
                                $table .= '<input type="hidden" name="JAN REAL" value="'.$r['JAN REAL'].'">';
                                $table .= '<input type="hidden" name="FEV PREV" value="'.$r['FEV PREV'].'">';
                                $table .= '<input type="hidden" name="FEV REAL" value="'.$r['FEV REAL'].'">';
                                $table .= '<input type="hidden" name="MAR PREV" value="'.$r['MAR PREV'].'">';
                                $table .= '<input type="hidden" name="MAR REAL" value="'.$r['MAR REAL'].'">';
                                $table .= '<input type="hidden" name="ABR PREV" value="'.$r['ABR PREV'].'">';
                                $table .= '<input type="hidden" name="ABR REAL" value="'.$r['ABR REAL'].'">';
                                $table .= '<input type="hidden" name="MAI PREV" value="'.$r['MAI PREV'].'">';
                                $table .= '<input type="hidden" name="MAI REAL" value="'.$r['MAI REAL'].'">';
                                $table .= '<input type="hidden" name="JUN PREV" value="'.$r['JUN PREV'].'">';
                                $table .= '<input type="hidden" name="JUN REAL" value="'.$r['JUN REAL'].'">';
                                $table .= '<input type="hidden" name="JUL PREV" value="'.$r['JUL PREV'].'">';
                                $table .= '<input type="hidden" name="JUL REAL" value="'.$r['JUL REAL'].'">';
                                $table .= '<input type="hidden" name="AGO PREV" value="'.$r['AGO PREV'].'">';
                                $table .= '<input type="hidden" name="AGO REAL" value="'.$r['AGO REAL'].'">';
                                $table .= '<input type="hidden" name="SET PREV" value="'.$r['SET PREV'].'">';
                                $table .= '<input type="hidden" name="SET REAL" value="'.$r['SET REAL'].'">';
                                $table .= '<input type="hidden" name="OUT PREV" value="'.$r['OUT PREV'].'">';
                                $table .= '<input type="hidden" name="OUT REAL" value="'.$r['OUT REAL'].'">';
                                $table .= '<input type="hidden" name="NOV PREV" value="'.$r['NOV PREV'].'">';
                                $table .= '<input type="hidden" name="NOV REAL" value="'.$r['NOV REAL'].'">';
                                $table .= '<input type="hidden" name="DEZ PREV" value="'.$r['DEZ PREV'].'">';
                                $table .= '<input type="hidden" name="DEZ REAL" value="'.$r['DEZ REAL'].'">';
                                $table .= '
                                            <button type="button" class="btn btn-info button" data-toggle="modal" data-target="#exampleModal" name="button" onclick="abreModal(' . $r['ID'] .');">
                                              Gráfico
                                            </button>

Gráfico

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

                                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

'; //
                                $table .= '</form>	';

                            }

                            //Finalizando a tabela
                            $table .= '

';

                            //Imprimindo a tabela
                            echo '
';
                            echo $table;
                    ?>

Obrigada, pessoal.
Answer: Assim?

.table{
    border-collapse: collapse;
}

.table tr td{
  border-right: 5px solid lightblue;
}

.table tr td:last-of-type{
 border-right: none;
}

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

            1
            2
            3
            4
            5

Observação: Usei o last-of-type para remover a borda quando o elemento td for o último
Comment: Sua resposta foi bem útil, obrigada.
Comment: +1 um pelo capricho do  border-collapse :D
Comment: Considere clicar no botão abaixo do número de votação da resposta que você tiver gostado mais :p
Comment: kkkk, valeu @hugocsl
Answer: Com CSS3 você consegue fazer isso, usando o nth-child
Exemplo:

td {
  border-right: 2px solid red;
  padding: 20px;
}

td:nth-child(odd){
    border-right: 2px solid blue;
}

        Teste
        Teste
        Teste
        Teste

        Teste
        Teste
        Teste
        Teste

        Teste
        Teste
        Teste
        Teste

        Teste
        Teste
        Teste
        Teste

Comment: Então, na verdade é exatamente isso, eu só tirei a linha vermelha pra ficar uma linha azul a cada duas colunas. Resolveu. Obrigada.