Set NTP not to receive time from peers on Ubuntu

Question: In my /etc/ntp.conf, it says
By default, exchange time with everybody, but don't allow configuration.
restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery

I'd like to only receive time from the specified servers to prevent DDoS attacks like this.
How can this file be modified so that time is not received from peers?
Comment: Mouse over the down arrow; the popup says "*This question does not show any research effort; it is unclear or not useful*".  Downvotes without comment may be presumed to be for at least one of those reasons.
Answer: If the server is publicly accessible, you should have this line in your configuration:
restrict default kod limited nomodify noquery nopeer notrap

If you need remote management functions you can add restrict lines after that allowing particular IPs access. If it's not publicly accessible then you don't need to worry about the 'monlist' amplification attack.
You really should not be running a public NTP server if you don't know what you're doing. The management functions this line blocks, and which are exploited in the attack you linked to, have nothing to do with exchanging time with other systems. Also, "peers" different from "clients" and "servers" in NTP.
Edit:
The above just disables all admin functionality (which is the only thing that is known to be exploitable). NTP will not synchronize against anything unless it's specifically told to do so (via a server, peer, broadcast, or manycastclient directive - or a S0 hardware clock).
By default NTP will serve client requests, acting as a server - to disable this add noserve to the restrict statement above. This particular option allows you to allow some management functions while disallowing clients to synchronize time.
Alternately, if you want NTP to not "listen" to anything you can add this line instead:
restrict default ignore

Comment: Correct, that will put it in a "unmanaged client-only" mode.
Comment: See edit above.
Comment: You can't use `ntpq` on an "**unmanaged** client-only" ntpd. Blocking the port at the firewall works, so long as an attacker doesn't find another way onto your system.
Answer: You should specifically list the servers you want to listen to:
server 192.168.1.10

make sure broadcast is commented out.
Comment: -1 Sorry, but this isn't what he's actually asking for.
Comment: Just curious, why don't you want to share with peers?  Do you not trust them?  You could also turn on authentication so that you can be sure the server is really them.
Comment: Then cryptographic authentication is probably the way to go.
Comment: http://www.ntp.org/ntpfaq/NTP-s-config-adv.htm#S-CONFIG-ADV-AUTH
Comment: Actually the link explains how to set up authenticated NTP, which would solve his problem as revised by the comment thread.


$\lim_{n\rightarrow\infty}\int|f|^{1/n}d\mu=\mu(E_{f})$

Question: I've proved the next:
Let $(X,S,\mu)$ be a measurable space and $f\in L_{1}(\mu)$ such that $\mu(E_{f})<\infty$ where $$E_{f}=\{x\in X: f(x)\neq0\}.$$ Then $$\displaystyle\lim_{n\rightarrow\infty}\int|f|^{1/n}d\mu=\mu(E_{f}).$$
It's enough to apply Holder's Inequality to $|f|^{1/n}$ and $\mathcal{X}_{E_{f}}$ and by the other hand splits $|f|^{1/n}$ on the intervals $(0,1)$ and $[1,\infty).$
My question is: the above remains valid for $\mu(E_{f})=+\infty?$
Answer: Yes. Let $A=\{|f|\ge 1\}$ and $B=\{0<|f|<1\}$. Then $\int_A|f|^{1/n}\to\mu(A)$ by dominated convergence, while $\int_B|f|^{1/n}\to\mu(B)$ by monotone  convergence.
Comment: Cool!! Thanks @David C. Ullrich.


How the clear ListPicker selection with SelectionMode Multiple

Question: the orignal problem is :
I am able to clear the selection in listpicker dropdown buts its not resetting the text on corresponding textview.
Hers is how am clearing the selection:
<code>if (Location.SelectedItems != null)
{
    Location.SelectedItems.Clear();
}
</code>
Answer: I did not understand your question completely. But if you want to clear the selection for listpicker Try this
<code> Location.SelectedItems = null;
</code>
Or for Single Item
<code> Location.SelecteItem = null;
</code>


R: Looping over vector of strings for function input

Question: I have a vector of inputs in R and a function f.
inputs <- c('input1','input2','input3',...,'input10')
I want to obtain output <- c(f(input1),f(input2),...,f(input10)) without writing this out.
How can I do this in an efficient manner, and without using a for loop? Also, I'd like to do this without referring to the subscript on input (I just numbered it for the sake of this question).
Further, f('input1') does not work while f(input1) does. How can I resolve this?
Answer: Hope Vectorize could help
Vectorize(f)(inputs)

Comment: @FakeAnalyst56 Yes, you got it. you need `mget`, then try `sapply(mget(inuts),f)`
Comment: I still seem to run into the issue of "f('input1') does not work while f(input1) does." How can I fix 'inputs'?
Comment: Oh I think I figured it out: using mgets(inputs).


Create empty lists with name of attributes of other lists

Question: I have a list which, lets say it looks like this:
alist = ["apple", "tea", "oranges"]

What I want python to do now is take each attribute and create an empty list out of it. So basically this:
apple = []
tea = []
oranges = []

