Create a chain of transitions using jQuery

Question: I have created a little jQuery function with the help of transit.js that applies a transition to an element, and then to the next element after the transition is done.
The code applies the transition ony by one to whatever element is inside the .container div.
You can see the code in action here:

$(document).ready(function () {

    showDiv($('.container div:first'));

    function showDiv(tadaa) {
        tadaa.transition({
            opacity: 1
        }, 1000, function () {
            //call back
            showDiv(tadaa.next());
        });
    }
});
.container {
    border: 2px solid;
}

.container *{
    opacity: 0;
    display: inline-block;
    width: 50px;
    height: 100px;
    margin: 10px;
    vertical-align: top;
}

.container div {
    background-color: black;
}

.container p {
    background-color: red;
}

.container span {
    background-color: green;
}

.container input{
    background-color: blue;
    border: none;
    padding: 0;
}

  <input>

What would be the best way to accomplish this with jQuery but without using transit.js?
Answer: To do this with jQuery alone just change transition() to animate():

$(document).ready(function() {
  showDiv($('.container div:first'));

  function showDiv(tadaa) {
    tadaa.animate({
      opacity: 1
    }, 1000, function() {
      //call back
      showDiv(tadaa.next());
    });
  }
});
.container {
  border: 2px solid;
}

.container * {
  opacity: 0;
  display: inline-block;
  width: 50px;
  height: 100px;
  margin: 10px;
  vertical-align: top;
}

.container div {
  background-color: black;
}

.container p {
  background-color: red;
}

.container span {
  background-color: green;
}

.container input {
  background-color: blue;
  border: none;
  padding: 0;
}

  <input>


How can we change ownership of a Heroku add-on

Question: Is it possible to change ownership of a Heroku add-on? If so, how can we do that? In fact, I want to move an add-on from one Heroku account to another.
Let me elaborate my scenario a bit more to be clear.
I created an add-on with my test provider acount. Is there any way that I can delete the add-on from my test account and create the add-on with the same name with my official provider account? As a matter of fact, there is nothing about deleting the add-on or moving it under a different account in the Provider's documentation.
Comment: I would just email Heroku and ask them. They're very helpful.
Answer: A Google search lead me to this support page, which says

This currently depends on whether or not the app has any paid resources associated with it.
For an app with no paid resources, you can use "heroku sharing:transfer" from the command line to transfer the app to a new owner.
For an app with paid resources, you have two options.
1) Remove all paid resources, transfer the app like a free app, then have the new owner re-add the paid resources.
2) Both the old and new owners should file a support tickets at http://support.heroku.com authorizing the transfer and with the new owner accepting charges for the app.

Also check out the Transferring apps and Collaborating with Others articles on Heroku's Dev Centre.
Comment: It looks like you're referring to the client apps while my question was about add-on. Probably, I need to edit my question to be more clear. But thanks for your response on this.
Comment: @ShahzadLatif Ahh, good clarification! Thanks. Yes for ownership of add-ons rather than client apps I would probably contact Heroku support. Changing add-on ownership sounds like a much less frequent situation
Comment: I sent an email to Heroku add-ons team, but didn't get any reply from them! :(
Answer: Since you're talking about ownership of add-ons as an add-on provider and not just ownership of your heroku app, I would say you should probably contact the heroku add-on support team via email. See this page here for an email address. Hopefully as an add-on provider if you submit a help ticket they'll be able to help you as well.
Comment: thanks for pointing to the resources page. I'll try to contact the Heroku team directly and see if they might be of some help in this scenario.
Comment: @ShahzadLatif Excellent! Keep me posted, or feel free to accept this answer if it works :)


Fundamental group of a complex algebraic curve residually finite?

Question: Is the analytic fundamental group of a smooth complex algebraic curve (considered as a Riemann surface) residually finite?
Comment: Several of the answers to this MO question also answer this question: http://mathoverflow.net/questions/20471/why-are-free-groups-residually-finite.  (I do find Qiaochu's proof to be the most natural.  But it's nice that topologists can prove the result in moe topological ways.)
Comment: The proof I wrote down does rely on an annoyingly big hammer...
Answer: Yes. Recall that topologically such a surface is a $g$-holed torus minus $n$ points. Except in the cases $(g, n) = (1, 0), (0, 0), (0, 1), (0, 2)$ such a surface, call it $S$, has negative Euler characteristic, so by the uniformization theorem its universal cover is the upper half plane $\mathbb{H}$. Since the action of $\pi_1(S)$ on $\mathbb{H}$ by covering transformations is an action by biholomorphic maps, $\pi_1(S)$ embeds into $\text{PSL}_2(\mathbb{R})$. And any finitely generated subgroup of $\text{PSL}_2(\mathbb{R})$ is residually finite; the argument is nearly identical to the argument that any finitely generated linear group is residually finite.
The exceptional cases are straightforward to verify individually.


Get Entity from Path or Url Object Retrieved from Menu (Node or Page)

Question: Linking through menu link tree elements I'm getting a series of url objects and paths. What I'd like to do is turn those url objects or paths into entities. I want access to the actual entities that they refer to. Here's my code so far:
<code>$menu_tree = \Drupal::menuTree();
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_id);
$menu_tree_elements = $menu_tree->load($menu_id, $menu_parameters);
foreach ($menu_tree_elements as $menu_tree_element) {
  $menu_tree_link = $menu_tree_element->link;
  $url_object = $menu_tree_link->getUrlObject();
  $path = $url_object->toString();
  $url_params = \Drupal\Core\Url::fromUserInput($path)->
    getRouteParameters();
  var_dump($url_params);
}
</code>
I was thinking that I could possibly get the entity from the url parameters but I get the error

External URLs do not have internal route parameters.

Which makes sense to me because I have menu links that refer to just general Page entities not nodes. Like '/about'.
However I'm able to get to the paths just fine. Is there a way that I can load an entity since I have a url object that has a path directly leading to it?
UPDATE: I tried using
<code>$params = \Drupal\Core\Url::fromUserInput('/about')->
  getRouteParameters();
var_dump($params);
</code>
But all that did was return an empty array.
I received the same result when using
<code>$params = \Drupal\Core\Url::fromUri("internal:/about")->
  getRouteParameters();
</code>
Answer: I managed to come up with a solution by using the storage manager to load the entity using the path to load it.
<code>$page = \Drupal::entityTypeManager()
  ->getStorage('page')
  ->loadByProperties(array(
      'path' => $path
  ));
</code>
I'm assuming you can use the same method for nodes.
Comment: @Cyclonecode I'm reediting your edit to follow the conventions of the actual drupal core code. See the source code of the UserAuth class as an example https://api.drupal.org/api/drupal/core%21modules%21user%21src%21UserAuth.php/class/UserAuth/8.2.x
Comment: How should `$path` be formatted?
Comment: @Keven I believe something '/this-is-the-alias' works. Let me know if that doesn't.


Bass identification--No name anywhere