How can I accomplish this?
Comment: duplicate. sorry about that!~
Answer: You could (but shouldn't) use exec:
for item in alist:
    exec(item + " = []")

This is, however, generally discouraged. Use a dict instead:
list_dict = {}
for item in alist:
    list_dict[item] = []

Comment: Thanks. I guess I need lists since I have more VALUES which need to go into these created lists (and the dic only has one KEY). However, with your solution `exec`. How would I append something to these created lists? Of course with `.append`, but how (since it does not give me anything as an output)
Comment: These lists now exist. If `alist` contained `"apple"`, then there is a list called `apple` that you can use like any other list (e.g., `apple.append(...)`)
Answer: You could do so by holding the list names as the keys of a dictionary. Something like this:
alist = ["apple", "tea", "oranges"]
yourListDict = {}
for name in alist:
    yourListDict[name]=list()

Output:
yourListDict['apple']
=> []

An alternative syntax would be:
{k: [] for k in alist}

as Jon Clements points out in: https://stackoverflow.com/a/14241195/2259303
Comment: I support the `dict` recommendation, but that's not valid Python syntax.
Comment: @DSM just realized. updated. thanks!
Comment: Thanks. But I think I need lists since I will `.append` more than one value to the so created list. That would end in trouble with the dic when I try to assign more than one VALUE to the same KEY
Comment: @Christoph the values *are* lists. you could do `yourListDict['apple'].append("myString")`. then if you printed `yourListDict['apple']` you'd get `["myString"]`. It would work just like a list! the only thing different is  how you access it.


If $p =\frac{4\sin\theta \cos\theta}{\sin\theta +\cos\theta}$ Find the value of $\frac{p+2\sin\theta}{p-2\sin\theta}$

Question: Problem :

If $\displaystyle p =\frac{4\sin\theta\cos\theta}{\sin\theta +\cos\theta}$, find the value of $\displaystyle \frac{p+2\sin\theta}{p-2\sin\theta} + \frac{p+2\cos\theta}{p-2\cos\theta}$.

Please help how to proceed in such problem..Thanks..
Answer: HINT:
So, we have $$\frac p{2\sin\theta}=\frac{2\cos\theta}{\sin\theta+\cos\theta}$$
Apply Componendo and dividendo to get $$\frac{p+2\sin\theta}{p-2\sin\theta}=\frac{2\cos\theta+\sin\theta+\cos\theta}{2\cos\theta-(\sin\theta+\cos\theta)}=\frac{\sin\theta+3\cos\theta}{\cos\theta-\sin\theta}$$
Similarly,  $$\frac p{2\cos\theta}=\frac{2\sin\theta}{\sin\theta+\cos\theta}\implies \frac{p+2\cos\theta}{p-2\cos\theta}=...=\frac{3\sin\theta+\cos\theta}{\sin\theta-\cos\theta}=-\frac{3\sin\theta+\cos\theta}{\cos\theta-\sin\theta}$$

Alternatively, $$\frac{p+2\sin\theta}{p-2\sin\theta}=\frac{\frac p{2\sin\theta}-1}{\frac p{2\sin\theta}+1}=\frac{\frac{2\cos\theta}{\sin\theta+\cos\theta}+1}{\frac{2\cos\theta}{\sin\theta+\cos\theta}-1}=\frac{2\cos\theta+(\sin\theta+\cos\theta)}{2\cos\theta-(\sin\theta+\cos\theta)}$$
$$\implies \frac{p+2\sin\theta}{p-2\sin\theta}=\frac{\sin\theta+3\cos\theta}{\cos\theta-\sin\theta}$$
Similarly for $$\frac{p+2\cos\theta}{p-2\cos\theta}$$
Comment: @sultan, when you notice the required expression to be of the form  $$\frac{a+b}{a-b}\text{ or } \frac{a-b}{a+b},$$ you can safely go for Componendo and dividendo
Comment: May I know the mistake here? If "Componendo and dividendo" is the objection (no sure why), there is also the alternatively method mentioned in the answer
Answer: You can directly substitute the value P in the given term
We get:
$\large \large \frac {3\sinθ  +  \cosθ}{\sinθ  -  \cosθ}    +         \frac {3\cosθ  +  \sinθ}{\cosθ -  \sinθ}$
which simplifies to $2$
Answer: Note that $$\frac{p}{2\cos\theta}=\frac{2\sin \theta}{\cos\theta+\sin\theta}$$ and
$$\frac{p}{2\sin\theta}=\frac{2\cos \theta}{\cos\theta+\sin\theta}$$
Now apply the componendo-dividendo method to the first and second equalities and sum them up, you'll get the answer. It'll be $2$.


List all the subgroups of C12 and compute the index of each

Question: Ok, so I'm slowly progressing with my Abstract course. Ill post my work first and then point out my confusion or doubt, I suppose.
I'm fairly certain that there are six subgroups. The trivial subgroup (just the identity), the improper subgroup (all of G), and subgroups of order 2,3,4, and 6.
I gathered this from the factors of 12. I went ahead and computed the gcd(12,s) where s runs from 1 to 12 to obtain the above orders. There were duplicates. For example x3=x9=order3.
The generators of the group are x1, x5, x7, x11. This is gained from the coprimes from 1 to 12 with 12. All the generators have order 12
I guess my question is when subgroups of duplicate order are found, do we just treat them as the same subgroup. They are the same subgroup, right? So we aren't concerned with which element of G is necessarily involved, but rather just the subgroup that is produced by the given order?
Comment: Yes, that's right.  Two subgroups with exactly the same elements are in fact the same subgroup.
Answer: Two subgroups are equal if and only if they have the exact same set of elements. Just having the same order is not enough! It happens to be true that two subgroups of $C_{12}$ are equal if and only if they have the same order, but that will not be the case in general. For example, $C_2 \times C_2$ has three distinct subgroups of order $2$ (can you find them?)
To answer your question: yes, your classification of the subgroups of $C_{12}$ is correct.


How can I prove this statement about isomorphism and inner product?

Question: I have to prove the following:
"Let T be an isomorphism of a vector space $V$. Prove that if $\langle u, v \rangle$ is an inner product of $V$, then the same happens with $P_{T} : V \times V \rightarrow \mathbb{R}$ defined by $P_{T} = \langle T(u), T(v) \rangle$."
I thought that using $T^{-1}(T(u)) = u$ could get me somewhere, but I don't know how to use it.
Comment: Asserting that $P_T$ is an inner product means that there is a sequence of properties that you have to check. With which ones of these properties are you having a problem?
Answer: Clearly $P_T$ is conjugate symmetric because $\langle \cdot,\cdot \rangle$ is conjugate symmetric. Also $\langle Tu,Tu \rangle=0\iff Tu=0\iff u=0$, because $T$ is an isomorphism. Note that $\langle Tcu,Tv \rangle=\langle cTu,Tv \rangle=c\langle Tu,Tv \rangle$ for every scalar $c$. Can you verify other properties?
Answer: If $T$ is an isomorphism of $\mathcal{V}$, then $T(\vec{u}) = A\vec{u}$ for some invertible matrix $A$. To check if $T(u) \cdot T(v)$ is a valid inner product, we must check three conditions: positive definiteness, symmetry, and linearity. We begin by noting that $T(\vec{u}) \cdot T(\vec{v}) = (A\vec{u}) \cdot (A\vec{v})$.

Positive Definite: $T(\vec{u}) \cdot T(\vec{u}) \geq 0$, with equality if and only if $\vec{u} = \vec{0}$. Because $T(\vec{u}) \cdot T(\vec{v}) = (A\vec{u}) \cdot (A\vec{u}) = \vec{v} \cdot\vec{v}$ for some $\vec{v} \in \mathbb{R}^n$, and the original inner product was positive definite, we have $T(\vec{u}) \cdot T(\vec{v}) \geq 0$. To prove equality only occurs when $\vec{u} = \vec{0}$, we simply note that as $A$ is invertible, the only solution for which $A\vec{u} = \vec{0}$ is $\vec{u} = \vec{0}$. Again, as the original inner product was positive definite, we know that $\vec{v} \cdot \vec{v} = \vec{0} \iff \vec{v} = \vec{0}$.
Linearity: $T(\vec{u}) \cdot T(\vec{w} + \vec{v}) = T(\vec{u}) \cdot T(\vec{w}) + T(\vec{u}) \cdot T(\vec{v})$. This can be rewritten as the condition $(A\vec{u}) \cdot (A(\vec{w} + \vec{v})) = (A\vec{u}) \cdot (A\vec{w} + A\vec{v})$, and applying the linearity of the original inner product, we have our result. Using similar logic, we can also verify that $T(k\vec{u}) \cdot T(\vec{v}) = k (T(\vec{u}) \cdot T(\vec{v}))$.
Symmetry: I'll assume your vector field is over the reals, although this is easy to verify for any other vector field with the concept of a conjugate. We require $T(\vec{u}) \cdot T(\vec{v}) = T(\vec{v}) \cdot T(\vec{u}) = \vec{u} \cdot \vec{v}$, which is true because the original inner product was symmetric.


How do I see if it's improving my response time?

Question: I installed memcached for a Drupal 6 site. The status report shows it's properly installed.
How do I check if it's working as expected, and speeding up my site?
Answer: You can check the status at /admin/reports/memcache.
Comment: Ok I checked the report page you mention above... it has a lot of statistics.. namely: Gets, Transferred, Per-connection average etc. What's the most important variable to focus on? Thanks again!
Answer: Use webpagetest or one of its brethren to see how long it takes for the backed to deliver the HTML. You'll have to compare with and without memcache, warm vs cold cache. There are better analyses you can do, like new relic and blackfire, either requires a web server agent running.


How to decode/understand the math behind ACF and PACF?

Question: For the past month I have been trying to understand the math behind the autocorrelation function and partial autocorrelation function for time-series project I have been working on. However, I am only able to find loads of articles which answer questions like How you can generate ACF & PACF plot in Python or in R, How to understand ACF and PACF plot? or How to obtain p and q values from ACF or PACF plot? Nowhere I am able to find something which tells me the exact math behind them!
I am looking for something that derives this comprehensively enough, in hopes of trying to replicate derivation myself(am a computer science graduate). Can anyone help me out with the same? Any resource would do! Or maybe list down all the steps so that I can try researching in pieces.
Comment: You will find all the math in the Brockwell & Davis book "Introduction to Time Series and Forecasting"
Comment: This paper on the [characterization of the pacf](https://projecteuclid.org/download/pdf_1/euclid.aos/1176342881) might be of some help to you.
Comment: Thank you @Stochastic for the resource. Will definitely check this out.
Answer: The lectures provided here, based on the book Time Series Analysis are comprehensive. They might require a bit of background in control theory though.
Comment: Thank you @Akylas, will check the resource out! The lectures seem to be comprehensive. Will try and add an answer here, if I am able to churn up any of the derivations!


Error: The `style` prop expects a mapping from style properties to values, not a string

Question: I am getting error while creating a functional component which return a svg. what is going on here?
here is the code :
import React from 'react';

const TwitterIcon = () => {
  return (
    <svg viewBox="328 355 335 276" xmlns="http://www.w3.org/2000/svg">
    <path d="M 630, 425A 195, 195 0 0 1 331, 600A 142, 142 0 0 0 428, 570A  70,  70 0 0 1 370, 523 A  70,  70 0 0 0 401, 521A  70,  70 0 0 1 344, 455 A  70,  70 0 0 0 372, 460A  70,  70 0 0 1 354, 370A 195, 195 0 0 0 495, 442A  67,  67 0 0 1 611, 380 A 117, 117 0 0 0 654, 363A  65,  65 0 0 1 623, 401A 117, 117 0 0 0 662, 390A  65,  65 0 0 1 630, 425Z"
      style= {styles.fill}/>
  </svg>
  );
}

    const styles = {
  fill: "fill: skyblue"
}

export default TwitterIcon;

Basically I want to use svg as a component .
If this is not solvable please let me know alternate way of using svg in react . I am Newbie
Comment: @ sriram can you check this is what you expecting and what color you want to fill let me know ! https://codesandbox.io/s/59531561-so-w61t7
Comment: its working can you update the answer
Comment: so I can accept it
Comment: added the answer you can accept it and upvote if it helped you, thanks sriram :)
Comment: ok one more how to reduce the size of the icon its too big
Comment: you can add width and height ,i have updated the codesandbox you can check it https://codesandbox.io/s/59531561-so-w61t7, let me know if it worked for you
Comment: yeah it works can i add that as css in js styles property ?
Comment: yes and you can use as style.width and style.height
Comment: please edit it in codesandbox I am newbie to coding
Comment: updated the answer with all required in comments :) happy coding :)
Answer: You need to add the fill property in the svg element as shown below,
import React from "react";

const TwitterIcon = () => {
  const { fill, width, height } = styles;
  return (
    <svg
      viewBox="328 355 335 276"
      height={height}
      width={width}
      xmlns="http://www.w3.org/2000/svg"
      fill={fill}
    >
      <path d="M 630, 425A 195, 195 0 0 1 331, 600A 142, 142 0 0 0 428, 570A  70,  70 0 0 1 370, 523 A  70,  70 0 0 0 401, 521A  70,  70 0 0 1 344, 455 A  70,  70 0 0 0 372, 460A  70,  70 0 0 1 354, 370A 195, 195 0 0 0 495, 442A  67,  67 0 0 1 611, 380 A 117, 117 0 0 0 654, 363A  65,  65 0 0 1 623, 401A 117, 117 0 0 0 662, 390A  65,  65 0 0 1 630, 425Z" />
    </svg>
  );
};

const styles = {
  fill: "grey",
  width: 210,
  height: 500
};
export default TwitterIcon;

Working codesandbox
Answer: What's style="#3BA9EE" is supposed to do? It's not the way you specify the styles. See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style
Do something like <path ... style={{stroke-width: "2"}} />
Comment: problem still exists Im using css in js
Comment: @sriramhegde I've edited my answer, see how it's done
Answer: Style has to declare properties to which you assign values, I'm guessing you want to do something like style="stroke: #3BA9EE".
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style
Comment: yes I canged the code I am still getting the same error
Comment: What you've done will output `style="red"`, you need it to output `style="fill: red"`


How to control Loading panel using master page and without using AJAX

Question: I have an asp.net project and I want to show the progress image (GIF) without using AJAX and using simple java-script DIV magic.
All I want to do is to put one div (which show animation clock while page loading in progress) in master page (asp.net master page so I need not to repeat the code on every content pages) and show it when page load is in progress.
I hope your understand what I want to do.
Thanks,
Comment: To clarify: That one div contains just some generic "loading, please wait..." string, or like you said, a spinning clock GIF? Also, you mention "master" page - do you mean that there are "clone" pages? As in...clone windows?
Comment: I have updated question to justify your clarifications.
Comment: something like this but not this one as this is somewhat not complete one.....http://wiki.asp.net/page.aspx/1633/full-screen-loading-panel/
Answer: You can achieve like this

Comment: you put this code in masterpage and on body **onload** call function **init()** The div with id **loading** is area where u put gif loading image.just below that u will find function which control visiblity of image with div.
Answer: make 2 sections in your document's body

// Code for gif image
</div

// Whole page content

And after that include this javascript. Not in header

If you know jQuery you can do similarly on $(document).ready() event


Limitations on App images

Question: Are there limitations to which image types you can use in your app?
When I try uploading an apk to the play store using either only svg or webpimages I get the following error:

Upload failed
  You need to check the icon inside your APK because it is not valid.

Ofc I decompiled and checked that the icons actually were there.
I know jpg / png is the way to go.
But. Since Api 19 there is support on webp (which is...poorly documented and I could not find whether it was officially supported on all devices.)
Also, since Api 21 there is official svg support. This one is documented.
So I made 3 flavors of my app (it's a small flashlight widget consisting of 2 images, Source Code)

png default
webp 19+ (smaller than png)
svg 21+ (even smaller ;))

Now while installing works fine and the app is running, I can only upload the png version, getting the error mentioned above on my other flavors.
I did not find any constraints on which image formats you were to use, besides some notions that you should use png / jpg.
Since android gradle plugin 1.3 supports svg to png conversion at compile time, making a flavor for 21+ with nothing but svgs seems tempting.
What are the limitations?
Comment: Did you find answer to this question?
Comment: @NinjaCoder Yes. It seems like you have to include a png. I added an answer below.
Answer: I contacted the Google Play Developer Support, asking whether the launcher / app icon needs to be of the png file format.
Their answer was the following:

[...] I can confirm you are correct that the launcher icon does need to use a png and not a svg. For more information please see the following:
  https://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html

So it seems like you will always have to at least include one png file (the app icon) in your apk.

Limitations on App images


Flutter_riverpod giving me problems while installing

Question: I am trying to install flutter_riverpod but it gives me these error messages by following the normal approaches on installing packages. That is from pub.dev
I added flutter_riverpod: ^1.0.4 under my dependencies but gives me an error that says
Because riverpod depends on flutter_riverpod ^1.0.4 which depends on riverpod 1.0.3, riverpod 1.0.3 is required.
So, because riverpod is 1.0.0+1, version solving failed.
pub get failed (1; So, because riverpod is 1.0.0+1, version solving failed.)
exit code 1

Below is my pubspec.yaml file
name: riverpod
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.1 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  flutter_riverpod: ^1.0.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

This is the results of running flutter doctor too
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.2, on Ubuntu 22.04.1 LTS 5.15.0-47-generic, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 2021.2)
[✓] VS Code
[✓] Connected device (3 available)
[✓] HTTP Host Availability

• No issues found!

Comment: Can you share your pubspec.yaml file?
Comment: Remove the restriction on the flutter_riverpod package and try again.
Answer: Your specific problem is because your project is named riverpod. It conflicts with the riverpod dependencies of hooks_riverpod and flutter_riverpod. Rename your project and it will work.
Source: Version solving failing on running "flutter pub get" for Riverpod with the new Flutter 2.2.2 verison
Comment: `Because riverpod depends on flutter_riverpod ^2.0.0-dev.9 which depends on riverpod 2.0.0-dev.9, riverpod 2.0.0-dev.9 is required.`. This is the error after your suggestion
Comment: This is after using dev.7
`because riverpod depends on flutter_riverpod ^2.0.0-dev.7 and riverpod is 1.0.0+1, version solving failed`
Comment: I am also using `flutter_riverpod: ^2.0.0-dev.7` but I never get this error.
Comment: Can it be as a result of using the flutter versin 3.3.2 ?
Comment: I am using Flutter version 3.0.0.
Comment: For some reason, using the version `flutter_riverpod: ^1.0.0-dev.10` works but when I declare a global provider variable like `final helloWorldProvider = Provider((_) => 'Hello world');`. There is no recognition of the Provider class even after importing riverpod
Comment: @Samuel, did my edited answer help you?


A Hölder continuous function whose Fourier coefficients do not decay very fast

Question: At Stein's book of Fourier analysis (Chapter 3, page 91, exercise 15) I was trying to solve the following problem I have to prove that the result
$$\widehat{f}(n)=O\left(\frac{1}{|n|^{\alpha}}\right)$$
Cannot be improved by showing that the function:
$$f(x)=\sum_{k=0}^{\infty}2^ {−kα} e^{i2^{k}x}$$
with $0<α<1$, satisfies
$$|f (x + h) − f (x)| ≤ C|h|^{α}$$
and $\widehat{f}(N ) = 1/N^{α}$ whenever $N = 2^k$
But I don't know what I am supposed to do here?, there is a hint but it doesn't clarify the question, Can someone help me with this question please?
Comment: Is $\alpha$ the Holder continuity exponent in the theorem? If so, then you must check is that the function is $\alpha$ Holder continuous. Then you're done, since the given bound on the Fourier coefficients is easily seen to be tight for this function.
Comment: That's a rigorous argument of the type that I was describing. It looks correct. By the way, this is closely related to an interesting topic I studied last semester called the Littlewood-Paley decomposition. I don't know whether this is covered in Stein's book, but it is a nice technique.
Comment: Yes, in the result I have mentioned  the $\alpha$ is the one of the Holder condition  :) but Holder continous is...?
Comment: So you need to show that $\left | \sum_{k=0}^\infty 2^{-k \alpha} \left ( e^{i 2^k x} - e^{i 2^k y} \right ) \right | \leq C |x-y|^\alpha$. To do this I think you will need to perform some balancing of terms: when $k$ is small, the difference in the exponentials is small and the Fourier coefficient is bounded, while when $k$ is large, the reverse occurs.
Comment: Thanks a lot :), is this answer right? https://zr9558.files.wordpress.com/2014/08/fourier-analysis-stein-shararchi-solutions.pdf page 32
Comment: Wow I think in a very close future Im going to start with that hopefully :), so that is the idea you were decribing right?
Comment: The one in the webpage :)
Comment: Yes, that's the idea I had in mind (although I didn't work out how exactly to do the splitting).
Comment: Well so we are done , and I hope in a future point we can discuss the new topic Littlewood-Paley decomposition
Answer: This is a Weierstrass-type function. One can prove the continuity by splitting the sum into low frequencies and high frequencies; the cutoff will depend on the scale $h$. Namely, $k_0 = -\log_2 h$.
High frequencies. If $k\ge k_0$, then $2^{-k}\le h$, the terms are small enough so that we can simply bound them by the triangle inequality: they contribute $O(h^\alpha)$.
Low frequencies. If $k<k_0$, then  the derivative of the $k$th term, namely $i 2^ {k(1-\alpha)} e^{i2^{k}x}$, is bounded by $2^ {k(1-\alpha)} $. Summing this over $k\le k_0$ shows the derivative of the sum of all low-frequency terms is $O(2^{k_0(1-\alpha)})$ which is $O(h^{\alpha-1})$. Hence, the difference of values of this sum on the scale of $h$ is $O(h^\alpha)$.
Comment: (It is complicated to see who the human being might be behind this user-identity... I would be interested to know who understood this question, etc. if you would care to divulge...)
Comment: Well I think this is interesting but how this improves my question ? Well I think is a higher level for me :) can someone clarify?


Hide/Show Columns in an HTML Table (with multiple column in the header)

Question: Can anyone help please, I am trying to hide/show my html table columns, my table has three rows in the header and need to hide/show the columns of the second row with the contained small rows, I used an example found here in Stackoverflow but still can't succeed to do the job, my code is as following:

        $(function() {
  // on init
  $(".table-hideable .hide-col").each(HideColumnIndex);

  // on click
  $('.hide-column').click(HideColumnIndex)

  function HideColumnIndex() {
    var $el = $(this);
    var $cell = $el.closest('th,td')
    var $table = $cell.closest('table')

    var colIndex = $cell[0].cellIndex + 1;

    // find and hide col index
    $table.find("tbody tr, thead tr")
      .children(":nth-child(" + colIndex + ")")
      .addClass('hide-col');

    // show restore footer
    $table.find(".footer-restore-columns").show()
  }

  // restore columns footer
  $(".restore-columns").click(function(e) {
    var $table = $(this).closest('table')
    $table.find(".footer-restore-columns").hide()
    $table.find("th, td")
      .removeClass('hide-col');

  })

  $('[data-toggle="tooltip"]').tooltip({
    trigger: 'hover'
  })

})
        body {
  padding: 15px;
}

.table-hideable td,
.table-hideable th {
  width: auto;
  transition: width .5s, margin .5s;
}

.btn-condensed.btn-condensed {
  padding: 0 5px;
  box-shadow: none;
}

/* use class to have a little animation */
.hide-col {
  width: 0px !important;
  height: 0px !important;
  display: block !important;
  overflow: hidden !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
}
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/paper/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

        TOP

       <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">

        </button>

        A
       <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">

        </button>

        B

         AA

         AB

         BB

        BC

      Home
      Index
      ActionResult
      Authorize

      Client
      Index
      ActionResult
      Authorize

      Client
      Edit
      ActionResult
      Authorize

      Some columns hidden - click to show all

Many thanks
Answer: Try like this:

$(function() {
  // on click
  $('.hide-column').click(HideColumns)

  // on init
  $('.hide-column').eq(0).trigger( "click" );

  function HideColumns() {
    var $el = $(this);
    var $cell = $el.closest('th,td')
    var $table = $cell.closest('table')

    var colIndex = 0;
    var colSpan = 0;

    $cell.parent().children().each(function(index) {
      if ($(this).is($cell)) {
        colSpan = parseInt($cell.attr("colspan") || 1);
        return false;
      } else {
        colIndex += parseInt($(this).attr("colspan") || 1);
      };
    });

    // find and hide col index
    for (var i = colIndex; i < (colIndex + colSpan); i++) {
      $table.find("tbody tr, thead :nth-child(3)")
        .children(":nth-child(" + (i + 1) + ")")
        .addClass('hide-col');
    };

    //always show first header
    $table.find("thead :nth-child(1)").children().removeClass('hide-col');

    //hide clicked cell
    $cell.addClass('hide-col');

    // show restore footer
    $table.find(".footer-restore-columns").show()
  }

  // restore columns footer
  $(".restore-columns").click(function(e) {
    var $table = $(this).closest('table')
    $table.find(".footer-restore-columns").hide()
    $table.find("th, td")
      .removeClass('hide-col');

  })

  $('[data-toggle="tooltip"]').tooltip({
    trigger: 'hover'
  })

})
body {
  padding: 15px;
}

.table-hideable td,
.table-hideable th {
  width: auto;
  transition: width .5s, margin .5s;
}

.btn-condensed.btn-condensed {
  padding: 0 5px;
  box-shadow: none;
}

/* use class to have a little animation */

.hide-col {
  width: 0px !important;
  height: 0px !important;
  display: block !important;
  overflow: hidden !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
}
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/paper/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

          TOP

         <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column" data>

        </button> A
         <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">

        </button> B

          AA

          AB

          BB

          BC

        Home
        Index
        ActionResult
        Authorize

        Client
        Index
        ActionResult
        Authorize

        Client
        Edit
        ActionResult
        Authorize

        Some columns hidden - click to show all

As th elements with colspan are being used, a different approach is needed. Instead of only considering the current column index, the above solution finds the range of indexes of td cells within tbody according to the th where the button was clicked ($cell).
To hide that span of columns, it first loops through the 2nd row of the table, adding each colspan to colIndex until it gets to $cell. The td indexes to hide on each row are then from colIndex to colIndex + the colspan of $cell (1-based in jQuery).
Comment: [Try like this](https://stackoverflow.com/a/65302846/2687204).
Comment: Hi sbgib, still have an issue while implementing this solution, when i start hiding the columns from the right it works fine, but when i start from the left, i can see the issue; some cells get hidden even if not needed to be, can i send to you the code please ?
Comment: How has it been changed from the working demo? If you can upload it somewhere I can take a quick look.
Comment: sure, this is the link to it:  https://stackoverflow.com/questions/65288649/hide-and-show-html-table-columns


ReactJS: TypeError: this.props is not a function

Question: Here is App.JS
import React, { Component } from 'react';
import Header from './Header';
import Todo from './Todo';
import Form from './Form';

class App extends Component {
  state= {
    list: [
      {
        title: "Take out trash",
        id: 1
      },
      {
        title: "Take dog for walk",
        id: 2
      },
      {
        title: "Doctor appointment",
        id: 3
      }
    ]
  };

  prevItemId=3;

  handleAddPlayer=(name)=> {
    this.setState( prevState=> {
      return {
        players: [
          ...prevState.players,
          {
            name,
            score: 0,
            id: this.prevPlayerId+=1
          }
        ]
      }
    });
  }

  render() {
    return (

        <Todo
          number={this.state.list.length}
          list={this.state.list}
        />
        <Form addItem={this.handleAddItem}/>

    );
  }
}

export default App

Here is the form component (Form.js)
import React, {Component} from 'react'

class Form extends Component {

  state= {
    value: ''
  }

  handleChange=(e)=> {
    this.setState({value: e.target.value})
  }

  handleSubmit= (e)=> {
    e.preventDefault();
    this.props.addItem(this.state.value);
    this.setState({value: ''})
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          List Item:
          <input type="text" name="name" value= {this.state.value} onChange={this.handleChange}/>

        <input type="submit" value="Submit" />
      </form>
    )
  }

}