Question: Could someone help me figure out what kind of electric bass this is? I found it in my great-grandparent's attic. There is not a single word on this thing anywhere, and I can't find a similar model via photo.
On an additional note, a recommendation of strings I should use to replace the old ones?
I apologize in advance for poor photo quality:
Comment: btw, it would be nice if you could inline a selection of those photos here, to prevent bit rot - or, as it's difficult for new users, specify permission & someone with higher rep could do it for you. As you own the rights to the images, we can't do it without permission.
Comment: It looks like the kind of thing you could buy in Woolworths in the 60s & 70's, except Woolies eventually own-branded as "Audition". It's definitely that kind of age as the 'finger rest' is below the strings, so you were expected to play with your thumb. The 'extra' scratch plate above hints at Burns, but I doubt it's a Burns. It probably retailed at £20 or so back then & other than as a curio, probably isn't worth much more now, I'm afraid.... unless someone nails it as some kind of hidden gem... but don't hold your breath ;)
Comment: I apologize, I couldn't figure out how to put the photos on here directly. If you or someone else want to move them, I can try changing permissions
Comment: I found something very similar on eBay, not identical but all the hallmarks - https://www.ebay.com/itm/Vtg-Horugel-Burns-Japanese-Electric-Bass-Guitar-1960s-1970s-Weird-Retro-Project-/142679653275 but sincerely doubt they'll get the $225 they're asking for.
Comment: This is what I meant by the Burns-look, btw... they did the 'horn' [attached](http://www.thunderrow.com/attachment.php?attachmentid=2128&d=1340669946&stc=1) or [separated](https://www.vintageandrare.com/uploads/offers/475/286/burns-Bison-Legend-Bass-Limited-Edition-1994-original.jpg?1517893787). As soon as George Harrison played one, all the far eastern factories will have been attaching new bits to look like it ;)
Comment: What about the headstock? Any serial numbers on it?
Answer: Your instrument appears to be a 'Top Twenty' Bass that was made in Japan. It is possibly a 60/70's but can't be sure. The pick up on the bass is a Hofner staple pick-up so that would er towards 60's. I have a similar bass with the same pick-up.
Answer: This isn't a clear, complete answer to the question, but it is a partial answer with valuable information that could lead to a complete answer, so:
It's a 60/70's Japanese Fender knock-off of some sort. (That's back in the days when Japanese stuff was cheap and junky.) It's made of various cheap parts that don't really match each other.
There were many names stuck onto those products- often the same instrument with different names, or vice versa. Without a name on it, it may be impossible to accurately identify it. (Perhaps some mad collector or dealer or expert in old instruments could nail it for you, if you could find someone like that.) At that time, teenagers were becoming very interested in music, due to the Beatlemania, then Woodstock, etc, so the markets were flooded with such instruments - low priced knock-offs of expensive American instruments (in this case the Fender Jazz Bass) that targeted the young market with prices that were fraction of the cost of a "thoroughbred".
In the USA, such an instrument probably cost around $79.95 in Sears, in 1970. Now it might be worth 3x or 4x as much, assuming it's in good playing condition. (That's after taking inflation into account...) Judging from the pics, it doesn't look bad at all. Highly doubtful you've stumbled upon some buried treasure.
Take a look here - you might find something similar - I didn't right now but the list is always changing: Vintage basses under $1000 - note that the basses for sale there are mostly in excellent condition, with known names.
Among the listings there is this :Gallan Jb Circa 1969 3ts

You can see similarities to your bass, and also differences. So perhaps it's a "Gallan" of some sort. The seller (Japanese) describes it this way:

...This bass, although a kind of budget build back in the day,that
went for around 35000JPY, is a very decent Jazz bass. The neck is 3 pc
maple, rugged and reliable, and is still healthy with an operational
truss. The body is most likely plywood with maple laminate on top and
back,   the fretboard is rose with abalone inlays and white binding.
The scale is 34" and all the hardware, circuit, pots and pickups are
original!
It was made for Kyowa-shokai corporation by the Matsumoto
Musical Instrument group, meaning Matsumoku most likely made the neck
and the rest maybe was outsourced to other builders. This was one of
Kyowa's first brands and was later replaced by their slightly higher
grade Fresher brand in the mid seventies.

As you can see, that instrument is probably made from parts coming from different sources, and the name "Gallan" was subsequently replaced with "Fresher". So maybe yours is "Gallan" or a "Fresher" or maybe some other name entirely, built by someone else, using some parts from the same source used to build the Gallan.
Note that your bass has a few interesting features that could make exact identification easier:

The truss rod adjustment - that little rod sticking out of the bottom
of the neck, under where it meets the body: It is exposed and can be
adjusted easily without an allen wrench or special tools. Many
basses, even today, don't feature that - it is a plus.
The tortoise shell pickguard covering the front is split into two
parts, with a separate, small panel on the upper right hand side.
That is unusual.
The "witch's hat" style knobs for the volume and tone controls. Note
the difference between those and the ones on the Gallan pictured her.
Those are often found on older instruments - you'll be hard pressed to find them on a modern design. It could be random entirely - they just happened to have some knobs
like those around and used them. Or, it could be part of some sort of
"signature" look or style they were trying to achieve to make their
instrument stand out.

Your best shot at getting a good ID for it online will be here:
TalkBass.com - Bass Guitar Instrument Discussion - if there's anybody around who might be able to ID it, they will probably be found on that site. You'd have to become a member of the site to post the question - it's free.

On an additional note, a recommendation of strings I should use to
replace the old ones?

Hard to recommend strings without knowing what style of music you intend to play, and what the length of scale is. (It's probably 34 inches). We also don't recommend specific products here on this site.
So I'll just say that a good quality medium gauge, long scale (34 inches), nickel, round wound string for 4 string electric bass from D'Addario or GHS are good for general use. There are many brands, but those two are very popular with a great number of players. DR, LaBella and Ernie Ball are other names name you'll often see. Personally I have used only D'Addario or GHS string for many years.
Important A word of advice: If you intend to try and sell and make a few bucks (It's possible if you put in some effort, although as mentioned, not a great fortune), do not modify or fix it up in any way. (You also put in a picture of the cord, but that's separate from the bass and is worthless - likely it's flaky too.) Whatever value it might have is because of its original "vintage" condition. If you change it somehow, you will immediately diminish greatly whatever value it has. You can clean it up and polish it (be careful you don't rub off the finish), but don't change anything on it - no new strings, new tuning pegs, new pickup, new finish, new knobs, etc. Handle it with care and put it back together carefully, since you've now taken some of it apart.
Comment: If you'd like to link this post elsewhere, go for it. As for changing any parts, I don't intend to sell it, however I also would like to keep it as close to its current state as possible. I believe I tried playing it a couple years ago and it not functioning as it should, but I don't remember the specific issue, nor do I have an amp as of now to test it. Hell, it could have been the cord that went with it. Thanks for the history in coordination with the different parts of the bass. I don't really know much about basses to begin with, I just enjoy trying new instruments when I get the chance.
Comment: Body contour, pick guards, neck inlays, and pickups all don't match.

Bass identification--No name anywhere


Find the maximum value for $x+y+z-xy-yz-zx$

Question: If $x,y,z$ are real numbers for which holds $0\le x,y,z \le 1$, then find the maximum value of $x+y+z-xy-yz-zx$ and find $(x,y,z)$ for which you get the maximum value.
This is how did it and I would like to know if I made a mistake or someone has another solution for it.
Let $S=x+y+z-xy-yz-zx$
We have that
$$
0 \ge (x-1)(y-1)(z-1)=xyz-xy-yz-zx+x+y+z-1=xyz-1+S \\
\Rightarrow S \le 1-xyz \le 1.
$$
It holds for $(1,0,k)$ and all permutations, whete k is a real number so that $0 \le k \le 1$.
Comment: You get $-1\le xyz-1+S$ if you double check your work, which unfortunately doesn't help.
Answer: Here is another way/ hint:  the function is linear in each variable, so extrema will occur only when variables take values at the end points of their intervals.
Answer: $% Predefined Typography
 \newcommand{\paren} [1]{\left({#1}\right)}
 \newcommand{\bparen}[1]{\bigg({#1}\bigg)}
 \newcommand{\brace} [1]{\left\{{#1}\right\}}
 \newcommand{\bbrace}[1]{\bigg\{{#1}\bigg\}}
 \newcommand{\floor} [1]{\left\lfloor{#1}\right\rfloor}
 \newcommand{\bfloor}[1]{\bigg\lfloor{#1}\bigg\rfloor}
 \newcommand{\mag}  [1]{\left\lVert{#1}\right\rVert}
 \newcommand{\bmag} [1]{\bigg\Vert{#1}\bigg\Vert}
 \newcommand{\abs}  [1]{\left\vert{#1}\right\vert}
 \newcommand{\babs} [1]{\bigg\vert{#1}\bigg\vert}
 %
 \newcommand{\labelt}[2]{\underbrace{#1}_{\text{#2}}}
 \newcommand{\label} [2]{\underbrace{#1}_{#2}}
 %
 \newcommand{\setcomp}[2]{\left\{{#1}~~\middle \vert~~ {#2}\right\}}
 \newcommand{\bsetcomp}[2]{\bigg\{{#1}~~\bigg \vert~~ {#2}\bigg\}}
 %
 \newcommand{\iint}[2]{\int {#1}~{\rm d}{#2}}
 \newcommand{\dint}[4]{\int_{#3}^{#4}{#1}~{\rm d}{#2}}
 \newcommand{\pred}[2]{\frac{\rm d}{{\rm d}{#2}}#1}
 \newcommand{\ind} [2]{\frac{{\rm d} {#1}}{{\rm d}{#2}}}
 \newcommand{\predp}[2]{\frac{\partial}{\partial {#2}}#1}
 \newcommand{\indp} [2]{\frac{{\partial} {#1}}{\partial {#2}}}
 \newcommand{\predp}[2]{\frac{\partial}{\partial {#2}}#1}
 \newcommand{\ind} [2]{\frac{{\rm d} {#1}}{{\rm d}{#2}}}
 \newcommand{\predn}[3]{\frac{\rm d}^{#3}{{\rm d}{#2}^{#3}}#1}
 \newcommand{\indn} [3]{\frac{{\rm d}^{#3} {#1}}{{\rm d}{#2}^{#3}}}
 %
 \newcommand{\ii}{{\rm i}}
 \newcommand{\ee}{{\rm e}}
 \newcommand{\exp}[1] { {\rm e}^{\large{#1}} }
 %
 \newcommand{\red}  [1]{\color{red}{#1}}
 \newcommand{\blue} [1]{\color{blue}{#1}}
 \newcommand{\green}[1]{\color{green}{#1}}
$
$$f(x, y, z)= x + y + z - xy - yz - zx$$
Crit point:
$$\begin{cases}
\indp{f}{x} = 1 - y - z = 0 \\
\indp{f}{y} = 1 - z - x = 0 \\
\indp{f}{z} = 1 - x - y = 0 \\
\end{cases}$$
$$\downarrow$$
$$[x, y, z] = [1/2,~1/2,~1/2]$$
So the candidates for min-max are allow the 10 cases (due to symmetry) of crit points and end points:
$$\begin{cases}
x \in \{0,~ 1/2,~ 1\} \\
y \in \{0,~ 1/2,~ 1\} \\
z \in \{0,~ 1/2,~ 1\} \\
\end{cases}$$
The min cases ends up being $[1,~ 1,~ 1]$ and $[0,~ 0,~ 0]$, and the max case ends up being $[1,~ \text{anything},~ 0]$.
Answer: $$f(x,y,z)=x+y+z-xy-yz-zx$$
Note that $\frac{\partial f}{\partial x}=1-(y+z)$
So, 3 possibilities :

$y+z>1$ : $x=0$ will maximize f, so $f(0,y,z)=y+z-yz=1-(1-y)(1-z)$ that is maximum for $y=1$ or $z=1$, and $f=1$
$y+z<1$ : x=1 will maximize f, so $f(1,y,z)=1-yz$, that is maximum for $yz=0$, so either $y$ or $z$ equal $0$ and once again $f=1$
$y+z=1$ : $x$ can be anything because $f=1-yz$, same case than before with $y,z$ equals to $1,0$ or $0,1$

So to conclude, $f$ is maximum for any triplet $(x,y,z)$ such that one is $0$ and another one is $1$.


Leetcode ones and zeros with 3D array, fail pass sample test cases

Question:
I am working on leetcode ones and zeros.
I tried to use a 3D array by following this guide

Here is my code
/**
 * @param {string[]} strs
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var findMaxForm = function(strs, m, n) {
    const len = strs.length;
    const dp = new Array(len+1).fill(0).map((_, i) => {
        return new Array(m+1).fill(0).map((_, j) => {
            return new Array(n+1).fill(0);
        });
    });

    const get1s = (ele) => {
        const arr = ele.split('');
        const ones = arr.reduce((acc, a) => acc + parseInt(a));
        return ones;
    }

    const get0s = (ele) => {
        const ones = get1s(ele);
        const zeros = ele.length - ones;
        return zeros;
    }

    for(let i=1; i<=len; ++i) {
        const ele = strs[i-1];
        const zeros = get0s(ele);
        const ones = get1s(ele);

        for(let j=0; j<=m; ++j) {
            for(let k=0; k<=n; ++k) {
                if(j-zeros >=0 && k-ones >= 0) {
                    dp[i][j][k] = 1 + dp[i-1][j-zeros][k-ones];
                } else {
                    dp[i][j][k] = dp[i-1][j][k];
                }
            }
        }
    }

    return dp[len][m][n];
};

sample input / output
["10","0001","111001","1","0"]

m = 5

n = 3

expect = 4

Not able to pass sample test cases. Could someone have a look?
Comment: I don't get case 2. Why is '10' filtered out?
Answer: There are two issues in your code:

In get1s, the reduce method is called without initial value. This is a problem, because the array being iterated has strings, and so the default initial value for acc will be a string. This means the + operator will execute as a string concatenation, and not as an arithmetic operator. The fix is to provide the second argument to reduce (0).

You need to make sure you only improve the values in dp, and not "worsen" them. The blog post you referred to did this correctly with this Python code:
dp[i][j][k] = max(dp[i-1][j][k], 1+dp[i-1][j-cz[i]][k-co[i]]);

In the your JavaScript version, this max call is not present.

Here is your code with those two corrections:
var findMaxForm = function(strs, m, n) {
    const len = strs.length;
    const dp = new Array(len+1).fill(0).map((_, i) => {
        return new Array(m+1).fill(0).map((_, j) => {
            return new Array(n+1).fill(0);
        });
    });

    const get1s = (ele) => {
        const arr = ele.split('');
        // Fix: reduce must start with initial value 0:
        const ones = arr.reduce((acc, a) => acc + parseInt(a), 0);
        return ones;
    }

    const get0s = (ele) => {
        const ones = get1s(ele);
        const zeros = ele.length - ones;
        return zeros;
    }

    for(let i=1; i<=len; ++i) {
        const ele = strs[i-1];
        const zeros = get0s(ele);
        const ones = get1s(ele);

        for(let j=0; j<=m; ++j) {
            for(let k=0; k<=n; ++k) {
                if(j-zeros >=0 && k-ones >= 0) {
                    // Make sure to carry forward a DP value when
                    //    selecting the current string brings no improvement.
                    dp[i][j][k] = Math.max(dp[i-1][j][k], 1 + dp[i-1][j-zeros][k-ones]);
                } else {
                    dp[i][j][k] = dp[i-1][j][k];
                }
            }
        }
    }

    return dp[len][m][n];
};

Further improvements
There are some things that can be improved:

The blog article you referred explained that you can reduce the 3D table for dynamic programming to a 2D array. The outer dimension can be omitted. You just have to ensure in the main logic, that the values are read before being overwritten: for that purpose the loops with j and k should iterate backwards.
Once the first point is implemented, you don't need the else case anymore, as it will be a non-operation
One the first point is implemented, you can remove the if condition and turn it into a loop condition for both loops.
There is hardly ever a good reason to write new Array in JavaScript. In this case you could benefit from Array.from in combination with its second mapper argument.
The function get1s should not need to convert a string to an array. You can benefit from replaceAll to get the required result; and then maybe it is overkill to have it as a function (debatable).

Here is the updated code:
var findMaxForm = function(strs, m, n) {
    // We can re-use DP rows, so we can skip the outer dimension.
    //    Use Array.from avoiding an intermediate array
    const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));

    for (const ele of strs) { // We don't need variable i anymore
        // No need to convert the string to array in order to count zeros or ones:
        const ones = ele.replaceAll("0", "").length;
        const zeros = ele.length - ones;
        // Reversed iterations to make sure we read the data
        //     from the previous outer iteration
        for (let j = m; j >= zeros; --j) {
            for (let k = n; k >= ones; --k) {
                dp[j][k] = Math.max(dp[j][k], 1 + dp[j - zeros][k - ones]);
            }
        }
    }

    return dp[m][n];
};


Can I use MS SQL?

Question: I don't want the whole of Drupal (Drupal itself plus SQL) on the same server. I need Drupal on a normal LAMP setup connecting to a db hosted on a separate server using MS SQL. Is it possible?
I've seen there's a MS PHP drive for Drupal to work, but the drive is a Windows executable file, so I guess it won't work on a Linux box.
Alternatively, is there any difference in Drupal itself for it to be able to connect to MS SQL?
Answer: Out of the box there is practically no support for MSSQL. Drupal 7 there was an attempt to support it driven by the Commerce Guys, but that work migrated to a contrib module and is not in core. Here is a quick rundown of compatibility.
Drupal 6: Not possible
Drupal 7: Possibly with the MSSQL Layer module called SQLsrv. But be prepared for issues when using contrib modules, some will not work because many modules write out SQL commands and run them with db_query instead of the abstraction layer for performance reasons - especially complex queries.
Drupal 8: Not possible out of the box. There is a third party module that provides a driver for MSSQL.
If you really want to get the most out of Drupal with as little headache as possible, run MySQL or even MarianDB on Windows.
Answer: Drupal 7 and 8 have full MSSQL Support.
Currently, PHP7 is also supported and Linux Support for PHP7 is comming soon.
My recommendation is that - if you are using MSSQL - go for a full MS software stack.
To install Drupal on SQL Server see this tutorial:
http://www.drupalonwindows.com/en/blog/installing-drupal-windows-and-sql-server
http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows
Comment: I have given up. At the time I was trying to run Drupal on Azure, which I did with some success but the problems it generated was not worth the trouble, at the end I migrated to Acquia, which is where I'm at the moment.
Comment: Sorry to hear that. Unfortunately you are comparing apples to oranges. Acquia is designed to do the hosting/infrastructure work for you (and that comes at a price) and is Drupal specialized. I know projects that saved a 5 figure number per month by moving away from Acquia.
Comment: I have been running Drupal 8.4 with sqlsrv 8.x-1.0-rc4 successfully for a few months. I have had to patch core and the sqlsrv module. Core needs to be patched to allow entities to be edited, while the sqlsrv patch fixes a paging when viewing lists of entities. (https://www.drupal.org/project/sqlsrv/issues/2931061) (https://www.drupal.org/project/drupal/issues/2342699)
Answer: By default Drupal supports MySQL, PostgreSQL and SQLite. But you can try to extend existing classes and write your own for MsSQL (or find some existing). I don't think that MsSQL can work on Linux, but maybe via emulator.

Can I use MS SQL?


Frog jumping between states, expected time

Question:
There is a frog which, when standing on the number $n$, will jump to
  $n-1$ with probability $0.6$ or to $n+1$ with probability $0.4$. The
  frog starts on number $2$, what is the expected value for the number
  of jumps the frog will take before reaching the number $1$ (for the
  first time)?

What I thought was: Let $T_{i,j}=\text{inf}\{n\in\mathbb{N}^{\star}:X_n=j\}|X_0=i$, where $X_n$ is the state of the frog after the jump number $n$. So we must find $\mathbb{E}[T_{2,1}]$. We have
$$\mathbb{E}[T_{2,1}]=1+0.4 \mathbb{E}[T_{3,1}] \quad
\text{and} \quad
\mathbb{E}[T_{3,1}]=1+0.6 \mathbb{E}[T_{2,1}]+0.4 \mathbb{E}[T_{4,1}]$$
but then I couldn't figure out what to do next. The solution I found states that \begin{equation}\mathbb{E}[T_{3,1}]=2\mathbb{E}[T_{2,1}] \quad \quad \quad (\star)\end{equation} but I can't see why this is true. It says that the equality holds because of symmetry: "since the expected number of jumps to go from 3 to 2 is the same as the expected number of jumps to go from 2 to 1", but I think this means $\mathbb{E}[T_{3,2}]=\mathbb{E}[T_{2,1}]$ (I understand why this last equality is true) which I can't connect to $(\star)$. Could someone please explain why $(\star)$ is true?
Comment: What is your source for this quote? A math.se page?
Comment: I found it on a website that has many exercises of different topics, what do you mean with a math.se page?
Comment: What is this site?
Comment: brilliant.org in the probability section
Answer: Symmetry tells us that $\mathbb E[T_{3,2}] = \mathbb E[T_{2,1}]$, and we also have $\mathbb E[T_{3,1}] = \mathbb E[T_{3,2}] + \mathbb E[T_{2,1}]$ because

In order to get from $3$ to $1$, you need to get to $2$ at some point, which takes $T_{3,2}$ steps.
At that point, you're at $2$ and need to get to $1$, which takes $T_{2,1}$ steps.

So then you solve for $\mathbb E[T_{2,1}]$, with one catch: you should prove that these expectations are finite somehow.
For example, you could use the fact that $\mathbb E[T_{2,1}] = \sum_{k \ge 1} \Pr[T_{2,1} \ge k]$, and then put upper bounds on $\Pr[T_{2,1} \ge k]$. This is not hard, since $T_{2,1} \ge k$ requires at the very least that there are more $n+1$ steps than $n-1$ steps over an interval of length $k$, and the probability of this decays geometrically.
Answer: Let $e(k)$ be the expected number of jumps to reach the target if the frog is $k$ units to the right of the target.

We want to find $e(1)$.

Assuming $e(1)$ is finite, we get
\begin{align}
e(1) &= {\small\frac{3}{5}}(1) + {\small\frac{2}{5}}(1 + e(2))\\[4pt]
e(2) &= 2e(1)\quad\text{[i.e., e(1) + e(1)]}\\[4pt]
\end{align}
Solving the above system of equations, we get $e(1) = 5.$

Explanation of why we have $e(2) = e(1) + e(1)\,$:

When the frog is $2$ units to the right of the target, it can set a new subgoal of reaching $1$ unit to the right of target. The expected number of jumps to achieve the subgoal is just $e(1).$ After achieving the subgoal, the frog is now $1$ unit to the right of the target, hence the expected number of jumps from that point is just another $e(1)$. Since the expected values add, we get $e(2) = e(1) + e(1).$


Geometric intuition for Properties of the Orthogonal Projection

Question:
Properties of the Orthogonal Projection: (Firm) Nonexpansivness
Let $C$ be a nonempty closed convex set Then:
1. For any $v,w\in\mathbb{R}^n$:
$\begin{aligned}
  (P_C(v)-P_C(w))^T(v-w)\geq||P_C(v)-P_C(w)||^2
 \end{aligned}$
2.(Non-expansiveness) for any $v,w\in\mathbb{R}^n$:
$\begin{aligned}
  ||P_C(v)-P_C(w)||\leq||v-w||
 \end{aligned}$

I've learnt this theorem in convex analysis course and I would like to get some geometric intuition for both of them
Answer: Orthogonal projection in ${\mathbb R}^n$ can be thought of as shining a light onto an object and looking at the shadow it casts on the far wall.  That oversimplifies a little too much, because the "far wall" is a plane so we're projecting down into at most two dimensions, but it's not a bad image to start with.
When we project we are reducing the number of dimensions we are considering (this is sometimes referred to as 'setting co-ordinates to zero') in order to get a feel for the macroscopic properties of the object.  Your second point expresses this: when we reduce the number of dimensions that we consider an object in, we are losing part of the object and so the end-result cannot grow, it can stay the same or shrink.  (Mathematically: if $v = (v_1, v_2, \ldots ,v_n)\in {\mathbb R}^n$ is our vector and $Pv = (w_1, w_2, \ldots ,w_n)$ is an orthogonal projection then we have $|w_n| \leq |v_n|$ for each $n \in {\mathbb N}$ so $v$ is "smaller" in some sense than $Pv$).
Your first point expresses the concept that the orthogonal projection preserves orientation: whatever direction the vector $v-w$ points (i.e. what sign it has), the projection $Pv-Pw$ points in the same direction (has the same sign).


Using Perl Ansi color to color entire screen

Question: I'm using Term::ANSIColor along with Win32::Console::ANSI in Windows.
I often use colored printing in my scripts to highlight some key info or whatever.
For the first time though, I'v tried something that works, but not quite how I would want it to.
What it looks like when I print on grey/white background:

And what I want is (edited to look the way I want it to print):

Thus I'm wondering if anyone knows how to go about ANSI escape sequences. Ho do I fill the entire piece that I'm printing on with a color and not just to the newline.
Also, here is my script (two ways I tried):
print color('bold blue on_white'), "\tnr\tisiNdebele\n";
print colored ['bold blue on_white'], "\tnso\tSepedi\n";

This isn't a major issue. I'm just wondering if someone knows how I can achieve this.
Comment: Fill the lines with spaces? :D
Answer: My solution uses Term::Size::Any to figure out how big the terminal is, and Text::Tabs to convert the \ts into spaces. We need to do that because a tabulator is only one character wide, but gets converted to 4, or 8 or whatever number of spaces when printed out.
use strict;
use warnings;
use Term::Size::Any 'chars';
use Term::ANSIColor;
use Text::Tabs 'expand';

my ($columns, $rows) = chars;

sub full_background {
    my ($text) = @_;

    chomp $text;
    return sprintf(qq{%-${columns}s}, expand($text)) . "\n";
}

print color('bold blue on_white'), full_background( "\tnr\tisiNdebele\n" );
print colored ['bold blue on_red'], full_background( "\tnso\tSepedi\n" );

Here's what it looks like.


Proteção de código .NET

Question: Tenho uma aplicação em C# que desenvolvi, ela será instalada em vários clientes. O problema é que tenho que proteger o código da aplicação, pois efetuei alguns testes com o aplicativo ILspy e todo o código fonte fica exposto. Qualquer um pode pegar uma DLL que você criou e copiar o código fonte. O Visual Studio 2015 já possui uma ferramenta para "ofuscar" o código, porém ela só altera o nome de algumas variáveis e métodos, uma pessoa com experiência em C# pode facilmente driblar isto.
Qual a solução mais viável para proteger o código fonte .NET?
Comment: Da uma olhada, tem uma lista aqui. http://stackoverflow.com/questions/2646707/something-better-than-net-reflector
Comment: @PauloHDSousa, essa lista é justamente o meu problema. Quero evitar que o código seja visto.
Comment: Da uma olhada na lista.
Comment: Ok, vou olhar sim.
Answer: Em uma resposta clara e sucinta, NÃO TEM COMO!
Digo que isso não é possível de fazer pelo fato de que por mais habilidoso que você seja, sempre terá alguém habilidoso o suficiente em engenharia reversa  (ou outros tipos, incluindo engenharia social) para conseguir quebrar a sua proteção. Os crack's são a prova mais real sobre isso.
O que é possível fazer é dificultar o acesso, mas não existe uma forma que garanta 100% de proteção.
Mas então quer dizer que devo deixar da forma que está?
Isso depende muito. As vezes o trabalho que você terá para dificultar o acesso pode não ser viável por diversos fatores, por exemplo o tempo e custos para realizar essa tarefa.
Mas então não existe nada?
Bom, existem algumas ferramentas, para .net em específico, que ajuda a realizar esse processo, que são:

DotOfuscador.
Themida

Qual sua recomendação?
Não se preocupe muito com isso, pois se a pessoa tem capacidade para entender e usar um sistema de engenharia reversa e deixar o código funcionando, muitas vezes ela tem capacidade para fazer um igual, e as vezes o processo pode ser até mais rápido.
Agora, se seu problema seria com o uso indevido do sistema, você pode utilizar uma forma de licenças para assegurar a utilização do sistema.
Complementos:
Como complemento, deixo algumas perguntas aqui sobre o assunto, duas delas muito parecido com a sua.

Como proteger o código fonte?
Protect .NET code from reverse engineering?
O que é Engenharia Reversa?
Comment: @Robss70 Dê uma olhada [aqui](https://eren.ws/2014/02/04/encrypting-the-web-config-file-of-an-azure-cloud-service/) e [aqui](https://azure.microsoft.com/en-us/blog/securing-your-connection-string-in-windows-azure-part-1/). É uma forma, mas eu não conheço seu ambiente, então não tem como saber qual a melhor. Todavia, isso foge da pergunta original. Caso tenha mais dúvidas, o site já possui muito material sobre o assunto. Caso não ache nada, pode abrir outra pergunta sobre isso, especificamente.
Comment: +1 pela resposta clara e sucinta.
Comment: Entendi, já havia pensado na questão da pessoa que tem capacidade para entender e usar um sistema de engenharia reversa. No caso de você desenvolver algo novo ou uma solução muito boa para algum problema e que queira proteger sua ideia, neste caso seria mais "fácil" desenvolver em c++ ou c ?
Comment: @Robss70 Entra no mesmo problema. Você pode dificultar, agora impedir não dá. [Esta resposta](http://stackoverflow.com/a/6481695/4843158) fala sobre essa questão em `C++`
Comment: @Randrade, realmente esse assunto engenharia reversa e propriedade intelectual é extremamente complexo. Muito obrigado pela ajuda.
Comment: @Robss70 Propriedade intelectual é mais complexo ainda. Porém, se fizer tudo certo, estará amparado pela lei, mesmo que não consiga proteger o fonte terá a garantia que é seu. Com isso, poderá fazer algo judicialmente, se possível.
Comment: @Randrade, já abusando da sua boa vontade, no caso de string de conexão, como você protegeria esta informação no código fonte?
Comment: @Robss70 Isso irá depender do seu contexto. Depende do que está utilizando, com o que está trabalhando, como será essa conexão, etc. Eu geralmente não me preocupo muito com isso, pois meus sistemas ficam em um ambiente controlado e uso a autenticação do Windows.
Comment: É uma string de conexão Sql Server para uma banco de dados no Microsoft Azure, e o ambiente dos clientes são iguais ao velho oeste.
Comment: @Randrade, mais uma vez muito obrigado pela sua atenção.
Answer: Nenhuma técnica protegerá de fato, pode dificultar. Se está escondendo um segredo, está fazendo algo errado no código. Se não tem segredo, em geral os malefícios de fazer isso superam os benefícios. Leia isso, é importante.
Tem uma lista na Wikipedia com ofuscadores. Obviamente a qualidade de cada fará um trabalho melhor. Algumas técnicas criam problemas para execução. É comum o desenvolvedor nem se dar conta que é o ofuscador o causador e sofrer sem necessidade. Há casos da pessoas que sempre acha que os problemas do seu código é o ofuscador.
Não sei qual é o melhor, principalmente para sua necessidade.
Mas começando principalmente em .NET 7 (antes era possível com alternativas mais complicadas de se adotar) é possível gerar código nativo, ou seja, o código de máquina o processador. Isso torna muito mais complicado obter o código original de volta, e não sei se tem alguma ferramenta pronta para uso que gere o C#, então é impossível para a maioria das pessoas. Não protege segredos, mas o trabalho de retomar o código original é tão grande quanto fazer do zero. Se isso bastar então CONSEGUE TER A PROTEÇÃO QUE DESEJA.
Coloquei no GitHub para referência futura.
Comment: Já li a respeito destes problemas de execução, principalmente em reflection. Muito obrigado pela sua ajuda.

Proteção de código .NET


Gestures not getting detected in accessibility mode

Question: I am programming an app where I need to put a label onto top of the screen and whenever user touches it (or swipes finger above it), I need the label text to be read out loud. I tried the following ways:
First make the accessibility element of the label = YES.
[labelInfo setIsAccessibilityElement:YES];

But this doesn't work.
Then I tried defining many gestures like two touches, single tap; long tap using one and two fingers etc., and in that gesture class I write UIAccessibilityPostNotification, so that the text can be read out loud. But it doesn't seem to work at all. This is how I did it:
UITapGestureRecognizer *TapOnLabel = [[UITapGestureRecognizer alloc] initWithTarget:labelInfo action:@selector(TapOnLabel:)];
[TapOnLabel setIsAccessibilityElement:YES];
[TapOnLabel setNumberOfTapsRequired:2];
[TapOnLabel setNumberOfTouchesRequired:1];
[labelInfo addGestureRecognizer:TapOnLabel];
[TapOnLabel release];

-(void) TapOnLabel:(UITapGestureRecognizer *)gestureRecognizer
{
  UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, @"Where am    I?");
  NSLog(@"%@",labelInfo.text);
}

Is there something I am missing or no gestures work in accessibility mode, because many are predefined. For ex. two finger two tap is music on/off etc.
If this is the case, I need atleast swipe to work. Any thoughts on this?
P.S. I have seen the solution of a similar question here. But it is particular to zoom gestures and not helpful to me. Also, all the gesture classes work perfectly without accessibility mode, so they have been written correctly.
Comment: You shouldn't need to implement any gestures yourself for this. Is the label a normal UILabel? If not, what is its `accessibilityLabel`? In the simulator with accessibility inspector on (can be found in the settings), what label, hint, trains does the inspector give you for that label?
Comment: Just for giggles....   how would your question actually be used?   if the user cannot read the screen (various reasons), then how would they know what area to swipe (partial words, different languages perhaps)??   what is the use case for this question?
Comment: @pithhelmet I guess you haven't considered visually-impaired people? They will here the labels being spoken aloud so that they know they are touching the correct app.
Answer: The gestures are all intercepted by VoiceOver. There is a gesture passthrough mode where you double-tap and hold your finger on the screen for 1s. You will then hear a tone and the intercept will be disabled until you lift your finger or complete a gesture. This gives you essentially 8 gestures you can then complete - the four swipes and the four drags.
But having said that, why does your application need to behave in this way? Why can you simply not add the accessibility label and/or hint and allow the VoiceOver focus and touch-to-explore work as they are designed?


What's the measure of the segment $MD$ in the triangle below?

Question: For reference:

In the figure, calculate $MD$, if $BM = 6\ \mathrm m$, $DE= 1\ \mathrm m$ and $M$ is incenter *. (Answer:$2\ \mathrm m$)

*(Added later)

My progress: I found a solution on the net but the consideration of point $M$ being the incentre (not mentioned) was made in the statement besides using more advanced trigonometry. Would it be possible to solve it by geometry and without considering M as incenter?
Let $M$ = incenter triangle $ABC$
By Incenter Theorems:
$\displaystyle \frac{MB}{MD} = \frac{a+c}{b} \iff \frac{BD}{MD} = \frac{a+b+c}b \iff MD = \frac{b}{2p} \cdot BD = \frac b{2p} \cdot \frac{2ac \cdot \cos \frac{B}2}{a+c} \implies \\\displaystyle
MB = \frac{ac \cos \frac{B}2}{p}\\ \displaystyle
EM = EA = EC = \frac{\frac b2}{\cos \frac B2} = \frac b{2\cos \frac B2}$
Using a non-trivial relationship
$\displaystyle ac \cos^2 \frac B2 = p(p-b) \implies \\\displaystyle
\frac{MB}{ME} = \frac{2(p-b)}b \iff \frac{6}{1 + MD} = \frac{a+c - b}{b} = \frac{MB}{MD} -1\\\displaystyle
\implies \frac6{1+x} = \frac6x -1 \iff x=2$
Original Problem:
Comment: No if $M$ is not fixed or there is no more info, there is no unique solution.
Comment: is BP and BQ are tangent to the smaller circle
Comment: @MathLover Is there a solution by geometry considering M incenter?
Comment: @Bometh  yes, it is.
Comment: @petaarantes not sure, the question itself isn't very clear to me.
Comment: @MathLover  Is triangle $BPQ$ is isosceles since $BP$ and $BQ$ are tangent to the same point and since $PM$ = $MQ$, $BM$ would be perpendicular to $PQ$?
Comment: Yes that is correct
Comment: Can you link the source?
Comment: @ACB   I have posted above the original problem
Comment: I now see your edit to the question that $M$ is incenter. That makes a geometric solution possible. See my answer.
Comment: *"I found a solution on the net.."* is it possible to share that also :) ?
Comment: @ACB  When I said "on the net" the truth is this solution was taken from another forum in my country...it is not from a specific site..
Comment: @petaarantes ... if you are still interested in this question and if I can address the original version of this question, please see [this one](https://math.stackexchange.com/q/4322021/997661).
Comment: @A-B-C gratidude...very good.
Answer: Say, $MD = x$. As $M$ is the incenter of $\triangle ABC$,
$ \displaystyle \frac{BM}{MD} = \frac{a+c}b$
$ \displaystyle  \implies \frac 6x = \frac{a+c}b\tag1$
$ \displaystyle CD = \frac{ab}{a+c}\tag2$
As $\triangle ADE \sim \triangle BDC$ and $AE = ME$,
$ \displaystyle \frac{AE}{DE} = \frac{BC}{CD}$
$ \displaystyle \implies ME = MD + DE = x + 1 = \frac{a+c}b ~  \left[\text {using } (2)\right]$
Plugging into $(1)$,
$ \displaystyle \frac 6 x = x + 1 \implies (x-2)(x+3) = 0$
That leads to $x = 2$.

$AE = CE = ME$ is always true if $M$ is the incenter of $\triangle ABC$ and $E$ is the point where the angle bisector of $\angle B$ intersects the circumcircle of $\triangle ABC$. See below -
$ \displaystyle \angle CAE = \frac{\angle B} 2, \angle MAC = \frac{\angle A}2$
$ \displaystyle \implies \angle MAE = \frac{\angle B + \angle A}2 = 90^\circ - \frac{\angle C}2$
Also, $ \displaystyle \angle MEA = \angle C \implies \angle AME = 90^\circ - \frac{\angle C}2 = \angle MAE$
$\therefore AE = ME$
Comment: @ACB I agree with you. Once we know $M$ is incenter, that is immaterial and so is the inner circle. But if we did not know $M$ was incenter, it does help us realize that $BE$ is angle bisector.
Comment: I am wondering why it is given that PM=MQ...
Comment: As you said, we can determine that BE is angle bisector. Also we can see that the inner circle is tangent to two sides of the triangle and to the circumcircle at the same time. And we have segments with fixed lengths. So there maybe a way to show M is the incentre, without assuming that.
Comment: @MathLover .. I have found a [way](https://math.stackexchange.com/q/4322021/997661) to prove that M is the incentre. But I don't know how to prove this (which completes the answer): "*Consider two orthogonal circles. Draw a line through the centre of one circle which cuts the other circle at A and B. Any circle through A and B is orthogonal to the first one*". Do you know a proof or any theorem which states this? (Sorry to bother you)
Comment: @MathLover ... Thanks for the source. By the way, I have found another answer to my question which does not involve the above. I'll will post it in a few hours .... FYI: I asked the second question also here, where I was given the same reference you gave :)
Comment: @MathLover ... I posted the answer. Please go through the link above. I think that solves this problem as well.


Unpublished Nodes and Content Access

Question: I have a view that relies on a specific content type to display images. The Content Type has a Title,  a File Field, and a checkbox for show or don't show.  The default setting for all nodes created using this Content Type is unpublished, so that users can't randomly access the node ( basically it's a slideshow that displays banner ads, accessing the actual node isn't a bad problem per se ).
This works great.  As it turns out I also need a members only section for the site, so I installed Content Access.  That works great for restricting access to the nodes I need restricted.  However, I discovered that now the unpublished Slideshow nodes don't show.
My question is how to work around this.  Will another access module work differently or is this a core feature?  Could I write a small module to grant view access to the Slideshow nodes?  Or barring all that, is there a module or ( I know it's probably off-topic) an htaccess recipe that would not allow direct viewing of the nodes of a certain type?
Comment: It sounds as if you just need to check your configuration for Slideshow content type. If this is not what you meant, please elaborate more as it's not quite clear what are you trying to achieve and where is the problem exactly.
Answer: I solved this by making the Content Type nodes published again.  So in my View I check to see if the checkbox is check AND if the node is Published.  The slider works as it should.  I was then left with the task of deciding if allowing access to the actual node was desirable.  Viewing the direct node in my case was not all that bad, it's not restricted content or anything but I felt it would just be sloppy.  So since I had Panels already installed, this solution https://drupal.stackexchange.com/a/19072/12881 worked out great.  If someone stumbled upon one of the nodes of that specific Content Type they're just sent to the front page.

Unpublished Nodes and Content Access


Ajax não entra no success

Question: E estou tendo uma dificuldade em Ajax.
tenho o seguinte:
      beforeSend: function ()
      {
          $("#btnEvniar")
          .prop('disabled', true)
          .click(JaClicouProc(3,this));
      },
      success: function (resultado)
      {
          FechaDivAg();
          swal({
            title: "Sucesso!",
            text: "Helpdesk enviado com Sucesso.",
            showConfirmButton: false,
            timer:3000,
            html: true
          });

          $(".cam").each(function () {
              $(this).val('');
          });
      }

A função JaClicouProc() trava a tela para que o usuário não fique enviando vários helpdesks...
Porém não entra na parte de sucesso do Ajax. esta função FehcaDivAg() destrava a tela.
No arquivo alvo do Ajax que é um arquivo .php estou dando um echo "true";
Alguém sabe o porque não esta entrando em success?
Segue código da função conforme solicitado!
function JaClicouProc(qualmsg, wcam, msgopc)
{
   if (typeof(msgopc) != "undefined")
       ShowAguarde(qualmsg, msgopc);
   else
       ShowAguarde(qualmsg);
//     ShowAguarde(qualmsg);    :MostraAguarde
   document.getElementById(wcam.id).blur();
// gab 2016-07-26. Usa a função para não processar duas vezes (a mesma do botão salvar)
   return true;
}

Comment: Se não entra no Sucess é porque está travando no beforeSend, ele funciona em cascata. Como você mesmo disse, a função JaClicou trava, o erro deve estar nela.
Comment: Faz um teste: comenta todo o beforeSend e veja se entra no success... se entrar, o problema é no beforeSend.
Comment: Coloca o Ajax completo porque outros parâmetros podem influir no resultado.
Comment: mesmo retornando true na função jaClicou? o ajax completo é bem grande! posta mesmo assim?
Comment: Tá entrando no beforeSend?
Comment: sim está entrando.
Comment: então tenta dá um ao invés de `echo "true"` tenta dar um `echo json_encode( array( 'retorno': true ))`
Comment: bom... comentei a função e deu certo... o código é da empresa em q estou trabalhando e não posso mexer em algumas funções... era a função JaClicouProc realmente... Obrigado!
Comment: Se puder colocar o que tem nessa função pra ver o que está acontecendo.
Answer: Se a função beforeSend não retornar true, a requisição é abortada, conforme diz a documentação. Faça assim:
beforeSend: function ()
{
    $("#btnEvniar")
      .prop('disabled', true)
      .click(JaClicouProc(3,this));
    return true;
},

Comment: Legal amigo... agora funcionou perfeitamente... Obrigado! infelizmente fui vetado para fazer mais perguntas... Obrigado a todos.

Ajax não entra no success


grpc/protobuffer ask for specific fields

Question: GraphQL lets you ask for specific fields, the response contains only the fields that you had asked for. For example:
a graphql query like:
{
  hero {
    name
  }
}

will return:
{
  "data": {
    "hero": {
      "name": "R2-D2"
    }
  }
}

where as a graphQl query like:
{
  hero {
    name

    friends {
      name
    }
  }
}

would return:
{
  "data": {
    "hero": {
      "name": "R2-D2",
      "friends": [
        {
          "name": "Luke"
        },
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia"
        }
      ]
    }
  }
}

Is there a similar mechanism/library/pattern that can be used in gRPC  to achieve the same?
Answer: FieldMask is similar in protobuf. It is a list of fields to retain, so the first example would be paths: "hero.name" and the second would be paths: ["hero.name", "hero.friends.name"].
It is probably most frequently used to specify which fields should be changed in an update. But it can equally be used to specify the fields that should be returned.
The server can either process the FieldMask directly (e.g., only using the listed fields in a SELECT SQL query), or it can retrieve all the information and filter the result using FieldMaskUtil.merge() to copy just the requested fields into a new proto message to return to the client.


Could not find android.jar for API Level 25

Question: Estou tentando apenas rodar um simples "Hello World", no Visual Studio. Criei um projeto do tipo Cross Plataform. Eu instalei o Visual Studio 2017, ao tentar rodar não abre o emulador, gerando o seguinte erro:
Erro: Could not find android.jar for API Level 25. This means the Android SDK platform for API Level 25 is not installed. Either install it in the Android SDK Manager (Tools > Open Android SDK Manager...), or change your Xamarin.Android project to target an API version that is installed. (C:\Program Files (x86)\Android\android-sdk\platforms\android-25\android.jar missing.)
Answer: aparentemente só está faltando a plataforma para a qual seu projeto foi criado, então deves instalar a versão correta. Vá em Ferramentas>> Android>>Gerenciador do SDK do Android, sem seguida selecione a opção da versão do pacote correspondente, clique em Instalar Pacote. Isto deve resolver.


Can degree of root field exceed the number of roots?

Question: I'm doing a self study in Abstract Algebra, and have a question that seems like it should be very easy.  (Perhaps, I'm just in overload.)
Can the degree of a root field of a polynomial exceed the number of roots?
More formally:
Let a(x) be any polynomial in F[x], where F is a field, and let F(c1,c2,...,cn) be the root field of a(x).  Then can [F(c1,c2,...,cn]:F] exceed the number of roots of a(x)?
Answer: Certainly! Take $F=\mathbb{Q}$ and let $f=t^3-2$, for instance. If $\zeta=e^{2\pi i /3}$, then $f$ has roots $2^{1/3}, \zeta 2^{1/3}, \zeta^2 2^{1/3}$, so the root field of $f$ over $F$ is $F(\zeta, 2^{1/3})$. Now $F(2^{1/3})$ is contained in this root field and is a degree three extension over $F$ since the polynomial $t^3-2$ is irreducible over $F$ (by Eisenstein, say), but $F(2^{1/3})$ cannot be the whole root field since it's contained in $\mathbb{R}$! Thus the degree of the root field over the base field has to be strictly greater than three.
It's not hard to see that the degree of the extension is actually 6.
Answer: Let me assume $p(X)\in F[X]$ is irreducible.
The degree of the splitting field of $p$ over $F$ is at least n, and is at most $n$-factorial. In fact, it's much more likely to be $n!$ than not as $n$ grows large.
If the splitting field of $p(X)$ has degree $n$, $p(X)$ is called a normal polynomial. These are quite exceptional, with the property that $F(\alpha)$ is Galois over $F$, for any root $\alpha$ of $p(X)$.


Real Analysis basic questions

Question: I am studying for math 400 lvl class and I forgot how one to one function on infinity value. For instance, consider the following:
$$f(x)=tx+g, \hspace{1cm} -\infty < x < + \infty, \quad t,g, \in \mathbb{R}.$$
Question: is is it one to one? I think it is not one to one function because it fails horizontal line test when it's graphed.
Please correct me if i am wrong. Any help would be appreciated it. Thank you
Answer: First you need to remind yourself what is the condition for the function be one-to-one, and that is
$$f(x) = f(y) \text{ implies } x=y, \text{ for all } x,y \in \mathbb{R}.$$
Let's figure if this is true for the given function. Assuming $f(x) = f(y)$ we have
$$tx+g = ty+g, \text{ therefore } tx=ty.$$
If $t = 0$ then it is not one-to-one, as for any values of $x,y$ we have $0 \cdot x = 0 \cdot y$.
If $t \neq 0$, on the other hand, we can divide by it, obtaining $x=y$, hence an one-to-one function.
Comment: Thank you very much. i deeply appreciate your help.

Real Analysis basic questions


Server 2008/Windows 7/Samba Unspecified error 80004005

Question: I have a Samba share on a LAN with 2008 PDC/DNS. Smb authenticates with AD and I have several Win7 Machines that can connect fine.
I recently added a couple of new computers to the LAN which were imaged the same way (same software, etc.; different hardware so different drivers) as the other machines and they have the same policies set.
I can not get the new machines to connect to the samba share no matter what. I am always met with either Unspecified Error 0x80004005 or Network Path not found.
I've turned off the firewall; set LANMAN auth to respond to NTLM only/send LM & NTLM responses/use NTLM session security if negotiated in Local Sec Policy > SEcurity Options; tried both ip and hostname to connect.
SMB log shows that authentication succeeds; but then connection is immediately killed by the client.
tcpdump shows nothing remarkable except that when trying to connect from the client via hostname there is an unknown packet type error:
ack 201 win 255 NBT Session Packet: Unknown packet type 0xABData: (41 bytes)

Here's a couple of lines from that error:
11:18:37.964991 IP 001-client.domain.local.49372 > smb.domain.local.netbios-ssn: P 1670:2146(476) ack 201 win 255 NBT Session Packet: Unknown packet type 0xABData: (41 bytes)
[000] AA 46 96 FA D5 99 33 75  0C C4 20 CE 26 42 F3 61  \252F\226\372\325\2313u \014\304 \316&B\363a
[010] F0 8C FB 65 18 17 40 A5  DB 42 BB 94 37 53 92 EC  \360\214\373e\030\027@\245 \333B\273\2247S\222\354
[020] 55 98 7F C4 AE 3D 6B 10  C4                       U\230\177\304\256=k\020 \304

11:18:37.964998 IP smb.domain.local.netbios-ssn > 001-client.domain.local.49372: . ack 2146 win 100

[edit for strike: this turned out to be an issue with arp cache and the client being issued an old ip from dhcp that previously belonged to another machine]
I'm also getting this error consistently:
[2012/09/10 11:50:00.529650,  2] smbd/sesssetup.c:1413(setup_new_vc_session)
  setup_new_vc_session: New VC == 0, if NT4.x compatible we would close all old resources.

Here's smb.conf just in case (though don't see how if other machines are working fine):
[global]
    workgroup = MYDOMAIN
    realm = MYDOMAIN.LOCAL
    server string = domain|smb share
    interfaces = eth1
    security = ADS
    password server = 192.168.1.3
    log level = 2
    log file = /var/log/samba/%m.log
    smb ports = 139
    strict locking = no
    load printers = No
    local master = No
    domain master = No
    wins server = 192.168.1.3
    wins support = Yes
    idmap uid = 500-10000000
    idmap gid = 500-10000000
    winbind separator = +
    winbind enum users = Yes
    winbind enum groups = Yes
    winbind use default domain = Yes

[samba-share1]
    comment = SMB Share
    path = /home/share/smb/
    valid users = @"MYDOMAIN+Domain Users"
    admin users = @"MYDOMAIN+Domain Admins"
    guest ok = no
    read only = No
    create mask = 0765
    force directory mode = 0777

Any ideas what else I could try or look for? Or what might be the problem?
Thanks.

Update 1
Noticed on the other machines that Local Security Policy > LAN Manager authentication level was Not Defined. There is no way to set it as such through the LSP editor, so had to go into regedit and delete HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\lmcompatibilitylevel
However, this didn't solve the issue. Am now met with Accessing the resource '\\smb\share' has been disallowed. or Unspecified Error depending on who I'm logged in as (regular user == former; admin == latter)

Update 2
It's incredibly frustrating when you ask a question on SF and in the interim keep searching for answers only to find a couple of hours later your own question is repeatedly the first google result ;)

Update 3
I ran Wireshark on the client, and so far as I can tell everything on the Samba end is working correctly. I see in a Negotiate Protocol Request an NT Status of STATUS_SUCCESS (which may very well be the authentication success, but don't know).
Everything is pointing to an issue on the Client itself. On other machines, everything works as expected. Including a VM running on my box. It works using both admin and regular user credentials.
NB the client I'm trying to get this working on has Firewall off and no a/v etc for the time being while trying to work this out.
I've updated the NIC driver and there is only 1 iface available. DNS is working and I've matched up all the settings I can find to the working VM and other working machines.
Getting desperate so any ideas would be awesome.
Answer: So the issue seems to have been that secpol was set to Digitally Sign Communications (Always).
To fix: Secpol.msc > Local Policies > Security Options > Microsoft network client: Digitally sign communications (always) => Disable
Thanks.
edit:
as the-wabbit said, it is better to update samba to handle the requirement rather than disable it so as to maintain security.
Comment: SMB signing issues are indeed quite often the cause for connection failures with obscure error messages. But instead of disabling signing altogether, I would advocate enabling it on the Samba server side as it is an important security feature. `server signing = mandatory` in the `[global]` section of /etc/samba/smb.conf should take care of the problem.
Comment: Maybe this answer might help so that samba signs connections automatically? http://superuser.com/a/707701/91022
Answer: Try to to enable only SMB 2 or 3 on server or just on windows client. In the registry set value on 1 for: AllowInsecureGuestAuth in key:
HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\
Answer: If the Samba server runs SMBv1, then new machines with Win10 have a problem, since they're missing the SMBv1 client function. To enable that function, follow this guide from windowscentral.com:

Open Control Panel (the good old one, not the "touch" version)
Click on Programs.
Click on Turn Windows features on or off link.
Expand the SMB 1.0/CIFS File Sharing Support option.
Check the SMB 1.0/CIFS Client option.
Click the OK button.
Click the Restart now button (restart is really needed since it needs to install the function when turning off the computer)
Comment: Alternatively, you can add the line `min protocol = SMB2` to your smb.conf file.
Answer: Set the following registry value to  1
HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters\AllowInsecureGuestAuth
If its not there create the value as a DWORD
Answer: I got 0x80004005 permission error:

for another reason I have no active Client for Microsoft Networks in my WiFi dangle Network panel and:

Change Network security: LAN Manager Authentication Level to "Send LM & NTLM responses"
Change Minimum Session Security for NTLM SSP to disable "Require 128-bit encryption" into "No Minimum Security".

and possibly:

Uninistalling KB2536276.
Answer: In my case this was caused by the server's firewall allowing TCP port 139, but blocking port 445. It seems that Windows 10 always uses port 445, not 139.
Answer: In my case problem was in smb encrypt configured as desired.
Try to alter this option with different values, in my case server smb encrypt = required
fixed the problem.
Comment: where did you set this? smbd.conf? under global. please provide more information
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to set empty or null value doesn't worked in Jquery change

Question: I want the value in the input text to be null after the hide process
This is my view :

  Status Karyawan

    <select id="status" name="status" class="form-control form-control-sm" required>
        <option value="" selected>Pilih Status Karyawan</option>
        <option value="Kontrak">Kontrak</option>
        <option value="Tetap">Tetap</option>
    </select>

  Tgl. Pengangkatan

    <input name="tgl_pengangkatan" type="text" class="form-control datepicker form-control-sm" id="tgl_pengangkatan" placeholder="yyyy-mm-dd" value="">

  Tgl. Akhir Kontrak

    <input name="tgl_berakhir_kontrak" type="text" class="form-control datepicker form-control-sm" id="tgl_berakhir_kontrak" placeholder="yyyy-mm-dd" value="">

And than, this is my script:


How to make a countdown timer in Android?

Question: I have two EditTexts in XML. In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second.
Additionally, how can I keep it updating until it gets to zero minutes and zero seconds?
Comment: possible duplicate of [Android countdown](http://stackoverflow.com/questions/10010684/android-countdown)
Answer: As shown in the documentation for CountDownTimer:

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        // logic to set the EditText could go here
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

Comment: This is a nice answer but can anyone show me how to do a custom set countdown time rather than just inputting 30 seconds? I tried getting the value from an EditText but it didn't seem to work at all.
Comment: What if I wanted to base the CountDownTimer on a set alarm? How do I know how many milisUntilFinished?
Comment: Do you know if there is a pause method for the `countdowntimer`? So say the user wanted to pause a game they clicked a button and the countdown timer is paused and when they click play it keeps on ticking?
Comment: What will happen if i set timer for 24h for example everything is working fine but user changes his device time How to Avoid that?
Answer: if you use the below code (as mentioned in accepted answer),
new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

It will result in memory leak of the instance of the activity where you use this code, if you don't carefully clean up the references.
use the following code
//Declare timer
CountDownTimer cTimer = null;

//start timer function
void startTimer() {
    cTimer = new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
        }
        public void onFinish() {
        }
    };
    cTimer.start();
}

//cancel timer
void cancelTimer() {
    if(cTimer!=null)
        cTimer.cancel();
}

You need to call cTtimer.cancel() whenever the onDestroy()/onDestroyView() in the owning Activity/Fragment is called.
Comment: Yes! 10/10. this should be correct answer. OR else even though you press BACK, the countDownThread is very much working. You can place a Log.i, and you will see it throwing up info every 1sec, if you dont put a ".cancel()".
Comment: is there a way to check if the CountDownTiner is still running before cancelling?
Comment: check if timer is !=null
Comment: What will happen if i set timer for 24h for example everything is working fine but user changes his device time How to Avoid that? @AbdulrahmanAbdelkader
Answer:
MainActivity.java
package com.zeustechnocrats.countdown;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private String EVENT_DATE_TIME = "2023-12-31 10:30:00";
    private String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private LinearLayout linear_layout_1, linear_layout_2;
    private TextView tv_days, tv_hour, tv_minute, tv_second;
    private Handler handler = new Handler();
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.count_down);

        initUI();
        countDownStart();
    }

    private void initUI() {
        linear_layout_1 = findViewById(R.id.linear_layout_1);
        linear_layout_2 = findViewById(R.id.linear_layout_2);
        tv_days = findViewById(R.id.tv_days);
        tv_hour = findViewById(R.id.tv_hour);
        tv_minute = findViewById(R.id.tv_minute);
        tv_second = findViewById(R.id.tv_second);
    }

    private void countDownStart() {
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    handler.postDelayed(this, 1000);
                    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
                    Date event_date = dateFormat.parse(EVENT_DATE_TIME);
                    Date current_date = new Date();
                    if (!current_date.after(event_date)) {
                        long diff = event_date.getTime() - current_date.getTime();
                        long Days = diff / (24 * 60 * 60 * 1000);
                        long Hours = diff / (60 * 60 * 1000) % 24;
                        long Minutes = diff / (60 * 1000) % 60;
                        long Seconds = diff / 1000 % 60;
                        //
                        tv_days.setText(String.format("%02d", Days));
                        tv_hour.setText(String.format("%02d", Hours));
                        tv_minute.setText(String.format("%02d", Minutes));
                        tv_second.setText(String.format("%02d", Seconds));
                    } else {
                        linear_layout_1.setVisibility(View.VISIBLE);
                        linear_layout_2.setVisibility(View.GONE);
                        handler.removeCallbacks(runnable);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, 0);
    }

    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(runnable);
    }
}

activity_main.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/linear_layout_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:gravity="center_horizontal"
        android:visibility="gone">

        <TextView
            android:id="@+id/tv_event"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="Android Event Start"
            android:textColor="@android:color/white"
            android:textSize="20dp"
            android:textStyle="normal" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear_layout_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_days_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Days"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_hour"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_hour_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Hour"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_minute"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_minute_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Minute"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_second"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_second_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Second"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Comment: Do not forget to clean the timer once the activity is destroyed. Otherwise you will sendup with memory leak
Comment: Why `handler.postDelayed(runnable, 1 * 1000);` ??
Comment: handler.postDelayed(runnable, 0) = handler.post(runnable)
Comment: excellent solutions if anybody wants to add time zone try this dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
Answer: just copy paste the following code........
MainActivity
package com.example.countdowntimer;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;

public class MainActivity extends Activity {

      TextView text1;

 private static final String FORMAT = "%02d:%02d:%02d";

 int seconds , minutes;

@Override
public void onCreate(Bundle savedInstanceState) {

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

    text1=(TextView)findViewById(R.id.textView1);

    new CountDownTimer(16069000, 1000) { // adjust the milli seconds here

        public void onTick(long millisUntilFinished) {

            text1.setText(""+String.format(FORMAT,
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
  TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                      TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
        }

        public void onFinish() {
            text1.setText("done!");
        }
     }.start();

  }

  }

activity_main.xml
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="34dp"
    android:layout_marginTop="58dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

   </RelativeLayout>

Comment: Please do not encourage copy pasting of code. A link to documentation and explanation would have been a better answer.
Comment: but when my mobile locked its paused and when i unlocked it will resume..what can i do for continues timer ??
Answer: Just Call below function by passing seconds and textview object
public void reverseTimer(int Seconds,final TextView tv){

    new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("TIME : " + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

Comment: Perfect case to catch NPE.
What happens when activity is destroyed and timer remains running?
Answer: Revers CountDown timer with hours minutes and seconds
public void reverseTimer(int Seconds, final TextView tv) {

    new CountDownTimer(Seconds * 1000 + 1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);

            int hours = seconds / (60 * 60);
            int tempMint = (seconds - (hours * 60 * 60));
            int minutes = tempMint / 60;
            seconds = tempMint - (minutes * 60);

            tv.setText("TIME : " + String.format("%02d", hours)
                    + ":" + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

Answer: Using Kotlin:
var timer = object: CountDownTimer(30000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tvTimer.setText("seconds remaining: " + millisUntilFinished / 1000)
        }

        override fun onFinish() {
            tvTimer.setText("done!")
        }
    }
timer.start()

Answer: Output: 01:30
new CountDownTimer(90000, 1000) {

            public void onTick(long duration) {
                //tTimer.setText("seconds remaining: " + millisUntilFinished / 1000);
                //here you can have your logic to set text to edittext resource id
                // Duration
                long Mmin = (duration / 1000) / 60;
                long Ssec = (duration / 1000) % 60;
                if (Ssec < 10) {
                    tTimer.setText("" + Mmin + ":0" + Ssec);
                } else tTimer.setText("" + Mmin + ":" + Ssec);
            }

            public void onFinish() {
                tTimer.setText("00:00");
            }

        }.start();

Answer: public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}
Answer: var futureMinDate = Date()
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
try {
    futureMinDate = sdf.parse("2019-08-22")
} catch (e: ParseException) {
    e.printStackTrace()
}

// Here futureMinDate.time Returns the number of milliseconds since January 1, 1970, 00:00:00 GM
// So we need to subtract the millis from current millis to get actual millis
object : CountDownTimer(futureMinDate.time - System.currentTimeMillis(), 1000) {
    override fun onTick(millisUntilFinished: Long) {
        val sec = (millisUntilFinished / 1000) % 60
        val min = (millisUntilFinished / (1000 * 60)) % 60
        val hr = (millisUntilFinished / (1000 * 60 * 60)) % 24
        val day = ((millisUntilFinished / (1000 * 60 * 60)) / 24).toInt()
        val formattedTimeStr = if (day > 1) "$day days $hr : $min : $sec"
        else "$day day $hr : $min : $sec"
        tvFlashDealCountDownTime.text = formattedTimeStr
    }

    override fun onFinish() {
        tvFlashDealCountDownTime.text = "Done!"
    }
}.start()

Pass a future date and convert it to milliseconds.
Answer: The Interface way.
import android.os.CountDownTimer;

/**
 * Created by saikiran on 07-03-2016.
 */
public class CountDownTimerCustom extends CountDownTimer {

    private TimeTickListener mTickListener;
    private TimeFinishListener mFinishListener;
    private long millisUntilFinished;

    public CountDownTimerCustom(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);

    }

    public void updateTickAndFinishListener(TimeTickListener tickListener) {
        mTickListener = tickListener;
    }

    public void updateFinishListner(TimeFinishListener listener) {
        mFinishListener = listener;
    }

    public long getCurrentMs() {
        return millisUntilFinished;
    }

    public int getCurrentSec() {
        return (int) millisUntilFinished / 1000;
    }

    @Override
    public void onTick(long millisUntilFinished) {
        this.millisUntilFinished = millisUntilFinished;
        if (mTickListener != null)
            mTickListener.onTick(millisUntilFinished);
    }

    @Override
    public void onFinish() {
        if (mTickListener != null)
            mTickListener.onFinished();
        mFinishListener.onFinished();
    }

    public interface TimeTickListener {
        void onTick(long mMillisUntilFinished);

        void onFinished();
    }

    public interface TimeFinishListener {
        void onFinished();
    }
}

Comment: if it possible to provide more code for starters :)
Comment: @shareef Hi, what are you looking for?
Comment: I mean gist or repo for usage would be great
Answer: Here's the solution I used in Kotlin
private fun startTimer()
{
    Log.d(TAG, ":startTimer: timeString = '$timeString'")

    object : CountDownTimer(TASK_SWITCH_TIMER, 250)
    {
        override fun onTick(millisUntilFinished: Long)
        {
            val secondsUntilFinished : Long =
            Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
            val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
                    "%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish()
        {
            timerTxtVw.text = "0:00"
            gameStartEndVisibility(true)
        }
    }.start()
}

Answer: Try this way:
private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }

        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}

Answer: // the count down timer

 new  CountDownTimer(30000, 1000)
         {
        @Override
        public void onTick(long l) {

        }
        @Override
        public void onFinish() {

                //on finish the count down timer finsih
                         }

            }
        }

    }.start();

Answer: Clean solution with Rx, someone might be interested in
Extension for Numbers (Double, Float, Long, etc.):
fun Number.countDownTimer(tick: Long = 1, timeUnit: TimeUnit = TimeUnit.SECONDS): Observable<Long> {
    val count = this.toLong()
    return Observable.interval(tick, timeUnit)
        .take(count)
        .map { count - it - 1 }
}

Usage
60.countDownTimer().subscribe { textView.text = it }

Answer: I achieve a cool approach for the timer with kotlin flows so you can implement this in ViewModel
    var countDownInit = 30
    fun countDownTimer() = flow<Int> {
    var time = countDownInit
    emit(time)
    while (true){
        time--
        delay(1000L)
        countDownInit = time
        emit(time)
    }
}

then in your activity or fragment just call this function like this
lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                 viewModel.countDownTimer().collect{time->
                      //and update UI
                     //and for the finish section you can just use this
                     this.cancel()
                 }
        }
}

And there is now crash or sth on the pause of the application lifecycle and always you have the latest seconds


How To Negate the Formal Definition of an Injective Function

Question: in my linear algebra class, the professors gave us a formal definition of an injective function, which is
Given a function f,
if $\forall$ x, x' $\in$ $R$ where x $\ne$  x' $\implies$ f(x) $\ne$ f(x'), then f is injective.
I am trying to negate this statement for a proof, but am unsure if I am thinking of this correctly. From what I am able to deduce, this can be broken down into its logical statements. The definition says that we have a P which implies a Q. In this case, the P is [$\forall$ x, x' $\in$ $R$ where x $\ne$  x' $\implies$ f(x) $\ne$ f(x')], and Q is [f is injective.] And if we look at the statement P, we can think about that in terms of R implies T. This is where I get tripped up. The P is [∀ x, x' ∈ R where x ≠ x'] and the Q is [f(x) ≠ f(x')]. Q is clearly a statement. f(x) either does or does not equal f(x'). But, R, which is [∀  x, x' ∈ R where x ≠ x'] does not have a truth value - or the truth value is dependent on x $\ne$ x', which still does not make sense to me.
I say that it does not make sense because I don't understand how to negate this statement. Negating P $\implies$ Q can be written as P $\wedge$ $\neg$Q. This would be equivalent to
[$\forall$ x, x' $\in$ $R$ where x $\ne$  x' $\implies$ f(x) $\ne$ f(x')] $\wedge$ [f is not injective].
While that is logically true, that does not give us any insight into the type of function that a non-injective function is. Intuitively speaking, a function that is not injective can be written as
if $\exists$ x, x' $\in$ $R$ where x $\ne$  x' $\implies$ f(x) = f(x'), then f is not injective.
I cannot figure out how to use logical equivalencies and negations to arrive at that statement. Any help with understanding how to arrive at this definition from the original definition is greatly appreciated.
Comment: When your professor asked you to "negate the definition of an injective function", I'm certain they wanted you to just simplify $\lnot((\forall x, x' \in \Bbb{R})(x \neq x' \implies f(x) \neq f(x'))$. That is, they wanted you to state what it means for a function to *not* be injective. You don't have to include $Q : f$ is injective as part of the negation. After all $((\forall x, x' \in \Bbb{R})(x \neq x' \implies f(x) \neq f(x')) \implies f$ is injective is a tautology, and its negation is simply $F$.
Answer: The reason of your confusion is that the definition you quoted is actually not fully formal, it mixes up English and symbols of formal logic in a bit loosy manner. If I was to give a definition of an injective function I would not write
$$ \forall x,\ x' \in R \  where\  x \ne  x' \implies f(x) \ne f(x')$$
but instead I would say that a function $f: R \rightarrow S$ is injective if and only if
$$ \forall x,\ x' \in R: x \neq x' \implies f(x) \ne f(x').$$
And now the negation is easy:
$$ \exists x,\ x' \in R: x \neq x' \land f(x) = f(x').$$
From formal point of view, the literal definition you quoted is incorrect (more strictly speaking it is not even a definition - precisely for the fact that "$x,\ x'\ where\ x \neq x'$" is not a sentence) - so no point in trying to negate it.


Por que meu Client só envia duas solicitações?

Question: Meu HttpClient só tá enviando duas solicitações. O server recebe, retorna os 2 valores mas ele na verdade é um loop que envia um monte de vezes! Alguém pode me ajudar?
public static void main(String[] args) throws IOException, InterruptedException {
    SendData sender = new SendData();
    String JsonDeDados;
    String infos = "informacoes";

    HttpClient client = HttpClientBuilder.create().build();
    CloseableHttpClient clientclose = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://localhost:5030/data");

    do {

        JsonDeDados = sender.sendMessageDATA();
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair(infos, JsonDeDados));
        StringEntity entity = new StringEntity(JsonDeDados);

        post.setEntity(entity);
        post.setHeader("Content-Type", "application/json");

        CloseableHttpResponse response = (CloseableHttpResponse) client.execute(post);
        System.out.println("Código da Resposta: " + response.getStatusLine().getStatusCode());
        clientclose.close();
        Thread.sleep(1000);

    }while(true);

}

Comment: Como está feita a estrutura do laço? Sem o laço, fica difícil adivinhar o que está acontecendo no controle de fluxo de execução
Comment: é um do while(true) normal, pra ficar enviando eternamente
Comment: Editei o código pra ficar mais completo, mas já me deram downvotes :c
Comment: `clientClose` é instanciados uma única vez e fechado diversas vezes? E não é usado uma vez se quer antes de ser fechado?
Answer: Acho que pode estar faltando o comando .releaseConnection(); no seu HttpPost. Possivelmente vai ficar:
post.releaseConnection();

Tenta isso, se não for, pode ser algo no seu laço de repetição
Comment: Onde eu posso posicionar essa linha? Depois do clientclose.close(); ?
Comment: É, isso mesmo. Tenta e informa se deu certo.
Comment: Funcionou, você poderia dar uma explicação rápida sobre o que esse comando faz?
Comment: Então, como o próprio comando diz, ele "solta" a conexão. Assim você não fica com uma "fila" de requests. Como ele tá dentro do laço, ele abre a conexão, envia, fecha. Abre, envia, fecha. E assim vai. Espero ter ajudado, e recomendo dar uma lida nesse [artigo](https://www.mkyong.com/java/apache-httpclient-examples/)


C++: Is the ignored return value destruction behavior well-defined

Question: Question: Is an ignored return value destructed immediately or at the moment going out of scope.?
The code below returns for my compiler
Output:

Who makes it, has no need of it.
Who buys it, has no use for it.
Who uses it can neither see nor feel it.
What is it?

Therefore the ignored value is destructed immediatly. But is this compiler specific or standard-behavior?
<code>struct foo
{
   ~foo()
   {
      std::cout << "Who makes it, has no need of it. \n"
                << "Who buys it, has no use for it. \n";
   }
}

foo createFoo()
{
   return foo();
}

int main(int argc, char* argv[])
{
     createFoo();
     std::cout << "Who uses it can neither see nor feel it.\n"
               << "What is it?";
}
</code>
Answer: The returned temporary is destroyed immediately after the full expression completes except if its lifetime is extended by being bound to an rvalue or const lvalue reference.
Comment: ... or to an rvalue reference.
Comment: Just remove the word "const".  Also, the verb is *destroyed*.
Comment: @MarkB: I disagree that it makes any claim about the particularities of the reference binding rules.  For example, you don't feel compelled to explain polymorphism and binding to a base-typed reference here, do you?
Comment: maybe an example would be helpful
Comment: @Ben Voigt Unfortunately if I remove the word `const` then it sounds like you can bind a return by-value to a non-const lvalue reference.
Answer: In the standard 5.11 has

In some contexts, an expression only appears for its side effects. Such an expression is called a discarded-value
  expression. The expression is evaluated and its value is discarded.

So when the expression ends the value is then discarded and if it is a class type then the destructor is called.
Comment: In addition to this, 12.8.32 points out that  the compiler MAY omit copying of the return value, as it did here.  A different compiler may print the first half of the riddle twice because it would destroy one copy as it left `createFoo`'s scope and once on the line in `main` calling `createFoo`, as Nathan's answer points out.
Answer: §12.2 /3

Temporary objects are destroyed as the last step
  in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying
  a temporary object are associated only with the full-expression, not with any specific subexpression.

Exceptions are for constructor arguments, and for binding references to a temporary. (§12.3/4f.)
Comment: Particularly, only temporaries created by constructor default arguments.
Comment: There's an additional exception that occurs when initializing arrays.