export default Form

In Forms.JS I keep getting an error that this.props.addItem is not a function. I understand there are many forums on this topic, but I can't figure out what's wrong. I'm trying to add a liste item to the App state when on a submit event, with the handleSubmit function
Comment: `` but the function is named `handleAddPlayer`.
Answer: Change the function name in App.js :
  <Form addItem={this.handleAddPlayer}/>


Which step am I messing up with this integration by parts problem?

Question: I'm having issues with a dozen or so integration problems, but I'll start with this one. I'll try and post one at a time until it is solved and then move onto the next one.
$$\int_\frac{1}{12}^\frac{1}{4}  \frac{1}{\sqrt{x} * (4x + 1)}$$
Here are the steps I take.

Step 1. Set $$ u = \sqrt{x} $$  which means  $$ u^2 = x $$
Step 2. $$2u du = dx$$
Step 3. $$ \int_\frac{1}{12}^\frac{1}{4} \frac{2u du}{u(4x+1)} $$
Step 4. Cancel out the u which give $$ \int_\frac{1}{12}^\frac{1}{4} \frac{2 du}{(4x+1)} $$

I stopped there because to me it doesn't look like I'm going in the right direction. Why would I cancel out the u if the whole point of it is to use it for substitution? Should it be
$$ \int_\frac{1}{12}^\frac{1}{4} \frac{u du}{(4x+1)} $$
rather than cancelling out the 2?
I would appreciate it someone could tell me what I should be doing.
Comment: Are you allowed to use $\int \frac{1}{1+u^2}\ du=\tan^{-1}(u)+C$?
Comment: Why do you want to do integration by parts? Just a thought, substitution method (take out the radical) might work too. That 4x needs to be replaced by variable u as well
Comment: @Rebecca I'm allowed to use any method necessary, I just thought the proper way would be IBP. Judging by the replies, I am incorrect.
Comment: You've done most of the work already then; amWhy's answer explains how to finish it off, then just use the above integral.
Comment: @Rebecca Thank you for pointing that out, I appreciate it.
Answer: There is no real need to perform integration by parts, here. Rather, we proceed with substitution. You've done fine, up through step $(4)$, almost. Given where you got to, at step $(4)$:
$$\int_\frac{1}{12}^\frac{1}{4} \frac{2 du}{(4x+1)}$$
We first need to replace $4x + 1$ in the denominator by it's equivalent, with $4u^2 + 1 = (2u)^2 + 1$.
We need also to change the bounds of integration. $$\text{When }\,x = \dfrac 14, \;u = \sqrt{\dfrac 14} = \dfrac 12.\quad\text{When }\;x = \frac 1{12},\; u = \sqrt{\frac{1}{12}} = \frac{1}{2\sqrt 3}$$
$$\int_{\large \frac{1}{2\sqrt 3}}^{\large \frac 12} \frac{2\, du}{(2u)^2 + 1} = \tan^{-1}\left(2u\right)\Huge|_{\large \frac{1}{2\sqrt 3}}^{\large \frac 12}$$
Comment: I'm slightly upset, I would have never realized that $ \int \frac{2du}{(2u)^2 + 1} $ is integrated to arctan(2u). Thank you for the explanation, I need to review my inverse trig functions a bit so I don't get stumped by them.
Comment: You're welcome! You might want to begin your review [here](http://en.wikipedia.org/wiki/Trig_substitution#Integrals_containing_a2_.2B_x2)
Comment: Thank you! I'll definitely read into it before I post my next question. (some of my questions deal with trig sub)
Comment: @amWhy: Needs a UV to go with the check +1


Is there a way to make a smoothed kernel density graph when the underlying pdf is known imperfectly?

Question: First, let me describe my problem.
I have data on the pdf of school attendance by age group. However, ages 3-5 are bundled together in the source. I divided the 3-5 age group by 3 to get the average percentage for each year. However, I now want to estimate what the smoothed shape of the probability density function would be.
Visually, it looks like this:

Now, it makes sense to think, given the rest of the distribution, that more kids are attending at age 5 than at age 3. To estimate this smoothed distribution, I was planning on using seaborn and matplotlib to do kernel density estimation with a higher bandwidth.
These all require a 1-dimensional array of data, whereas my data is 2-dimensional:
age = [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
density = [5.6, 9.8, 9.8, 9.8, 13.6, 12.1, 9.6, 7.6, 6.4, 5.4, 4.6, 2.8, 1.4, 1]

So is there a way to either (a) do kde with 2-d data or (b) convert 2-d data into 1-d density data?
Answer: For 1D kde you can do:
pd.Series(density).plot.kde(ind=age)

which gives:


Javascript: Função não está retornando o valor correto

Question: O que pode estar de errado nessa função? Onde está o alert, está vindo o resultado correto, mas está retornando 0.
function AprovaCotacao(numForn) {
    var forn_aprovado = $("#cot_fornecedor" + numForn).val();
    var id = $("#cot_id").val();
    var url = host + "/cotacoes/Aprovar";
    var result = 0;

    $.ajax({
        url: url
        , data: { id: id, idFornecedor: forn_aprovado, numAprovado: numForn }
        , type: "GET"
        , dataType: "json"
        , contentType: "application/json; charset=utf-8"
        , success: function (data) {
            if (data.mensagem == '') {
                result = data.pedido;
                alert(result);
            }
            else {
                result = -1;
                alert(data.mensagem);
            }
        }
    });
    return result;
}

Resultado do json: {"mensagem":"","pedido":46}.
Comment: Luciano a melhor forma de resolver isto é entender o que é e como funciona assincrono e que querer forçar sincrono em JavaScript é desnecessário e provavelmente é porque você ainda não entende muito bem o comportamento de callback e assincrono em JS, recomendo os links: **1.** https://pt.stackoverflow.com/q/45706/3635 / **2.** https://pt.stackoverflow.com/q/16950/3635 **3.** https://pt.stackoverflow.com/q/51268/3635
Comment: @VictorStafusa tem mais umas 3 assim, até com respostas melhores, mas esta muito complicado achar, ainda mais porque se me recordo os titulos são coisas como: "problema com ajax", "erro no ajax" e "ajax não funciona", ai fica impossivel encontrar :/
Comment: Tem dois `alert` aí, pode explicar melhor?
Comment: o alert que mostra a variável result alert(result);
está retornando o código correto: 46, porém quando chamo a função fica sempre 0
Comment: Eu tenho uma noção, mas vou dar uma aprofundada no assunto. Obrigado!
Comment: @GuilhermeNascimento Tinha certeza que era duplicata, mas não tinha encontrado a pergunta anterior.
Answer: A chamada $.ajax(...) é assíncrona. Ou seja, ela não vai fazer a chamada imediatamente, e sim postar uma requisição para que seja feita. A execução do Javascript vai então encontrar o return result; e retornar zero. Só depois disso é que a chamada AJAX vai acontecer, mas aí, ao definir o valor da variável result, já será tarde demais.
Comment: Entendi, mas eu li que é contra indicado deixar a chamada síncrona, desta forma, qual seria a melhor forma de resolver esse problema?
Comment: @Luciano Isso depende de qual função está chamando a sua `AprovaCotacao` e o que ela está fazendo com o resultado. Sugiro editar a pergunta para incluir isso.


How to show data from database/cms in react?

Question: I have a react code as shown below in which to pull data from CMS/Database.
React code:

   { versionList.map((element,i)=>{
   console.log(element); /* Line Z */
   return(
   <ListItem>

title: {element.title}

description: {element.description}

air date: {convertToTimeZone({date: element.air_date_dt},selectedTimezone)}

   </ListItem>
   ) }) }

Line Z prints the following:
air_date_dt: "2021-03-20T11:00:00.000Z"
air_duration_i: "1"
description: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
description_en_t: "Aliquam tincidunt mauris eu risus."
description_fr_t: "Vestibulum auctor dapibus neque."
image: "/versions/en.png"
image_en_s: "/versions/en.png"
image_fr_s: "versions/fr.png"
title: "Hello World"
title_en_t: "Hello World"
title_fr_t: "Bonjour le monde"

Problem Statement: In my code above, the div inside the ListItem doesn't print anything although I am able to show everything at Line Z.
Comment: @pmiranda I am wondering if you can explain me in an answer. I am not a very strong react developer.
Comment: Try with: element?.title, element?.description, etc, and add a key to <ListItem
Answer: I think you have a warning because the ListItem component does not have a key property.
Try to move the key from the div to the ListItem component.
Another hint should be to check CSS. Make sure you do not have hidden blocks.
Answer: At Line Z you are doing a console log which is why you can see the data. The div and the rest of your code in that div is being returned. Depending on where is it is going and what is happening with it could be your problem. Could you please include the code where the return is send the div?
Answer: Add a key to the <ListItem> and use the ? in case the element object be undefined in the first render:
Try this code:

    { versionList.map((element,i)=>{
    console.log(element); /* Line Z */
    return(
    <ListItem key={`list-item-${i}`}>
      <div key={`div-key-${i}`}>

title: {element?.title}

description: {element?.description}

air date: {convertToTimeZone({date: element?.air_date_dt},selectedTimezone)}

    </ListItem>
    ) }) }


Efeito número aumentando/diminuindo

Question: Procurei no SOpt e não encontrei o que desejava
Suponhamos que eu tenha um botão e, ao efetuar um clique, ele altere o valor de alguma div ou input. O valor inicial seja 1, e ao clicar, mude para 10.
Gostaria que essa transição não fosse direta. Gostaria que os números fossem crescendo, do 1 ao 10 (Ex: 1,2,3,4,5,6,7,8,9 e, finalmente 10).
Pensei em fazer com setTnterval e um loop, mas não consegui pensar na solução em si.
Tenho preferência por jQuery.
Deixarei um trecho para ajudar. Desde já, obrigado pela atenção.

$("#alterarValor").click(function(){
$("#numero").text("10");
});
$("#voltarValor").click(function(){
$("#numero").text("1");
});

1

<input type="button" id="alterarValor" value="Alterar valor" />
<input type="button" id="voltarValor" value="Resetar" />
Answer: Tens de criar um loop com  setTimeout que vai mudando. Com um loop começas os setTimout todos ao mesmo tempo mas usando o i para multiplicar o tempo de espera o efeito é o que procuras.
Exemplo com 5 segundos de transição:

$("#alterarValor").click(function() {
  var numero = document.getElementById('numero');
  var min = 1;
  var max = 20;
  var duração = 5000; // 5 segundos

  for (var i = min; i <= max; i++) {
    setTimeout(function(nr) {
      numero.innerHTML = nr;
    }, i * 5000 / max, i);
  }
});

$("#voltarValor").click(function() {
  $("#numero").text("1");
});

1

<input type="button" id="alterarValor" value="Alterar valor" />
<input type="button" id="voltarValor" value="Resetar" />
Comment: Perfeito. Exatamente o que eu desejava. Obrigado!
Answer: Sei que a pergunta já foi respondida, mas, de qualquer forma, segue exemplo de outra maneira de fazer isso com os números em ordem crescente e decrescente para aumentar a base de conhecimento:

jQuery(function($){
  $("#alterarValorCrescente").click(function(){
    //Valor inicial
    var count = 1;
    countdown = setInterval(function(){
      $('#contagem').html(count);
      //Valor final
      if (count >= 10){
        //Ao chegar no valor final (10) interrompe a contagem
        clearInterval(countdown);
      }
      count++;
      //Transição a cada meio segundo
    }, 500);
  });
  $("#alterarValorDecrescente").click(function(){
    //Valor inicial
    var count = 10;
    countdown = setInterval(function(){
      $('#contagem').html(count);
      //Valor final
      if (count == 1){
        //Ao chegar no valor final (1) interrompe a contagem
        clearInterval(countdown);
      }
      count--;
      //Transição a cada meio segundo
    }, 500);
  });
  $("#voltarValor").click(function(){
    $("#contagem").text("1");
  });
});

1

<button id="alterarValorCrescente">Alterar valor +</button>
<button id="alterarValorDecrescente">Alterar valor -</button>
<button id="voltarValor">Resetar</button>
Comment: Opa! Muito obrigado amigo! Estarei analisando!
Comment: Desculpe só responder agora. Mas eu testei seu script e achei ele ainda mais interessante que o outro. Muito obrigado!
Comment: @Leandro como fazer para que isso ocorra no load da pagina, sem precisar clicar no botão "alterar valor"?

Efeito número aumentando/diminuindo


Adjusting Nutrient Intake for Energy Intake OR Body Weight OR Both?

Question: Introduction
I am analyzing a data set which I am grouping in protein intake quartiles. Before using the protein intake data (in grams), I want to adjust it to avoid potential confounding.
Problem
I have seen two main methods for adjusting the nutrient intake before entry in statistical analyses, adjusting for energy intake and adjusting for body weight.
The energy adjusted method I would use is the "nutrient residual model" described by Willet. The body weight adjusted method would simply be Nutrinent Intake / Body Weight.
What Have I Done
I have had the belief that the energy adjusted method would be the best solution, and the one I went with initially. But after a presentation at a seminar, I was suggested to group my data in by protein g/kg body weight.
Is there any guidance on which adjustment should be used in this case? And would using both adjustment be a wise choice?
Answer: So, not an expert in nutrition here, but this seems like an excellent problem to start with the good old linear regression. This is because instead of taking as heresay whether one model is better than another, we can test this directly. You could do this by:
Model 1:
protein intake = intercept + energy intake
Model 2:
protein intake = intercept + body weight
Model 3:
protein intake = intercept + energy intake + body weight + energy intake  * body weight
So this third model would test if energy intake and body weight are related in a multiplicative fashion. You could then directly compare Model 3 to Model 2 or Model 1 by doing an anova test. This will give you a p-value indicating whether adding that multiplicative term has done anything statistically significant. So to answer your questions, yes you can do both, but that may not be statistically significant, so do these regressions to see what comes out as most significant.
Comment: This approach is useful. But I am seeking an answer for which approach would be biologically sound. As in, would it make sense to adjust for energy intake when i've already adjusted for body weight, or vice versa.


How to make a type out of inherited custom classes c++

Question: I am trying to build my first game in c++ and I am attempting to make an Inventory system that will allow me to manage and arrange different Item data types within an Inventory container type. In the code below I only have the class declarations made up but I wanted to know how to make the "Item" class that I have made hold a data type of any of the different inherited items such as the Weapon, Apparel, and Aid categories. Would it be as simple as using a template parameter? If so then my question is how does something like a Constructor understand what to do in each instance of creating an item? The default Constructor may have to be something like a basic weapon that I decide to set up, correct? If anyone has any advice or links to provide that would be greatly appreciated.
Thanks!
ITEM.H:
#ifndef ITEM_H
#define ITEM_H

#include <iostream>

/*************************************************
* ITEM CLASS
* *This class is the type of data to be put into
*  the Inventory Container class.
**************************************************/
class Item
{
public:

private:

};

/*************************************************
* WEAPON CLASS
* *This class is a type of Item that classifies a
*  weapon item that can be in an Inventory.
**************************************************/
class Weapon : public Item
{
public:

private:

};

/*************************************************
* APPAREL CLASS
* *This class is a type of Item that classifies an
*  apparel item that can be in an Inventory.
**************************************************/
class Apparel : public Item
{
public:

private:

};

/*************************************************
* AID CLASS
* *This class is a type of Item that classifies an
*  Aid item that can be in an Inventory.
**************************************************/
class Aid : public Item
{
public:

private:

};

#endif //ITEM_H

EDIT:
Here is what I have as of now:
/*************************************************
* ITEM CLASS
* *This class is the type of data to be put into
*  the Inventory Container class.
**************************************************/
template <class T>
class Item
{
public:

private:
    T item_type;         //i.e. Weapon, Apparel, Aid, etc...

};

/*****************************************************************
* ITEM : WEAPON
* *Below is the code for all the different Weapon classes.
******************************************************************/

/*************************************************
* WEAPON CLASS
* *This class is a type of Item that classifies a
*  weapon item that can be in an Inventory.
**************************************************/
template <class T>
class Weapon : public Item
{
public:

private:
    T weapon_type;      //i.e. Melee, Ranged, etc...
};

/*************************************************
* MELEE CLASS
* *This class is a type of Item that classifies a
*  melee item that will be used as a weapon.
**************************************************/
template <class T>
class Melee : public Weapon
{
public:

private:

};

/*************************************************
* RANGED CLASS
* *This class is a type of Item that classifies a
*  ranged item that will be used as a weapon.
**************************************************/
template <class T>
class Ranged : public Weapon
{
public:

private:

};

ANOTHER EDIT:
Here is the newest code:
/*************************************************
* ITEM CLASS
* *This class is the type of data to be put into
*  the Inventory Container class.
**************************************************/
template <class T>
class Item
{
public:

protected:
    T item_type;         //i.e. Weapon, Apparel, Aid, etc...

};

/*****************************************************************
* ITEM : WEAPON
* *Below is the code for all the different Weapon classes.
******************************************************************/

//WEAPON CLASS
template <class T>
class Weapon : public Item
{
public:

protected:
    T weapon_type;      //i.e. Melee, Ranged, etc...
};

//MELEE CLASS
template <class T>
class Melee : public Weapon
{
public:

protected:
    T melee_type;      //i.e. Blade, Blunt, Fist, etc...

};

//BLADE CLASS
template <class T>
class Blade : public Melee
{
public:

protected:
    T blade_type;      //i.e. Dagger, Sword, etc...
};

//DAGGER CLASS
template <class T>
class Dagger : public Blade
{
public:
    //Default Constructor...the only Constructor
    Dagger() : damage(1), weight(0.5) { }

    //getters
    std::string getType() const { return "Dagger"; }

protected:
    int   damage;      //amount of damage it can inflict
    float weight;      //weight of the dagger
};

Comment: I'm not talking about for the Inventory class. I mean for the member variable in the Item class.
Comment: What are you trying to do?
Comment: I want to figure out how to set the member variable in `Item` so that it can be any of the categories like Weapon, apparel, etc. but I am not sure if a template will be the best for it. But I don't know of any other way to handle something like that either.
Comment: @songyuanyao Yes. That is what I am getting at.
Comment: Should the template's that I put have different letters as I go down the inheritance list? So like Item -> Weapon -> Melee -> Sword... Should each of them have a different template parameter?
Answer: One solution is to define your types as enums.
enum ITEM_TYPE { IT_WEAPON, IT_END };
enum WEAPON_TYPE { WT_MELEE, WT_RANGED, WT_END };

class Item {
public:
    Item(ITEM_TYPE type) : item_type(type) {}
protected:
    ITEM_TYPE item_type;
};

class Weapon : public Item {
public:
    Weapon(WEAPON_TYPE type) : Item(IT_WEAPON), weapon_type(type) {}
protected:
    WEAPON_TYPE weapon_type;
};

class MeleeWeapon : public Weapon {
public:
    MeleeWeapon() : Weapon(WT_MELEE) {}
};

class RangedWeapon : public Weapon {
public:
    RangedWeapon() : Weapon(WT_RANGED) {}
};

Comment: So would I want to make the member variables private or protected? Why?
Comment: `protected` members are only accessible by the `class` and any derived `class`es. `private` members are only accessible by the `class`. In this case, `item_type` can be accessed by `Item`, `Weapon`, `MeleeWeapon`, `RangedWeapon`. But if it was `private`, it can only be accessed by `Item`.
Answer: You can't and shouldn't need to store a type (type in the C++ language sense), use virtual functions to achieve what you want.
#include <iostream>
#include <memory>
#include <vector>

class Item
{
public:
     virtual const char* type() const = 0;
};

class Weapon : public Item
{
public:
      const char* type() const override { return "Weapon"; }
};

class Ranged : public Weapon
{
public:
    const char* type() const override { return "Ranged"; }
};

class Melee : public Weapon
{
public:
    const char* type() const override { return "Melee"; }
};

class Apparel : public Item
{
public:
    const char* type() const override { return "Apparel"; }
};

int main()
{
    std::vector<std::unique_ptr<Item>> items;

    items.emplace_back(new Apparel());
    items.emplace_back(new Ranged());
    items.emplace_back(new Melee());

    std::cout << "Inventory Types:\n";
    for (const auto& it: items)
        std::cout << it->type() << '\n';
}

See http://cpp.sh/6cjlt
Comment: I don't know if this would work because I want to get various variables and functions and types for each of the different items that can be made.


Null Pointer exception in ImageView

Question: I am trying to display an image from my phone using ImageView.
Here is my ImageActivity activity:
package com.example.apptest1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class ImageActivity extends Activity {

private static final int REQUEST_CODE = 0;
private Bitmap bitmap;
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image);
     ImageView imageView = (ImageView) findViewById(R.id.result);

}

public void pickImage(View View) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, REQUEST_CODE);
}

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        InputStream stream = null;
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
          try {
            // recyle unused bitmaps
            if (bitmap != null) {
              bitmap.recycle();
            }
            stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);

            imageView.setImageBitmap(bitmap);
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } finally {
            if (stream != null)
              try {
                stream.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
          }
      }

 }

And here is the activity_image.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}"
android:orientation="vertical">

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="pickImage"
    android:text="Button" >
</Button>

<ImageView
    android:id="@+id/result"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
</ImageView>

</LinearLayout>

But when I try to run the application,it displays the below logcat and stops abruptly
LogCat:
    05-28 23:11:48.226: E/AndroidRuntime(6115): FATAL EXCEPTION: main
05-28 23:11:48.226: E/AndroidRuntime(6115): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,  request=0, result=-1, data=Intent { dat=content://media/external/images/media/1242 flg=0x1 }} to activity   {com.example.apptest1/com.example.apptest1.ImageActivity}: java.lang.NullPointerException
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3525)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3568)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread.access$1100(ActivityThread.java:162)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.os.Handler.dispatchMessage(Handler.java:107)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.os.Looper.loop(Looper.java:194)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread.main(ActivityThread.java:5371)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at java.lang.reflect.Method.invokeNative(Native Method)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at java.lang.reflect.Method.invoke(Method.java:525)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run   (ZygoteInit.java:833)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at dalvik.system.NativeStart.main(Native Method)
05-28 23:11:48.226: E/AndroidRuntime(6115): Caused by: java.lang.NullPointerException
05-28 23:11:48.226: E/AndroidRuntime(6115):     at com.example.apptest1.ImageActivity.onActivityResult(ImageActivity.java:48)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.Activity.dispatchActivityResult(Activity.java:5311)
05-28 23:11:48.226: E/AndroidRuntime(6115):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3521)
05-28 23:11:48.226: E/AndroidRuntime(6115):     ... 11 more

I have debuged and checked that ImageView is null but not able to figure out why/how.Can someone please clear my doubt.Thanks in advance
Answer: Simple scope issue.
This line
ImageView imageView = (ImageView) findViewById(R.id.result);

needs to be
imageView = (ImageView) findViewById(R.id.result);

Why? Because the way you're doing it now means that you've declared a new imageView instead of using the one already declared previously. You've left that previously declared imageView untouched, and instead made a brand new one that's absolutely useless and dissapears after the onCreate() finishes. When you call imageView.setImageBitmap(bitmap);, you'll get an NPE because it tries to use the imageView declared in your class.
Answer: in your onCreate method you are creating a local variable by:-
ImageView imageView = (ImageView) findViewById(R.id.result);

That hides your global imageView member.
So, do below in onCreate:-
imageView = (ImageView) findViewById(R.id.result);

And the null pointer should go.

Null Pointer exception in ImageView


How can I integrate Google Documents List Data API with coldfusion page?

Question: Can someone please tell me the step that I should take to integrate google docs in .cfm page. It is a multi-user web application with single log-in , one username n password.
Thanks.
Answer: Try this free library at: http://cfgoogle.riaforge.org/ , read this post: http://www.coldfusionjedi.com/index.cfm/2007/12/8/Google-Docs-CFC
If you want to do it yourself without using the library above, you will need to learn how to consume RESTful services using the <cfhttp> tag, and construct and parse XML using <cfxml> and xmlParse().
This Yahoo guide introduces how to use CF to consume Yahoo's RESTful services: http://developer.yahoo.com/coldfusion/index.html


Show that for a set $A$, $|^A 2|$ = $|^{|A| }2|$.

Question: Question: Show that for a set $A$, $|^A 2|$ = $|^{|A| }2|$.
Comments: This is a part of a larger problem that I'm attempting to solve and it seems like the equality is true, but I'm not quite sure how to prove it. Idea: I need to find a bijection from $|^{|A| }2|$ to $|^A 2|$ and I can use that there is a bijection from $|A|$ to $A$, but I'm not sure how to proceed from here. Any input appreciated.
Comment: Could you explain the notation?
Comment: @TobiasKildetoft Yes, $^A B$ means the set of all functions from A to B.
Answer: A function $A\to 2$ is a function which, for each element of $A$, decides whether it goes in bin $1$ or in bin $2$. Or whether it is selected or dropped. Therefore it is a way to formalize any subset of $A$, and therefore an element of the power set of $A$. The set of all such functions is therefore the powerset of $A$, often denoted as $2^A$.
A function $A\to\lvert A\rvert$ maps a set to its cardinality. That cardinality is a cardinal number, and as such is considered to be a set of ordinal numbers. The cardinality of $A$ is the cardinality of $\lvert A\rvert$ itself.
For the cardinality of a powerset, it does not matter what the underlying set is. Only its cardinality is important. To illustrate this, consider the task of choosing items from a bag containing $10$ distinct items. There are $2^{10}$ ways to choose items, since each single item may be chosen or not chosen. It does not matter at all what items you are choosing from, be it apples, nuts or whatever.
To formalize things, you'll need three steps:
$$
\bigl\lvert A\to 2\bigr\rvert
\quad\leftrightarrow\quad
A\to 2
\quad\leftrightarrow\quad
\lvert A\rvert\to 2
\quad\leftrightarrow\quad
\bigl\lvert\lvert A\rvert\to 2\bigr\rvert
$$
The outermost bijections are simply due to the fact that a cardinal number has as many elements as the cardinality it signifies. The inner bijection does the same on the arguments of the domain of the function.
Answer: HINT: If $f\colon A\to|A|$ is a bijection, and $g\colon |A|\to 2$, consider $g\circ f$.
Comment: So is tbe $g\circ f$ the bijection then? We say that if $f(a)=0$, then $g\circ f = 0$ and if $f(a)=1$, then $g\circ f$=1.
Comment: @Sid, no, it's not a bijection. This is why I wrote "hint" at the beginning. What **is** $g\circ f$?
Comment: It is the composite function $g(f(a))$ for all $a$ in $A$.
Comment: Think, what are the relevant sets to your problem?
Comment: The set of all functions from the cardinality of A to a set with the cardinality of 2 and the set of all functions from A to a set with the cardinality of 2? Which we want to show that have the same cardinality? I am apparently a little lost.
Comment: Sid, and to which of them do $g$ and $g\circ f$ belong to?
Comment: I think the latter, since it is g(f(a)) but not f(g(a)). How does this help us find a proof (the right bijection)?
Comment: Good. So you started with $g$, which belongs to the former and by composing $f$ you ended with a function in the latter. Does that hint you of a possible bijection?
Comment: I appreciate your time in trying to make me understand this, I am thinking hard about it but I'm not sure. We have a function that belongs to the set which we want to find a bijection into, and we have another function that belongs to the set from which we want to find a bijection. We want it to be the other way, right? So would f(g(a)) suffice (instead of g(f(a))) or am I thinking about this incorrectly?
Comment: We have $g$ in $^{|A|}2$ and $g\circ f\in{}^A2$. What was the mechanism that took us from one set to the other?
Comment: The mechanism was a function composition. Do we need to do that again, so that we get g(g(f))? That we we go from $^{|A|}2$ to $^A 2$.
Comment: You need to define a function between sets of functions. This means that you need to define a function $F$ which takes $g\in{}^{|A|}2$ and returns some $F(g)\in{}^A2$.
Comment: I am trying, but how can we do so and be sure it is a bijection?
Comment: Well, if you choose $F$ right, then you should be able to show that it is a bijection. Begin by showing that $g\neq g'$ implies $F(g)\neq F(g')$, and then show that if $h\in{}^A2$ then there is some $g$ such that $F(g)=h$.
Comment: I don't know. I suppose we have to use $f$ since we know it is a bijection, but it uses elements the wrong set, we want to have it the other way around. Is there any way you can give me a stronger hint (I'm not good at this) or show me what bijection you had in mind?
Comment: @Sid: Okay, here's a stronger hint. I already gave you the definition $F$ using $f$.
Comment: I'm not sure if I understand you right ... $f$ is the bijection we were looking for? By the way, if you are tired of talking about this, I understand.
Comment: @Sid, no $f$ is a bijection from $A$ to $|A|$. We want to take a function in $^{|A|}2$ and end up with a function in $^A2$. What method, which appears in the comments does that and uses $f$?
Comment: I don't know, I give up.
Comment: Sleep on it. I am willing to help you, but I won't tell you the answer.


How do you get variable information in the editor for actionscript/flex

Question: I have a flex project with some actionscript files and when I mouse over variables in the class I would have expected information about that variable to popup like in other IDEs, but it doesn't seem to be working for me. I h ave the show quick doc on mouse over set to true and that works for Flash/Air runtime libraries and classes but nothing for my local stuff.
The quick doc stuff also doesn't seem to work for actionscript with a script tag in an mxml file unless I use the manual ctrl+q shortcut (just doesn't work on mouse hover)
Answer: This feature is active by default in Adobe Flash Builder and Flex for ActionScript 3.0 native classes and the components included in it like functions, variables, constant, etc.
To get this feature activated for the variable you create in your projects, you shall write comments over the lines of declaration of such variables you want their description to appear over.
This is the right format:
<code>/*
 * Your comment about the variable or the justDoIt function
 */
private function justDoIt():void
{
    return;
}
</code>
Now, whenever you call this function from any place in your code along he entire project, you'll be able to see the comment you wrote before it.


Adicionar elementos dentro do Array condicionalmente em JavaScript

Question: Quando tento mesclar dois objetos usando o operador spread condicionalmente, ele funciona perfeitamente com as duas condiçôes 'true' e 'false':

let condition1 = false;
let condition2 = true;
let obj1 = {
  key1: 'value1'
};
let obj2 = {
  key2: 'value2',
  ...(condition1 && obj1),
};
let obj3 = {
  key3: 'value3'
};
let obj4 = {
  key4: 'value4',
  ...(condition2 && obj3),
};

console.log(obj2); // {key2: 'value2'}
console.log(obj4); // {key4: "value4", key3: "value3"}

Quando tento usar a mesma lógica com Arrays, só funciona quando a condição é verdadeira 'true':

let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

console.log(arr2); // ['value2', 'value1']

Se a condição for falsa 'false', um erro será lançado:

let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

console.log(arr2); // Error

Por que o comportamento é diferente entre Array e Object?
Comment: Executando seu código não gerou o erro, tente executar: https://es6console.com/jvrzeln3/
Comment: @ThiagoKrempser, curiosamente o código não gera nenhum erro no [es6console.com](https://es6console.com/jvrzeln3/), mas isso não resolve a questão porque em outros  ele navegadores/compiladores gera.
Answer: então vamos a explicação:

Primeiro vamos entender as condicionais ternárias e lógicas:
Bom, a condicional que você tentou implementar no seu código é a lógica, ou seja, ela verifica se uma determinada condição é satisfeita e só então realiza uma ação ou atribui um valor. No caso do lógico && acontece como se fosse um if, porém sem o else e caso a condição não seja satisfeita ele retornará undefined, experimente:

// Lógico &&
// condição && se true
console.log('Lógico &&');

let cond = false;

const valueUndef = cond && 'teste'; // undefined/false

cond = true;

const valueDef = cond && 'teste'; // 'teste'

console.log(valueUndef);
console.log(valueDef);

// Ternário ?
// condição ? se true : se false
console.log('Ternário ?');

cond = false;

const valueDefOrUndef1 = cond ? 'cond true' : 'cond false';

cond = true;

const valueDefOrUndef2 = cond ? 'cond true' : 'cond false';

console.log(valueDefOrUndef1);
console.log(valueDefOrUndef2);

Agora veremos o motivo de funcionar em objetos literais e não em arrays:
Bom, primeiro você precisa saber que apesar de ambos serem objetos, tem comportamentos distintos e também reagem de forma distinta ao spread, isso por que enquanto o spread em um array espera receber um elemento iterable(String, Array, TypedArray, Map e Set) o spread em um objeto literal apenas espera receber um objeto qualquer e utiliza internamente das funcionalidade Object.values, Object.keys e/ou Object.entries para capturar as props e values daquele objeto para incorporá-lo. Exemplos:

// Objeto literal

const obj1 = { k1: 1 };
const obj2 = { k2: 2 };
const obj3 = { k3: 3 };
const obj4 = { k4: 4 };

const obj5 = { k5: 5, ...(true && obj1), ...(false && obj2) }

console.log(obj5);

// Internamente o que aconteceu aqui foi mais ou menos isso:

const obj3Keys = Object.keys(obj3);
const obj3Values = Object.values(obj3);

obj3Keys.forEach((v, i) => {
  obj4[v] = obj3Values[i];
});

console.log(obj4);

/* Ao receber o false como retorno da operação lógica e tentar
pegar suas props e values ele simplesmente retornou um iterable
vazio pois este objeto não tem props e values legíveis. */

console.log(Object.keys(false));
console.log(Object.values(false));

/* Sendo assim o spread funcionou como deveria para o objeto
mesmo não passando na condição, pois tentou espalhar o iterable
vazio e obviamente não incrementou nenhuma prop ou value por
conta deste fato. */

// Array

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...(true && arr1)];
console.log(arr3);

const arr4 = [...(false && arr2)];
console.log(arr4);

/* Utilizando a operação lógica neste caso você tem um efeito
inesperado, na primeira situação para o caso true tudo deve
correr normalmente, porém na segunda situação para o caso false
devemos ter um erro dizendo que não foi possível iterar sobre o
elemento estipulado. */

Entendendo o que ocorreu...
Isso acontece por que o spread no array espera receber um objeto exclusivamente iterável(String, Array, TypedArray, Map e Set) e vai buscar por uma propriedade única de cada array e oculta chamada Symbol.iterator para utilizar dela para iterar sobre a estrutura. Como os objetos geralmente retornados na negação da operação lógica são false; undefined e null, então eles não são iteráveis, o que acaba resultando no erro de sistema. Isso pode ser facilmente resolvido com uma operação lógica composta ou com o próprio ternário. Exemplos:

const arr1 = [1, 2];
const arr2 = [3, 4];

const arr3 = [...(false && arr1 || [5, 6])];

console.log(arr3);
/* Retornou false na primeiro operação, porém por ser uma
operação composta com uma alternativa or(||) eu consegui enviar outro elemento para ser iterado. */

const arr4 = [...(false ? arr2 : [])];

console.log(arr4);
/* Aqui da mesma forma retornou false, porém utlizando o ternário
eu pude gerar uma alternativa vazia para a condição, para que
tudo corresse normalmente mas nenhum valor fosse adicionado. */
Answer: Tenta assim:

let conditional = false;
let arr4 = ['value2', ...(condition ? arr1 : [])];
Comment: Te importas de editar o código para ele funcionar e também explicar porquê essa solução.


How to solve npm run build 137 error? Already have set 10gb

Question: I am running npm run build to create a docker. It has --prod option. If ran without --prod it builds fine. If built with --prod it goes into 137 ENDLIFECYCLE error.
Killed
npm ERR! code ELIFECYCLE
npm ERR! errno 137
Unfortunately i can't just remove the prod option, cos thats what works on dev machine and I am just supposed to be doing devops.
I saw many places that its because of memory low, so i set the variable
NODE_OPTIONS --max-old-space-size
It is at 10GB currently and it is not helping. And i can build same docker in my machine with 8GB.
This build is happening inside jenkins and i did a free -m inside docker just to see, the server has 64GB memory.
So what could be the issue?
Comment: adding --verbose helped us fix in short term. It *seems* like some process was killing it becuase it sees no output from npm run build. command used is npm run build -- --prod --verbose
Comment: Were you able to figure out the issue @manu ?
Answer: Did you try increasing memory available for docker via Docker > Preferences... > Advanced > Ram. It defaults to only 2 GB (on mac).
Answer: Do you use any framework?
you can check this two option 'optimization','aot' in angular.json
(If you use angular)
turn it to false maybe can resolve your problem temporarily
enter image description here
Answer: i had same issue , i updated angular to version 12 and all the dependencies to 12 it helped


What does "Final MON" mean in MLB Sunday games results?

Question: I've seen F/10 MON and F/11 MON and Final MON written after game results in the banner across the bottom of the TV, in WMBA, MLB and MLS, What does MON mean?
Google is giving me nothing.
UPDATE:
Typical result reads: "REDS 4, METS 6, F/11 MON." I have found F/11 means 11 rounds, and "FINAL MON" means the usual 9 rounds. However I've seen FINAL MON behind soccer results, so who knows what MON means. I'll try to take a screen shot.
UPDATE2:
There is no MLB on Mondays - Ever.
However, the results for MLB weekdays show "FINAL", and (I've just found out) "FINAL MON" Is only shown on Sunday games.
Perhaps it means final game up until monday (but not on monday) - How WEIRD.
I'll try to take a screenshot on Sunday.
UPDATE 3:
I was misled, our network wont show MLB on Mondays, certainly there is baseball on Mondays, my apologies. I have now seen "FINAL MON" on Wednesdays and Sundays.
Comment: Do you have a screenshot or a link using that language?  It might mean Monday or Montreal, but neither seems a perfect fit for your description.
Comment: No baseball on mondays, and not montreal, a typical result might be "REDS 4, METS 6, F/11 MON." I have found F/11 means 11 rounds, and "FINAL MON" means the usual 9?
Comment: Surely it wouldn't be FINAL MON as in french for END ?
Answer: Do you have a reference or a screenshot?
F/10 or F/11 is only commonly used for baseball (MLB) scores.  In that case it indicates the game is over (game is "F"inal), and that rather than the regulation 9 innings, additional innings were played (10 or 11).  I can't think of any reason you would see this terminology with WNBA or MLS scores.  Overtime for those games are indicated differently.
For MLS (or NHL or CFL), "MON" is most likely the abbreviation for Montreal, which has a team in those leagues.
For WNBA or MLB, the only thing I can see with that is someone reporting that the score is from a game played on Monday.  But the provider might be trying to say something else that I'm missing.  An image could clear it up.
Comment: There is no MLB on Monday, ever. In fact FINAL MON is only shown on Sunday games. As if indicating the end of the baseball week
Answer: It's hard to tell without a screenshot in question, but likely refers to Monday. As in F/10 MON, would mean the baseball game final score in ten innings is for Monday's game. This might appear Tuesday afternoon, when it's possible for a game to have started, but they are still showing yesterday's results. You might also see this in the playoffs, when they want to show how the series is going so far and are noting that the previous game was on Monday.
Comment: There is no MLB on Monday, ever. In fact FINAL MON is only shown on Sunday games. As if indicating the end of the baseball week.
Comment: Are you getting scores for the entire week then? Does WED or FRI show up? This must be something local to your broadcast in that case and not US TV standard.
Answer: There are MLB games on Monday: http://m.mlb.com/schedule/2018/08/13/
I always thought F/MON or the equivalent meant the game started on Sunday, but ended after midnight, meaning the game ended on Monday. That would explain why "FINAL MON" is only shown on Sunday games.


Confusion about proof of necessary + sufficient condition for $\theta \in \mathbb{C}$ to be an algebraic integer

Question: I am confused about a step in a proof of the following statement in Stewart Tall's ANT book:
$\theta \in \mathbb{C}$ is an algebraic integer if and only if the additive group $G$ generated by powers of $\theta$ is finite.
The "if" part of the proof proceeds as follows: The subgroup $\Gamma$ of $G$ generated by $1, \theta, \ldots, \theta^n$ must be finitely generated. Call the generators $v_1, v_2, \ldots, v_n$. Each $v_i$ is a polynomial in $\theta$ with integer coefficients, so $\theta v_i$ is also such a polynomial. Hence there exist integers $b_{ij}$ such that
$$\theta v_i = \sum_{j=1}^{n} b_{ij}v_j.$$
This last step is what throws me. How is it that $\theta v_i$ has such an expression? It seems to rely on the fact that the $v_i$ generate $\Gamma$. But $\Gamma$ is additive, so I see no reason why the product $\theta v_i$ is necessarily in $\Gamma$. Any clarification would be much appreciated. Thanks!
Answer: Say $v_i=a_0+a_1\theta +a_2 \theta^2+\cdots.$ Then $\theta v_i=a_0 \theta + a_1 \theta^2 + \cdots$ is also a polynomial in $\theta$ with integer coefficients. I think the trick needed here is to actually "multiply through" by the $\theta$ as just done, so the result is definitely one of the polynomials in $\theta$ with integer coefficients. Maybe the confusion is in thinking of the $\theta$ in the expression $\theta v_i$ as playing the role of a scalar.
Comment: I still don't understand why each $\theta v_i$ can necessarily be expressed in terms of the $v_i$. The $v_i$ generate $\Gamma$ so the degrees of the $v_i$ need not be higher than $n$. But at least one of the $v_i$ needs to have degree $n$ since $theta^n \in \Gamma$. But if you multiply that one by $\theta$ you will get a degree $n + 1$ polynomial. Why should that be expressible in terms of the $v_i$? Thanks
Comment: In the "if" part of the proof, does Tall's proof *assume* the group $G$ generated by powers of $\theta$ is finitely generated? And if so does it also assume $G$ is generated by $1, \theta, \theta^2,\cdots, \theta^n$? If so then since $\theta^{n+1}$ lies in $G$ it can be expressed as an integer combination of the powers from 0th up to nth power of $\theta$ and so when the last term $a_n\theta^{n+1}$ of $\theta v_i$ is encountered it can be expressed as just outlined, and that can be added to the previous terms of $\theta u_i$ whose degrees are less than $n$.
Comment: It assumes $G$ is finitely generated and assumes that $\Gamma$ is some subgroup of $G$ generated by $\{1, \theta, \ldots, \theta^n\}$. It does not assume that $\{1, \theta, \ldots, \theta^n\}$ generates the whole group.
Comment: Then in the above one should say that $\theta^{n+1}$ lies in $\Gamma$ with the same idea applied to the term $a_n \theta^{n+1}$ now (since in $\Gamma$) expresses it in $\Gamma$ as a linear integer coefficient combination of the powers of $\theta$ which generate $\Gamma.$


Why do we define the information structure as a finite measurable space?

Question: $\textit{Definition:}$ The information structure $\mathfrak{I}=((X^i),\mu)$ is given by a finite set of signals $X^i$ for each $i$ and by a probability measure $\mu$ over $X$. When $x$ is drawn according to$\mu$, player $i$ is informed about the coordinate $x^i$.
$\textit{Question:}$ Why do we need to define the information structure as a measure set which is finite and what does it mean that we know the probability measure?
I would appreciate it if anybody could give some example as well.
Answer: It's a finite set, so it's measurable, that's for free. In fact I would wager that it is chosen to be finite merely to do away with measure theoretic technicalities. The question you're actually asking, it seems to me, is why there's a probability distribution involved at all, that is, why is $X$ random. This ultimately has to get down to what is being modeled. As per the paper you linked to in your other questions, this structure was proposed by Aumann in an earlier paper. Did you read that? That's perhaps the cleanest way to get something definitive. One can make some general observations though.
Notice that the basic structure of this situation is that there is some central mechanism that communicates information to each player, who can then adapt their strategies on the basis of this information. Keep in mind that this central mechanism is a useful abstraction, and should not be taken too literally.
One situation we may model in this way is if all the players are probing some common environment - so 'the world' has some state, and the players make observations of this state to adapt their play. Most situations of this sort are noisy - typically the underlying state is random, and our measurement processes introduce further noise into the observation. The definition handles this by taking all this noise, and neatly packaging it into one distribution $\mu$, which is ultimately all that affects the agents' play (since they can only act on the basis of their $X^i$s).

As a broader comment, I think you might be skimping on your reading. At a basic level, the way theoretical study works is that you start with broad observations of the subject you care about, model these to abstract out the messy details (and to simplify enough to enable analysis), and then analyse this model to derive consequences that let you reason about how the actual thing might work (there's a lot of feedback that I'm ignoring here). I think there's a tendency for people starting out to think that all the action is in the third phase, but this is not true - in fact the first two phases are crucial, and also in a sense more difficult because they are softer. This question, along with the others you asked, suggest that you're not doing enough basic reading to get the overall structures the subject cares about, and are jumping ahead to ask why the particulars of the definitions (the second phase) are set up the way they are. Ultimately the reason for this is observations made in the first phase (and some amount of technical convenience), and so such things will remain gobbledygook until you grok something about the structures.
Do note that this is not easy, and takes time. Also in my opinion this is done much better verbally (in meetings/reading groups/class) than textually. Try to speak with your peers or an advisor for both references on what to read, and to discuss and clarify what you read in them.
Comment: This is the paper of Aumann https://www.sciencedirect.com/science/article/abs/pii/0304406874900378
You suggest, that I should start from here?
Comment: I do, yes. If you're confused about some definitions in a paper, and the paper refers to an earlier paper in which they were formulated, then it seems natural to consult this earlier paper to understand these definitions and the rationale behind them. An alternative would be to consult a textbook or survey on the subject, where the presentation of the earlier paper might have been streamlined and refined. I am not a game theorist, so I don't know if such a source exists, but your advisor or peers, if available, should have an idea of this.


Form inputs being disabed during the Ajax request

Question: I'm working on a module where I have a form inside of a block, I'm using Ajax to submit the form, but I noticed that the form's inputs are disabled when sending a request with Ajax. Well in my case I want to keep using the form's input (keyup event) and displaying the result for each request.
// my current code
$form['combine'] = array(
    '#type'       => 'textfield',
    '#size'       => 255,
    '#maxlength'  => 128,
    '#attributes' => array('placeholder' => 'Search'),
    '#ajax'     => array(
        'callback'  => 'ajax_filter_callback',
        'effect'    => 'fade',
        'wrapper'   => 'result-content',
        'event'     => 'keyup',
    ),
);

Comment: Is there a reason to not use autocomplete functionality for this? I think that it will not disable the input element when using this method. Drupal Examples has this where you can see how they implement this: https://api.drupal.org/api/examples/ajax_example!ajax_example_autocomplete.inc/7
Comment: @burnsjeremy I don't know, maybe I'll use autocomplete, it's just a big query with many joins, it's a customized filter in fact, I used Views combined filter but it's a bit limited for my case, so I developed my own module, with a form in a block as a filter (the one that gets its inputs disabled), but I'll take the idea of autocomplete into consideration. thank you
Answer: That functionality is built-in so you'll need to monkey-patch Drupal.ajax.prototype.beforeSend (found in misc/ajax.js).
Copy the entire code, but remove/modify this line:
$(this.element).addClass('progress-disabled').attr('disabled', true);

So in your module or theme's JS file:
Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
  // Place all code from the original function here, except the line above.
}

YMMV, you may unwittingly introduce unexpected behaviour by not waiting for each request to complete.
Comment: Thanks @clive, I know I may run into problems, but I guess it's not that elegant to disable the inputs, maybe wait behind the scene for the request to complete to make a new one, I don't know, I'll think about it, thanks again.


Proof that line $HG$ bisects the perimeter of $ABC$

Question:
Question. From this picture, $D$ and $E$ are excenters of $ABC$, and $G$ and $H$ are midpoints of $AB$ and $KL$.

Prove that $HG$ bisects the perimeter of $ABC$. In other words, prove that $AX=CX+CB$.
Prove that $HG$ is parallel to the angle bisector of angle $C$.

My Approach. I guess that $CX$=$CY$. If so, then we can prove problem 2) easily. And, we can change problem 1) as $AX=BY$.
Answer: Here is an approach.
1)Show that $AK=BL$ (this is easy)
2) From 1) note that $G$ will have the same power with respect to both circles.
3) Prove that $H$ has the same power with respect to both circles (this is the difficult part)
Hint: Extend $KL$, so that $K'$ is the intersection with the circle on the left and $L'$ is the intersection with the circle on the right. Note that the power of K w.r.t the circle on the right is the same as the power of L w.r.t the circle on the left, from this conclude that $KK'=LL'$ and therefore the power of $H$ w.r.t both circles is the same.
4) Since the locus of the points that have the same power with respect to both circles is a line, then we have that this line is $GH$.
5) Since $X$ is in the line $GH$, then the power of $X$ with respect to both circles are the same. From this we get $KX=CX+CL$ and therefore, $AX=CX+CB$. This proves the first part.
6) Since $Y$ is in the line $GH$, then the power of $Y$ with respect to both circles are the same. From here, we get $CK-CY=CY+CL$. Now, using that  $KX=CX+CL$ (by 5) conclude that $CX=CY$.
Comment: Bravo, well done!


$\ln{2n+1\over n+1}<{1\over n+1}+{1\over n+2}+\cdots +{1\over 2n}<\ln 2$

Question: Using the fact: ${x\over 1+x}<\ln (1+x)<x$, when $x>0$; deduce that:
\begin{equation}
\ln{2n+1\over n+1}<{1\over n+1}+{1\over n+2}+\cdots +{1\over 2n}<\ln 2
\end{equation}
This problem also asked to prove the fact I have given. I could prove it using MVT, but the deduction which should be easier is out of my hand.
Comment: Possible duplicate of [Proof for $\log\frac{2n+1}{n+1}<\frac{1}{n+1}+\frac{1}{n+2}+...+\frac{1}{2n}<\log 2$](https://math.stackexchange.com/q/957977).
Answer: Make a change of variables $y = \frac{x}{1+x}$, we have: $x = \frac{y}{1-y}$. So, from $\frac{x}{1+x}<\ln(x+1)$, we have :
$$y<\ln(\frac{1}{1-y}) = -\ln(1-y) \tag{1}$$
And because $\ln(1+x)<x\tag{2}$
From (1) and (2), we deduce that
$$\ln(1+x)<x<-\ln(1-x)$$
Replacing $x$ by $\frac{1}{n+k}$ for $k=1,...,n$
$$\ln(n+k+1)-\ln(n+k) < \frac{1}{n+k}< -(\ln(n+k-1)-\ln(n+k)) $$
Hence
$$\sum_{i=1}^n(\ln(n+k+1)-\ln(n+k))<\sum_{i=1}^n \frac{1}{n+k}<\sum_{i=1}^n(\ln(n+k)-\ln(n+k-1))$$
or
$$\ln(2n+1)-\ln(n+1)<\sum_{i=1}^n \frac{1}{n+k}<\ln(2n)-\ln(n)$$
or
$$\ln \left(\frac{2n+1}{n+1} \right)<\sum_{i=1}^n \frac{1}{n+k}<\ln(2)$$
Answer: The fact is: $\frac{x}{1+x} \lt \ln(1+x) \lt x$, when $x > 0$. Since we particularly know that $\ln(1+x) \lt x$, we can write:
$$\begin{align} & \ln(2n+1)-\ln(2n)=\ln\Biggl(1+\frac{1}{2n}\Biggl)\lt\frac{1}{2n} \\
& \ln(2n)-\ln(2n-1)=\ln\Biggl(1+\frac{1}{2n-1}\Biggl) \lt \frac{1}{2n-1} \\
& \space \space \space \space \space \vdots \\
& \ln(n+2)-\ln(n+1)=\ln\Biggl(1+\frac{1}{n+1}\Biggl)\lt \frac{1}{n+1} \\ \end{align} $$ If we rewrite these expressions in a single line all at once, we eventually get: $$\ln\frac{2n+1}{n+1}\lt \frac{1}{n+1} + \frac{1}{n+2} + \cdots +\frac{1}{2n}$$
$\ln()$ is an increasing function where it is defined. We can write for any $x>\frac{1}{2}$ that: $$\ln\Biggl(2-\frac{1}{x}\Biggl)\lt \ln2 \lt \ln\Biggl(2+\frac{1}{x} \Biggl)$$
Therefore, we can deduce that: $$\ln\frac{2n+1}{n+1}=\ln\Biggl(2-\frac{1}{n+1}\Biggl) \lt \ln2 \lt \ln\Biggl(2+\frac{1}{n+1} \Biggl)$$ Finally: $$\ln\frac{2n+1}{n+1} \lt \frac{1}{n+1}+\frac{1}{n+2}+\cdots+\frac{1}{2n} \lt \ln2$$