Flutter: How to expand/collapse (show/hide) a Row in a GridView or Wrap widget

Question: I'm trying to build a GridView where selected the item can expand/collapse (show/hide) a row in the immediate consecutive row of the selected item, like an information box.
On the screenshot below I'm showing an example where the Node 001 is selected.
Don't know if I can achieve this with GridView widget or Wrap Widget, but any help will be very appreciated.
Thanks in advance for your support.
Sample mockup screenshot:

My actual GridView code:
GridView.builder(
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: 5,
                  mainAxisExtent: 40),
              itemCount: nodes.length,
              itemBuilder: (BuildContext context, int index) {
                return TextButton(
                  onPressed: (selectedNode == nodes[index].slaveId)
                      ? () {}
                      : () =>
                          Provider.of<SelectedNode>(context, listen: false)
                              .value = nodes[index].slaveId!,
                  style: TextButton.styleFrom(
                      backgroundColor:
                          (selectedNode == nodes[index].slaveId)
                              ? selectedColor
                              : unselectedColor),
                  child: Text(
                      'Node ${nodes[index].slaveId.toString().padLeft(3, '0')}'),
                );
              },
            )

Modified code:
SizedBox(
        width: double.infinity,
        child: SizedBox(
          height: MediaQuery.of(context).size.height / 3.2,
          child: GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: 5,
                  mainAxisExtent: 40),
              itemCount: [1, 2, 3, 4, 5, 6, 7, 8, 9].length + 1,
              clipBehavior: Clip.none,
              itemBuilder: (context, index) {
                if (index != 1) {
                  return Stack(
                    clipBehavior: Clip.none,
                    children: [
                      TextButton(
                        onPressed: (selectedNode == nodes[index].slaveId)
                            ? () {}
                            : () => Provider.of<SelectedNode>(context,
                                    listen: false)
                                .value = nodes[index].slaveId!,
                        style: TextButton.styleFrom(
                            backgroundColor:
                                (selectedNode == nodes[index].slaveId)
                                    ? selectedColor
                                    : unselectedColor),
                        child: Text(
                            'Node ${nodes[index].slaveId.toString().padLeft(3, '0')}'),
                      ),
                      index == 0
                          ? Positioned(
                              child: Text('1hjkkhj'),
                              bottom: -20,
                              left: 0,
                              right: 0,
                            )
                          : SizedBox(),
                    ],
                  );
                } else {
                  return TextButton(
                    onPressed: (selectedNode == nodes[index].slaveId)
                        ? () {}
                        : () => Provider.of<SelectedNode>(context,
                                listen: false)
                            .value = nodes[index].slaveId!,
                    style: TextButton.styleFrom(
                        backgroundColor:
                            (selectedNode == nodes[index].slaveId)
                                ? selectedColor
                                : unselectedColor),
                    child: Text(
                        'Node ${nodes[index].slaveId.toString().padLeft(3, '0')}'),
                  );
                }
              }),
        ),
      ),

Answer: you can get the selected index and dived it to 4 and round up the result should give you the row number which that item click, so call this selectedRow row. in your grid view you can use selectedRow and add empty space for the next row. After that change item widget that you show in grid view and add it in a stack and add another container that contain your expanded widget. also remember that you should set stack and grid view clipBehavior to Clip.none.
something like this:
ListView.builder(
            padding: const EdgeInsets.all(8),
            itemCount: [1, 2, 3].length + 1,
            clipBehavior: Clip.none,
            itemBuilder: (context, index) {
              if (index != 2) {
                return Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Text('dasdasdasd'),
                    index == 1
                        ? Positioned(
                            child: Text('1hjkkhj'),
                            bottom: -20,
                            left: 0,
                            right: 0,
                          )
                        : SizedBox(),
                  ],
                );
              } else {
                return SizedBox(
                  height: 20,
                );
              }
            })

I know it is listview but the concept work in gridview too.
Comment: Ok got it working with the Wrap widget and as you mention, controlling the selectedRow I then build that row in a Column containing couple Rows... Thanks for the help.
Comment: Hi @eamirho3ein, Thanks for your prompt answer but I cannot see how to add a Row empty space as the GridView is limiting the size of each item in the grid. I have tested this forcing the positioned item with selectedItem == 0. I have updated my code with your instructions.


How to handle delete mutations with optimistic UI in Apollo?

Question: https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-mutation-options-optimisticResponse
There's plenty of documentation and tutorials showing use of the mutation update and optimisticResponse properties involving adding things, but I haven't seen any involving deletions.
I'm not exactly sure how that code should look. With a create mutation, you want to add the new item to the Apollo cache via update and add a temporary copy to the UI using optimisticResponse. But with a deletion, it doesn't make sense to "show" the deletion since it's the absence of data.
This is what I've got in a method in my Vue component, which is partly correct:
async handleDelete(trackId: number) {
  const result = await this.$apollo.mutate({
    mutation: require('@/graphql/delete-tracks.gql'),
    variables: {
      ids: [trackId],
    },
    update: store => {
      const data: { getTracks: TrackList } | null = store.readQuery({
        query: getTracksQuery,
        variables: this.queryVars,
      });

      if (data && data.getTracks) {
        data.getTracks.data = data.getTracks.data.filter(
          (track: Track) => track.id !== trackId
        );
        --data.getTracks.total;
      }

      store.writeQuery({
        query: getTracksQuery,
        variables: this.queryVars,
        data,
      });
    },
    optimisticResponse: {},
  });

  console.log('result:', result);
},

I figured out that I basically need to remove the deleted item from the Apollo cache, and that part seems to work great. Though the visual removal doesn't happen immediately, since there's no optimisticResponse. That's the part I have absolutely no idea how to go about writing.
Comment: reminder to wrap everything in the update with a try catch since store.readQuery can fail if theres nothing in the cache
Answer: Got it, it was much simpler than I thought. I just didn't quite understand how optimisticResponse came into play with update.
optimisticResponse: {
  __typename: 'Mutation',
  deleteTracks: [trackId],
},

So the update method will take this result from optimisticResponse and remove that track ID from the cache. update will be called a second time with the GraphQL server response, and the Apollo cache will be reconciled.


Swift: Parsing array elements from JSON request

Question: I am getting a JSON response from http request. After getting it, it has arrays and trying to parse.
Swift code:
if let finalResponse = parseJSON["visuals"] as? [String: Any] {

                let balanceResponse = finalResponse ["balanceList"] as? AnyObject
                print("balanceResponse::   \(balanceResponse)")

                let dateResponse = finalResponse ["dateList"] as? AnyObject
                print("dateResponse::   \(dateResponse)")

print log:
balanceResponse::   Optional(<__NSArrayM 0x17404b880>(
{
    data =     (
        "32872.23",
        "38814.87",
        "38915.85"
    );

}
dateResponse::   Optional(<__NSArrayM 0x17005a4f0>(
Apr 26, 2017,
Jun 10, 2017,
Jul 26, 2017
)

How to access 3 values in data array and 3 date values from dateResponse
Comment: Are you using a library like SwiftyJson?
Comment: No, i'm not using,
Answer: dateResponse and balanceResponse will return you a new array. So just treat them as any other array and access the element using index and fill your models.
Other simple way I will recommend you to use third party Library like ObjectMapper or SwiftyJson it will less your work and they are very much stable solutions.
UPDATE:
let balanceResponse = finalResponse ["balanceList"] as? AnyObject
let data = balanceResponse["data"]
let firstValue = data[0]

Comment: I could access the second array (dateResponse) as like any other standard array using index, but the first one (balanceResponse) could not able to access like standard array using index.


For E a Normed Vector Space, What Is $\mathbb{R}^{E}$? (Brezis, Theorem 3.16)

Question: I am currently reading Theorem 3.16 in Brezis's "Functional Analysis, Sobolev Spaces, and Partial Differential Equations".
The proof starts of: "Consider the Cartesian product $Y = \mathbb{R}^{E}$, which consists of all maps from $E$ into $\mathbb{R}$".
We denote the elements of $Y$ by $\omega = (\omega_{x})_{x \in E}$, with $\omega_{x} \in \mathbb{R}$. We equip the stanadard product topology to this space, which Brezis notes is the coarsest topology on $Y$ associated with the collection of maps $\omega \rightarrow \omega_{x}$. He then claims that this is "of course" the same as the topology of pointwise convergence.
I have found it hard to find a real definition of this set $Y = \mathbb{R}^{E}$, and I find this notation ambiguous. Each element of $Y$ is a function from $E$ into $\mathbb{R}$, but how exactly are we able to express this as a product of $E$ and $\mathbb{R}$? Could someone please point me to a fully fleshed out definition of $Y$ here?
Comment: $\Bbb R^E$ isn't the Cartesian product of $\Bbb R$ and $E$. Rather it is the Cartesian product of $|E|$ copies of $\Bbb R$.
Comment: Hi! Thank you for your response. So would it be possible to create a bijection between the set of maps between E and R, and this Cartesian product space?
Answer: It's not really a product, it's an "exponential object". In set theory (where this notation comes from), for sets $A$ and $B$, $A^B$ is by definition the set of functions from $B$ to $A$. The Cartesian product however of $A$ and $B$, $A \times B$, is the set of ordered pairs $\{(a,b): a \in A, b \in B\}$ which is a different object altogether.
As $2=\{0,1\}$ (in cardinals and ordinals, this is how the set $2$ is defined!) we can identify $A^2$ with $A \times A$ in an obvious way via a bijection that sends $(a,b) \in A \times B$ to the function $f: 2 \to A$ defined by $f(0)=a, f(1)=b$. So for finite products we usually identify the exponential $A^n$ with an $n$-fold product of copies of $A$. But note that they're not really the same set...
I'd better get used to thinking about these powers as exponential objects, i.e. sets of functions, not "tuples", except in the finite case, maybe.
And the product topology and "the topology of pointwise convergence" are common synomyms for the unique coarsest (smallest) topology that makes all "projections" (or evaluations, sending $f$ to $f(x)$ for some fixed $x$) continuous.
Comment: @DavidHughes There are no infinite tuples, really. It's just a notation for a certain function. If you write $(x_n)_n$ or $(x_0,x_1,x_2, \ldots)$ you just mean the function that sends $n$ to $x_n$. Just a convenient shorthand.
Comment: @DavidHughes Yes, define the projections $\pi_x: \mathbb{R}^E \to \mathbb{R}$ for any $x \in E$, by $\pi_x(f)=f(x)$ and then give this set the smallest topology such that all projections $\{\pi_x: x \in E\}$ are continuous. If you do this for $X \times X$ you get the two standard projections under the identification with $X^2$ that I gave.
Comment: How can I construct such a bijection for infinite dimensions?
Comment: But I need to equip this space with the "standard product topology" so $\mathbb{R}^{E}$ should be equivalent to Euclidean space somehow no?
Comment: Is there a name for this kind of space that I can easily look up and read more into?
Comment: @DavidHughes see [Wikipedia](https://en.wikipedia.org/wiki/Cartesian_product#Infinite_Cartesian_products) for example, and any good book on general topology, like Engelking or Willard, Kelley or Dugundji.
Answer: The definition as it is stated is a full definition. A function $\omega: E \to \Bbb R$ can also be viewed as a very long tuple of elements in $\Bbb R$, with an entry $\omega_x$ for every $x \in E$. So you get $\omega(x) = \omega_x$, where the left side is viewing $\omega$ as a function, and the right side is viewing $\omega$ as a tuple.
Now where do tuples live? In a product, so we get
$$
\Bbb R^E = \prod_{x \in E} \Bbb R.
$$
Just a smaller example, if $E =\{0,1,2\}$ (so it is not a vector space now, but just a set). Then a function $\omega: E \to \Bbb R$ is just a tuple $(\omega_0, \omega_1, \omega_2)$ of three elements in $\Bbb R$. And we have in this case
$$
\Bbb R^E = \prod_{x \in E} \Bbb R = \Bbb R \times \Bbb R \times \Bbb R.
$$

Since you also mention the product topology, you may be interested in this Wikipedia page on that subject.
Comment: @David There is no need to order them. A tuple is a family of elements, indexed by some set. The reason we usually view them as ordered is because finite tuples (when there is a finite amount of indices, like in my example) can always be ordered. But there is no real reason to order them, we do not need an "$x$th" entry, just entry with index $x$.
Comment: @David No, what I am saying is that you can no longer necessarily order them. For example, if we have a tuple with an entry for every $x \in \mathbb{Q}^2$, then our tuple is not really ordered. It is more like a table of entries. Generally, for infinite $E$ and $x, y \in E$, we cannot necessarily say if $x < y$ or $y < x$. But this is not needed to make sense of tuples. We can perfectly well have two tuples $\omega$ and $\omega'$ such that $\omega_x = 1$, $\omega_y = 2$ and $\omega'_x = 2$, $\omega'_y = 1$. We can still distinguish between these tuples by looking at the entries at $x$ or $y$.
Comment: I wouldn't think of it as tupels, but just as functions. A tupel $(x_1, \dots, x_n)$ with elements in $X$ can be seen as a function $\{1, \dots, n\} \to X$ by $i \mapsto x_i$. Now, generalise this, and consider a tupel $(\omega_x)_{x \in X}$ as the map that sends $x \mapsto \omega_x$. In fact, this is the formal definition of product! Thus, by definition $\mathbb{R}^E$ is the set of all functions $E \to \mathbb{R}$. If you have such a function $f$, we sometimes write it as $(f_x)_{x \in E}$ or $(f(x))_{x \in E}$
Comment: @EpsilonDelta That identification is precisely the point of the answer and the thing that OP was not understanding about some proof.
Comment: @David Well, $\mathbb{R}^\infty$ is not really well-defined, because it is not clear what kind of infinity is in the exponent. It may be countable (e.g. $\mathbb{Q}$) or uncountable (e.g. $\mathbb{R}$, and in fact there are many more different uncountable infinities). Anyway, you would call these things "product space" and the term "product topology" that Brezis uses is also standard. I have edited my answer to include a link with more explanation.
Comment: @David Usually in analysis it means that kind of thing, so I can see why you would think something like that. In more general settings it is better to be a bit more precise.
Comment: Thank you for your answer. How do we decide the order of these entries in these tuples? For my class, I will likely be expected to construct this $\mathbb{R}^{E}$ properly.
Comment: So, in finite dimensions, the vectors (1,2) and (2,1) are different, but you're saying that this sort of distinction doesn't exist in infinite dimensions?
Comment: Ok, but Brezis talks about equipping this space with the "standard product topology". He means the topology on Euclidean space right? So there should be an explicit way to show this space is equivalent to $\mathbb{R}^{\infty}$ no?
Comment: Is there a name for this kind of space that I can easily look up and read more into?
Comment: I see. I guess I had taken for granted that the infinity was the limit of increasing naturals. Thank you very much!


How to customize permissions for a custom module

Question: I created a custom module that hides a field in a content type editing screen from the user and simultaneously auto-selects a value for that field for the user. It works great for the admin role but for some reason my other user's who are able to login and who have permission to edit the content type don't get this functionality applied. They still see the field and can still select a value for it.
Anyone know how to make the permissions for a custom module apply to ALL users?
Here's my module code:
<code>/**
 * @file
 * Auto saving to a term reference field.
 */
 /**
  * Implementation of hook_form_alter().
  */
function seven_form_resource_node_form_alter(&$form, &$form_state, $form_id) {
    hide($form['field_icon']);
}
/**
 * Implementation of hook_node_presave().
 */
function grouphideandselect_node_presave($node){
  //Condition for particular content type
  if($node->type == 'resource'){
    $icon_ary = array();
    //Array to map category with icon given as Category=>Icon
    $field_type_to_icon = array(1 => 1,2 => 1,3 => 1,4 => 2,5 =>
2,6 => 2,7 => 2,8 => 6,9 => 6,97=>6,98 => 6);
    $category = $node->field_type['und'];
    foreach($category as $k=>$c){
      $icon = $field_type_to_icon[$c['value']];
      if(!in_array($icon, $icon_ary)){
        $icon_ary[] = $icon;
        $node->field_icon['und'][$k]['tid'] = $icon;
      }
    }
  }
}
</code>
Comment: Since you're not using the user submitted value at all, have you tried `$form['field_icon']['#access'] = FALSE;`? Also your hooks seem a bit off, can't figure out if your module's name is `grouphideandselect` or `seven_form`. The thing with `hide()` is it's more of a render thing, and can have unexpected behaviors. I'm not really sure why it's behaving like that for you (could be cache, most likely), but this has NOTHING to do with permissions
Answer: Add the Field Permissions module, this gives you control over every field in the content type. You edit the permissions on a field by field basis in the content type editing area. This gives you control over editing, and viewing the field.
https://www.drupal.org/project/field_permissions


Can this Fourier transformed function be transformed into partial fraction?

Question: Hi I'm self learning stochastic process, I've come across a problem and found
$$H=\frac{2+j(2w)}{(1-w^2)+j(2w)} \\
|H(iw)|^2=\frac{2^2+(2w)^2}{(1-w^2)^2+(2w)^2} \\$$
In attempt to find the power spectral density with partial fraction,
$$S_y(w)=|H(iw)|^2 S_x(w)=\frac{2^2+(2w)^2}{(1-w^2)^2+(2w)^2} \frac{3}{2^2+w^2} \\
= \frac{12(1+w^2)}{(w^2+1)^2(w^2+4)}
= \frac{A}{(w^2+1)^2}+\frac{B}{(w^2+4)} \\
A = \frac{12(1+w^2)}{w^2+4} = 0, w=\pm\sqrt{-1}= \pm j \\
B=\frac{12(1+w^2)}{(w^2+1)^2} = \frac{12(1-4)}{(-4+1)^2}=\frac{-36}{9}=-4, w^2+4=0, w=\pm2j$$
Is complex $w$ even making any sense? Because I thought w is part of $iw$, then it should be real if that makes sense.
Answer: $$\frac{12(1+w^2)}{(w^2+1)^2(w^2+4)}=\frac{12}{(w^2+1)(w^2+4)}=\frac{4}{w^2+1}-\frac{4}{w^2+4}$$
Comment: that's right. can w be imaginary? That's what I wanted to ask.
Comment: Now, I think of it, $\omega$ can be negative.


Interpreting Seasonality Component Exponential Smoothing Models

Question: I am building an exponential smoothing model that has seasonality in it, I would like to analyze the data with the seasonal factor removed so I can tell if a performance one month was due to seasonal factors or if it was just an over/under performing month.  I wanted to see if the approach I am taking makes sense or if I am widely off base.
For an example I looked at the Air Passengers data.  When using the ETS function it produces a MAM model and so then I look at the seasonal component.
library(datasets)
library(forecast)
fit <- ets(AirPassengers)
season <- fit$states[,"s1"]

I am going to use a bit of rounding for simplicity sake but let's say that for 1960 the first part of season is as follows:
Jan - 0.90
Feb - 0.89
Mar - 1.01
Apr - 0.99
....

Am I correct in interpreting this as January will be 10% lower due to seasonality factors, February 11% lower, March 1% higher, and April 1% lower?
If this is incorrect, is there a way to interpret the seasonality component in a similar way so that it can be "factored" out of other analysis?
Answer:
Am I correct in interpreting this as January will be 10% lower due to seasonality factors, February 11% lower, March 1% higher, and April 1% lower?

Yes. Given that your seasonality is multiplicative (the final "M" in the (M, Ad, M) model), this is exactly the correct interpretation. (If your seasonality were additive, you would need to interpret it as an additive offset.)


Transform general multivariate normal to standard multivariate normal

Question: I have data that I can assume will be multivariate normal with a known mean vector mu and known covariance matrix sigma, and I'm looking to identify points that fall outside the 95% ellipse. I think the proper way to do this is to apply a transform to the data to a standard multivariate normal, compute the euclidean distances to zero, and compare against the value derived from running mvtnorm::qmvnorm(.95,tail='both',mean=mu,sigma=sigma). However, if this is correct (and feel free to correct me if there's a simpler solution to labelling the points outside the 95% ellipse), I'm struggling with the transform part. I know I'd subtract the mean vector mu from the observed data matrix, and I need to do something involving the resulting matrix and sigma, but I'm lost on what. Some code below showing some data and ending where I'm stuck:
mu = c(100,50)
sigma = matrix(c(100,210,210,900),nrow=2)
obs_data = MASS::mvrnorm(1e2,mu=mu,Sigma=sigma)
transformed = t(t(obs_data) - mu)
#what now?

Comment: See https://stats.stackexchange.com/questions/62092.
Comment: Ah! So the Mahalanobis distance is the euclidean distance-from-zero after the transform, so I can just use the `stats::mahalanobis()` function. Neat! Quick follow-up @whuber: do compare these distances to the 95% ellipse (or hypersphere) would I be getting the comparison value via `mvtnorm::qmvnorm(.95,tail='both',mean=mu,sigma=sigma)` or `mvtnorm::qmvnorm(.95,tail='both',sigma=diag(2))`? (i.e. do I need to tell `qmvrnorm` the original mean & covariance?) I'm getting very different results between these two.
Comment: `qmvnorm` gives you the half-width of a mean-centered square (or, generally, hypercube) in the original coordinates.  In the transformed coordinates that region would correspond to a generalized rhombus.
Comment: Oh, looking at the help page for `stats::mahalanobis()` and it shows that the distances should follow the same quantile function as a chi-square distribution with df=ncol(x), so I don't even need `qmvnorm`. When I use `qchisq(.95,df=ncol(dat))`, I do indeed observe that 95% of the distances exceed this value. So I wonder what `qmvnorm()` is doing or is supposed to be used for?
Answer: With the help of the content here, I was able to work this out and thought I'd post the resulting code and verification:
#define a function to transform a standard multivariate normal (zero mean,
# identity covariance) to a non-standard multivariate normal with specified
# means and covariance.
std_to_mvn = function(Z,mu,sigma){
    tchol_sigma = t(chol(sigma))
    X_0centered = t(tchol_sigma %*% t(Z))
    X = t(t(X_0centered)+mu) #add means
    return(X)
}

#define a function to transform a multivariate normal with mean mu and covariance
# sigma to a standard multivariate normal with zero mean and identity covariance
mvn_to_std = function(X,mu,sigma){
    tchol_sigma = t(chol(sigma))
    X_0centered = t(t(X)-mu)
    Z = t(solve(tchol_sigma,t(X_0centered)))
}

#Check that we can induce the non-standard multivariate normal

#first,sample from a "standard" multivariate normal
z = MASS::mvrnorm(
    n = 1e5
    , mu = rep(0,times=3)
    , Sigma = diag(3)
)

#next, specify the parameters (arbitrary; taken from https://jamesmccaffrey.wordpress.com/2017/11/03/example-of-calculating-a-covariance-matrix/)
mu = c(68, 600, 40)
sigma = matrix(
    c(
        11.5 , 50, 34.75
        , 50, 1250, 205
        , 34.75, 205, 110
    )
    , nrow = 3
    , ncol = 3
)

#now, transform and check that we get what we expected
x = std_to_mvn(z,mu,sigma)
max(abs(colMeans(x)-mu)) # <1
max(abs(cov(x)-sigma)) # <1

#Check that we can transform a non-standard multivariate normal to standard
x = MASS::mvrnorm(
    n = 1e5
    , mu = mu
    , Sigma = sigma
)

#now, transform and check that we get what we expected
z = mvn_to_std(x,mu,sigma)
max(abs(colMeans(z))) # <1
max(abs(cov(z)-diag(3))) # <1


How can I include a large block of regex with LaTeX?

Question: Is it possible to include a large block of a regex (like this one: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html) without escaping all colliding characters first?
I think of something like
\begin{following_section_will_not_be_parsed_by_latex}
(a+?b)
\end{...}

Answer: You can include \usepackage{listings} and then use
\begin{lstlisting} [code|regex|whatever] \end{lstlisting}

Comment: verbatim is a little more lightweight than listings. But yes, both rely on turning LaTeX off for whatever happens inside the environment and turning it back on again afterwards.
Answer: Look at fancyvrb package.  From the README:

The `fancyvrb' package provides very
  sophisticated facilities for reading
  and writing verbatim TeX code. Users
  can perform common tasks like changing
  font family and size, numbering lines,
  framing code examples, colouring text
  and conditionally processing text.

So you can do something like:
\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
\begin{Verbatim}[fontsize=\small,frame=single,label=RFC822 regexp]
...
\end{Verbatim}

In order to not clutter your Latex file with the huge regex, you can include a file verbatim as well.
Answer: Use a verbatim block. But it won't look very nice :(


Administrator users can add records, end users can view them

Question: How can the administrator users add few records into the database (through a form), and how can the end users view them in the front end?

Administrator users will be adding records of training classes, through a form in an administration panel.
The end user will be viewing the list of training classes in the front end, in a block.

How to achieve these tasks?
Comment: any drupal geek existing here to answer my question?
Answer: here in short all the steps for the simplest solution I can think of:

depending on your content (needed fields...) you may need to create a new contentype (YOURCONTENTTYPE)(maybe using the CCK module (drupal6))
make sure the roles are set correctly (e.g. admin can create and view this content, authenticated only view...) via admin/user/permissions
create a block (node-)view with the views module where you filter by YOURCONTENTTYPE and sort by date
modify the visibility setings of this block via admin/build/block or in the view itself
admin can create content via node/add/YOURCONTENTTYPE

But it really depends on what exactly you want to do.
Answer: In Drupal, there isn't a flag that set a page as administration page, and a tag that set a page/block for end users.
What makes a page for administrator users is the permission that users needs to have to see that page. A settings page requiring the users to have the permission to administer users is considered an administration page; the same is true for a setting page requiring the permission "administer content type," or "administer nodes."
If you have a page that needs to be seen only from administrators, then you need to use an existing administration permission, or implement a module that implement the specific permission that you need.
A block implemented by Views can use the permission implemented in other modules as well, and you can set the permission users need to have to view a block (or in general, a view) created with Views.


UITabBarController initially highlights all tab bar item images

Question: I'm programmatically instantiating a UITabBarController that will manage 2 view controllers, and then setting it as the rootViewController. However when the views appear, it highlights all the tab item's images (although the text is properly highlighted). No matter what I set to the selectedIndex the images will all appear highlighted. Only when you tap on the tab bar items does it actually toggle the highlighted state on the images. What's going on here?
Code:
UITabBarController *tabController = [[UITabBarController alloc] init];
UIStoryboard *storyboard = [self storyboard];
OGVideoStreamViewController *questionsController = [storyboard instantiateViewControllerWithIdentifier:@"OGVideoStreamViewController"];
questionsController.isQuestion = YES;
OGVideoStreamViewController *answersController = [storyboard instantiateViewControllerWithIdentifier:@"OGVideoStreamViewController"];
answersController.isQuestion = NO;
OGMatchesViewController *matchesController = [[OGMatchesViewController alloc] initWithNibName:@"OGMatchesViewController" bundle:nil];

questionsController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Questions" image:[UIImage imageNamed:@"Tab Icon - Questions"] tag:0];
answersController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Answers" image:[UIImage imageNamed:@"Tab Icon - Answers"] tag:1];
matchesController.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Inbox" image:[UIImage imageNamed:@"Tab Icon - Inbox"] tag:2];

[tabController setViewControllers:@[questionsController, answersController, matchesController] animated:NO];
tabController.selectedViewController = questionsController;

[[UIApplication sharedApplication] keyWindow].rootViewController = tabController;

Comment: Tip of the Day - *Don't kitchen sink the AppDelegate*
Comment: This code isn't in the App Delegate. This code is in another view controller, which gets triggered after a user logs in.
Comment: Cool. You can try debugging it and see the *event(s)* when the tab bar items become highlighted. I was also interested in setting those 3 images for different control states - ```forState:UIControlStateNormal``` etc. Its an interesting puzzle to solve. Starred it, don't hesitate to share the fix if you solve it yourself.
Comment: What do you mean by events? The only method from `UITabBarControllerDelegate` that I can think of is `tabBarController:didSelectViewController:` but I'm confident it's selecting the correct VC (I've tried calling `[UITabbarController setSelectedViewController:]` and `[UITabbarController setSelectedIndex:]`).
Answer: I've had the same problem and it was due to me calling:
[UIView appearance].tintColor = [UIColor colorWithRed:1.000
                        green:0.793
                         blue:0.236
                        alpha:1.000];

I called it in my AppDelegate, so i could change it to the following:
self.window.tintColor = [UIColor colorWithRed:1.000
                    green:0.793
                     blue:0.236
                    alpha:1.000];


What is the equivalent of "Referential Integrity for CCK" in drupal 7?

Question: Is there a Drupal 7 equivalent for the Referential Integrity for CCK module?
Answer: There is a sandbox project for a D7 port that performs cleanup on cron.
Otherwise drupal supports databases that do not enforce referential integrity, so it has not (to my knowledge) been a core issue.
Comment: hey can i ask another question here too? @triskelion what is cron btw? that experimental project says "Unlike Referential Integrity for CCK, this version is performing the data cleanup at cron run " so can you enlighten me what is cron?
Comment: In the *nix world, maintenance tasks are performed on a schedule by the servers. The daemon is called cron. Drupal also performs site maintenance tasks by a schedule, and those tasks are enabled in modules by a hook_cron function. In other words, the database cleanup would not happen immediately, but on the next scheduled maintenance run.
Comment: ok i get you.. last question swear. what is *nix and what is daemon?
Comment: Unix, linux and other unix clones. And a deamon is a program that runs in the background to provide a service.
Comment: ok thanks. but isnt there a stable module in drupal 7 that do node reference clean ups?
Comment: Not that I am aware of.


AngularJS How to open a modal popup

Question: Hi I am brand new to AngularJS and I can't figure out how to open a modal dialog.  It's making me nuts!  Can anyone please tell me what I'm doing wrong?  My controller code is below:
updated code:
buttonh:
<button class="btn default-btn advancedbtn" ng-click="vm.openModal()">Advanced</button>

 angular.module('crm.ma').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

    $scope.items = ['item1', 'item2', 'item3'];

    $scope.animationsEnabled = true;

    $scope.openModal = function (size) {

        var modalInstance = $modal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'topnav_advancedmodal.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                items: function () {
                    return $scope.items;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

});

plunker link:  http://plnkr.co/edit/MeUnAqQf1FLHMhVJ8cGI?p=catalogue
Comment: Could you create a [plnkr](http://plnkr.co/)
Comment: `$modal` is part of the ui.bootstrap package.  is that included in your project?  i.e. do you have `angular.module('crm.ma', ['ui.bootstrap']);` declared anywhere?
Comment: @Claies it is included in the project.
Comment: @kostbone I've created one here http://plnkr.co/edit/MeUnAqQf1FLHMhVJ8cGI?p=catalogue  I've never used plnkr before so I hope I did it right.  Thank you.
Comment: Remove the `modalInstance.result...` part of your code. It is useful when you need to get a result from a modal, but that's not your case, plus `modalInstance` is not defined in your code, so I guess you have an error with that. Also remove the `size` property from the `$modal.open`, as it's optional and as you didn't pass it in the arguments.
Answer: Check out ngDialog at https://likeastore.github.io/ngDialog/
Dialogs in web applications are bit different than in desktop applications and the edge cases are many. ngDialog does a good job of solving many of these issues in one nice package.
Comment: unfortunately I have to do it this way.  I have to follow an example I already have, but I'm so new to angular that I don't know how to translate what I'm working with.
Answer: angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

  $scope.items = ['item1', 'item2', 'item3'];

  $scope.animationsEnabled = true;

  $scope.open = function (size) {

    var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };

});

Comment: I've copied your code only changing what I needed for my application and it still won't open on a button click.  I updated my code in the question.  Do you know what I am doing wrong?
Comment: copy/paste all your code here for check whats wrong, also you can see more details if open the developer console in your browser. I recommended Chrome Browser.

AngularJS How to open a modal popup


ActionScript 3 - use [brackets] instead of getChildByName

Question: I have a MovieClip inside library, linkaged to MyObject and it contains a textField.
I don't know how I can access this textField without using the getChildByName method.
Apparently, the 3rd section works when object is on stage (without using addChild). But when using addChild I think there has to be some kind of casting; which I don't know how.
var childElement: MyObject = new MyObject();
childElement.name = "theChildElement";
container.addChild(childElement);

btn.addEventListener(MouseEvent.CLICK, changeText);

function changeText(event: MouseEvent): void
{
    var targetBox:MovieClip = container.getChildByName(childElement.name) as MovieClip;
    targetBox.textField.text = "hello";  // THIS WORKS

    // This works too:
    // MovieClip(container.getChildByName("theChildElement"))["textField"].text = "hello"; // THIS WORKS TOO.

    // THIS DOESN'T WORK. why?
    // container["theChildElement"]["textField"].text = "hello";
}

Answer: There is a difference between Symbols created by the Flash IDE, which aggregate other DisplayObjects and programmatically created DisplayObjects.
When a DisplayObject is created in the Flash IDE, it's instance name can be used to resolve the instance as a property - which means it can be accessed via []. The [] can be used to access properties or keys of dynamic declared classes - like MovieClip. This necessary because you'll most likely down cast to MovieClip instead of using the symbol class created by Flash. That is not possible when simply using addChild, addChildAt or setChildAt from the DisplayObjectContainer API.
It is always the save way to access it via getChildByNameand check for null because otherwise your app, website or whatever is doomed for 1009 errors as soon as someone is changing the symbols.
I'd create a bunch of helper methods, like
// not tested
function getChildIn(parent:DisplayObjectContainer, names:Array):DisplayObject {
  var child:DisplayObject, name:String;

  while (names.length > 0) {
    name = names.shift();
    child = parent.getChildByName(name);
    if (!child) {
      // log it
      return null;
    }
    if (names.length == 0) {
      return child;
    }
  }

  // log it
  return null;
}

function getTextFieldIn(parent:DisplayObjectContainer, names:Array):TextField {
  return getChildIn(parent, names) as TextField;
}

function getMovieClipIn(parent:DisplayObjectContainer, names:Array):MovieClip {
  return getChildIn(parent, names) as MovieClip;
}

Answer: Your third method doesn't work because you are trying to call the ChildElement by it's name
without using getChildByName method. On the other hand, you shouldn't call your textField textField, because that's already an actionScript property.
Your should rather call it 'displayText' for example.
For a textField called 'displayText' contained in childElement :
function changeText(event:MouseEvent): void
{
    childElement.displayText.text = "hello";
}

Answer: As confusing as it may seem, instance name, and name are not the same. From your code you should always be able to get to your MC by it's variable name. To get your last like to work you could just use this.
childElement["textField"].text = "hello";


The class $l(F)$ of morphisms which have the left lifting property with respect to $F$ is stable under transfinite compositions.

Question: I am reading Cisinski's Higher Categories and Homotopical Algebra and I am having trouble trying to verify some claims there. My background in category theory is not very solid. I would like some help to understand and prove one of that claims.

Let $i: A \to B$ and $p: X \to Y$ be two morphisms in a category
$\mathcal{C}$. We say that $i$ has the left lifting property with
respect to $p$, or, equivalently, that $p$ has the right lifting
property with respect to $i$, if any commutative square of the form

has a diagonal filler

(i.e. a morphism $h$ such that $hi = a$ and $ph = b$).
A class of morphisms $F$, in a category $\mathcal{C}$, is stable under
transfinite compositions if, for any well ordered set $I$, with initial element $0$, for any functor $X: I \to \mathcal{C}$ such that,
for any element $i \in I$, $i \neq 0$, the colimit $\varinjlim_{j < i} X(j)$ is representable and the induced map
$$\varinjlim_{j < i} X(j) \to X(i)$$ belongs to the class $F$, the colimit $\varinjlim_{i \in I} X(i)$ exists and the canonical morphism $X(0) \to \varinjlim_{i \in I} X(i)$ belongs to $F$ as well.
Proposition: Let $\mathcal{C}$ be a category with a class of morphisms $F$. Then the class $l(F)$ is stable under transfinite compositions.

The above proposition is just a small part of the Proposition 2.1.4 in the book. I was able to prove the other parts, so I am not completely lost. The problem is in this definition of transfinite composition... I know what a colimit is, I know what a well ordered set is, but I am not sure I understood the definition at all. Where does the condition "the colimit $\varinjlim_{j < i} X(j)$ is representable" comes into play? What is the canonical morphism $X(0) \to \varinjlim_{i \in I} X(i)$? Is this one of that morphisms in the definition of cocone? How does the above definition is equivallent to the nLab definition of transfinite composition? How to prove the above Proposition?
Answer: Cisinski means that the colimit exists, in more common terminology for English-speaking mathematicians. (In the Grothendieck school, it is traditional to speak of a colimit as a presheaf, so that it always exists, and the question is whether this presheaf is representable in the starting category.)
Now, as for what the condition says: first, consider the case that $i=i'+1$ is a successor ordinal. Then $\mathrm{colim}_{j<i}X(j)=X(i'),$ and so the condition simply says that the map $X(i')\to X(i)$ is in $F.$ The case in which $i$ is a limit ordinal is the natural way to say what is morally the same thing: for instance, the map $\mathrm{colim}_{i\in\omega} X(i)\to X(\omega)$ is in $F.$ If you're homotopy-theoretically minded you might picture this as the union of a countable chain of cofibrations, all mapping into $X(\omega).$
Yes, the canonical morphism from $X(0)$ to the colimit must be the appropriate leg of the colimiting cocone.
With all this spelled out, the proposition should be easy to prove by transfinite induction.
Comment: I am not homotopy-theoretically minded, but I think I got it now. I have to use the UMP of colimits to inductively draw the red dashed arrows in this figure: https://imgur.com/p6TOa8K
Right?
Comment: Oh, yes, I responded too quickly. This seems to be a small error. For instance if $F$ is the class of isomorphisms then $l(F)$ is all maps, but of course one can't get, say, colimits indexed by $\omega$ in an arbitrary category for free.
Comment: Thank you! Another person answered essentially the same thing. It's comforting to know that the difficulty in proving that wasn't just my fault.
Comment: I'm still having trouble trying to prove that $\varinjlim_{ i \in I} X(i)$ exists when $I$ is a limit ordinal.
Comment: That the colimit exists is an assumption, not something to be proved.
Comment: I thought I could only assume that each colimit $\varinjlim_{j < i} X(j)$, with $i \in I - \{0\}$, was representable. Look at the part "the colimit $\varinjlim_{i \in I} X(i)$ exists and the canonical morphism $X(0) \to \varinjlim_{i \in I} X(i)$ belongs to $F$ as well." I thought this was the conclusion I needed to prove. If the existence of $\varinjlim_{i \in I} X(i)$ was an assumption, then that quote should be  "and the colimit $\varinjlim_{i \in I} X(i)$ exists, then the canonical morphism $X(0) \to \varinjlim_{i \in I} X(i)$ belongs to $F$ as well."


Finding the number of Polysyllables in java

Question: Say I have a String array, I already counted the number of syllables in the array. How would I go about finding the number of Polysyllables in the array? I know I would have to count the number of words with syllables > 1, but I don't know how to go about doing that.
Comment: So... what have you tried? And, which language?
Answer: You need to keep track of the number of syllables in another data structure. You could use a simple int[] to do this, and it could be returned by the function that counts syllables, that you have already created.
String[] myStrings = {"One", "Syllable", "Dog", "Laptop"};
int[] mySyllables = countSyllables(myStrings);
//In the above case, mySyllables = {1, 3, 1, 2};

So once you have counted the number of syllables, and saved the values, you can iterate your mySyllables array, and whenever you encounter a value greater than 1, you know how many polysyllables you have.
int numPoly = 0;
for(int i=0;i<mySyllables.length;i++) {
    if(mySyllables[i] > 1) numPoly++;
}

In the given sample case, the end result is numPoly == 2, being "Syllables" and "Laptop"
Comment: I tried your method but for some reason, it is giving me 0 for the number of polysyllables...
Comment: Trying printing every value in the mySyllables array and making sure that there are values greater than one, otherwise numPoly will always be zero.
Comment: Everything in mySyllables is zero. "int[] mySyllables = countSyllables(myStrings);" is giving me a problem since my code is reading from a URL.
Comment: The countSyllables method you've posted only returns int, not int[]. Change this and then test manually with simple cases to make sure it's working correctly.


What is the difference between extract () function and associatve array in php?

Question: I want to know what is the difference between extract() function  and associative array () function in php. Where do i use this?
$state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA");
extract($state);
echo"\$AS is $AS
\n\$KR is $KR
\n\$OR is $OR
";

instead of this line if i am writting echo "$state[AS]"; then i am getting same result but what is difference ?
Comment: o.O what.. there is no associative array function.. just simply arrays. Whether they're numerically indexed or labelled defines the type of array ..
Comment: The extract function can be called *on* an array (associative arrays will set a variable with the index as the name, and the value of the element as the value of the array). It's probably not a good practice to use `extract()`.
Comment: What do you mean by "where do i use this"? What exactly is "this"?
Answer: Generally I would say don't use extract.
It's usually better to keep all the values inside the array since you can loop an array.
With variables you don't know how many got created with the extraction. Was it only one value in the array or 50?
If it's in the array you can count and loop them, in variables you need to test if each variable is set or not.
Also using extract will overwrite your variables if you are unlucky.
// Some calculations result in a price
$price = 500;

// Now you get an array from user input or json and extract it
$array = ["something" => "here", "price" => 10];
extract($array);

// Extracting overwrites your $price with value 10!
echo $price; // 10

Let's say we use the above scenario again but without the extract.
// Some calculations result in a price
$price = 500;

// Now you get an array from user input or json
$array = ["something" => "here", "price" => 10];

echo $price; // 500
echo $array['price']; // 10

Now we have both the array value and your value.
Nothing is compromised as we are in control of where the values go.
But as soon as you use extract, you really unleash everything and can only hope for the best.
TL/DR;
Don't use extract. If you do need to/want to use it, then only use extract on your own arrays that you have 100% control of.
Answer: I would agree with the answer given by @Andreas, i.e. avoid using extract where you can, as you may end up overwriting your variables. One thing not mentioned in the answer, however, is that you can avoid overwriting your variables with the use of the EXTR_PREFIX_SAME flag.
 $price = 500;
 $quantity = 1;

 $array = ["something" => "here", "price" => 10, "quantity" => 2];
 extract($array, EXTR_PREFIX_SAME, 'new');

 echo $price; // 500
 echo $something; // here
 echo $quantity; // 1
 echo $new_price; // 10
 echo $new_quantity // 2

Of course, with a large array, this may leave you wondering which of the variables, if any, have been allocated the prefix. You could create an array of these variables in order to find out...
print_r(array_filter(get_defined_vars(), function($key) {
        if(substr($key, 0, 4) == 'new_') return 1;
    }, ARRAY_FILTER_USE_KEY));

// output
Array
(
    [new_price] => 10
    [new_quantity] => 2
)

.... or loop through for the same result. Of course, if you were really unlucky, you could still end up overwriting your variables with this technique!
One thing to bear in mind is that extract() will only create or overwrite variables in the current scope. That means you could do the desired work within a local scope.
function getBillsInfo($aboutBill) {
    extract( $aboutBill);
    echo ("I'm " . $firstName); // I'm Bill
}

$firstName = 'Bob';

$aboutBill = [
    'firstName' => 'Bill',
    'surname' => 'Mcgill',
    'job' => 'grill',
    'location' => 'seville',
];

getBillsInfo($aboutBill);

echo '
' , ("I'm still " . $firstName); // I'm still Bob

Ultimately, I do think extract has its place, but you need to be careful with its use.
To answer the question "What is the difference between extract function and associative array in php", directly, is a bit of an apples and oranges scenario. extract is an array function, designed to work on an array. Whereas an associative array is, well, an array (ordered map)!


In which language ABRSM exams are normally taken?

Question: In which language ABRSM exams are taken in countries where the dominant language is not English?
Swiss ABRSM page is all in English, but the dominant language in my Swiss region is German. Can I expect that it will be possible to use German during the music theory exam?
Comment: I'd suggest contacting the board and asking them for a definitive answer. They should be happy to help with queries from potential candidates.
Comment: They do some effort to translate the theory exams in the local languages but I usually don't bother. The main purpose of doing an international music qualification is to get experience in doing music in English
Answer: A quick phone call revealed that you can take the theory exams in German, if you request it at the time of entry. English and German will appear for the questions, but I suspect it's standard German rather than any Swiss/German.


Aplicação Segura

Question: Estou desenvolvendo um sistema que será utilizado no meu trabalho para controle das maquinas, terminei a primeira etapa, agora começou a de testes.
Como na minha maquina eu não utilizo antivírus eu não tive nenhum problema nessa parte, mas ao instalar em uma outra maquina o executável é bloqueado pelo antivírus.

A aplicação monitora o computador e obtêm algumas informações, como ip,acesso ao cmd da maquina,acesso remoto.
Como eu faço para eliminar esse suposto vírus?
Tenho que rever todo o código novamente?
Pois no antivírus da microsoft acusa como Backdoor: Win32/Xiclog.A(Esta ameaça pode dar a um hacker malicioso acesso não autorizado e controle de seu PC.) a ideia do programa é controlar os computadores a distancia.
Answer: Leia o que você mesmo escreveu.

a ideia do programa é controlar os computadores a distancia.

Com mais cuidado agora.

controlar os computadores a distancia.

As suas definições pessoais de vírus não foram atualizadas com sucesso.
O seu programa é feito de partes. Uma delas garante controle irrestrito a uma máquina. O que garante que as demais partes não podem ser usadas para capturar texto de campos de senha em navegadores, por exemplo? Ou procurar por imagens e transmití-las para um servidor qualquer? Ou encriptar arquivos contra a vontade do usuário, e só decriptá-los mediante comando remoto? etc., etc., insira o comportamento do malware da vez aqui.
Daí você pensa em algum programa que realmente permite operar um computador através da rede, como o Team Viewer, ou a própria área de trabalho remota do Windows. Nesses casos você "autentica" o seu programa para utilizar uma conta de usuário, e essa conta deve ser "manipulada" em tempo real. O escopo do que você pode fazer dessa forma é muito limitado, mas por isso mesmo mais seguro. Talvez, para alcançar o seu objetivo, você deva estudar a arquitetura desses programas. Daí você pode fazer algo semelhante. Mas isso não é controle remoto.
Outra ideia mais simples: talvez você possa resolver o seu problema com uma arquitetura cliente-servidor. Ao invés de criar um programa ponta-a-ponta para controle remoto, crie serviços que podem ser instalados localmente nas máquinas e que façam determinadas ações dentro de um escopo limitado. Você pode fazer com que esses serviços atendam a requisições sobre vários protocolos de rede. Você também pode compartimentalizar suas funcionalidades por serviço, assim fica fácil controlar a autorização do que cada um pode fazer. Mas isso ainda não é controle remoto, ok?

Aplicação Segura


Express the feasible solution (3,1) as a convex combination of extreme points

Question: So i am given four extreme points:
$A: (0,0)$
$B: (8,0)$
$C: (2,3)$
$D: (0,1)$
and I need to express the feasible solution $(3,1)$ as a convex combination of extreme points. My professor did the following, he expressed it as:
$(3,1)=a(0,0)+b(8,0)+c(2,3)$
and solved for $a,b,c$
My question is the convex combination not unique and could I have done it as:
$(3,1)=a(0,0)+b(8,0)+c(0,1)$ instead?
Answer: Correct, it's not unique. Two non-collinear vectors in the plane form a basis.
Think of each point as its corresponding vector (from the origin to the point).
So for this representation to be unique, you need to have only 2 distinct points,
e.g. A and B. And then all the convex combinations give you all points on the segment [A,B]. So right, you could have done it your way too.


API gratuita para Histórico climatológico

Question:
Como já expliquei para o Guilherme nos comentários, eu deixo bem claro na minha pergunta que quero um HISTÓRICO climatológico. A pergunta indicada como duplicata NÃO mostra como recuperar HISTÓRICO climatológico. Por favor, tentem ler a pergunta antes de marcar duplicata, é uma falta de respeito marcar duplicata de uma pergunta sem antes ler a mesma.

Olá, estou brincando um pouco com a biblioteca python plotly e gostaria de tentar relacionar alguns dados históricos de previsão do tempo (chuvas, temperatura etc) com um conjunto de dados que já possuo.
Porém ainda não consegui achar nenhuma API que me forneça dados climatológicos históricos de uma cidade ou região de forma gratuita.
Existe alguma API que me forneça isso (dados climatológicos históricos) de forma gratuita?
O formato pode ser json, XML, não importa muito, desde que eu consiga acessar esses dados com Python está ótimo.
EDIT: A questao apontada como duplicata não é sobre historico de previsões do tempo e sim sobre previsões do tempo. O que eu preciso é do historico de previsoes de uma localidade.
Comment: Então o problema não era "pegar" e sim a questão de ser pago -.- podia ter falado antes né? Teria poupado algum tempo de entendimento do pessoal. Tá vou ver se encontro algo e te mando, pode ser? ;)
Comment: Talvez no [site do INMET](http://www.inmet.gov.br/portal/).
Comment: Você leu a parte que escrevi *"basta usar o urllib e um jsonparser"*? A tua pergunta é um pedido de serviço, se não é dup é offtopic. Agora se a dificuldade for no teu código python então o sentido muda e passa a ser on-topic.
Comment: Se você precisa de um **histórico** climático pra determinada região, já que não acha uma API gratuita que te de um histórico, você pode criar uma tabela por exemplo, que todo dia é alimentada usando um cronjob com o clima daquele dia
Comment: Nao entendi direito como usar urllib e jsonparser pra conseguir o historico, nas respostas desse outro topico tem apenas chamadas que retornam previsões do tempo (pode ser que eu tenha sido bem "noob" e nao tenha achado onde ver o historico), se for esse o caso por favor me ilumine!
Comment: Percebi que houve mais uma marcação de duplicata, já li umas 10 vezes esse outro tópico que o @GuilhermeNascimento indicou pra tentar encontrar onde explica a forma de recuperar o HISTÓRICO climatológico mas não encontrei nada. Fica a dúvida se eu sou extremamente "tapado" ou se as pessoas marcam duplicata sem ao menos ler as perguntas.
Comment: Possivel duplicata indica "possivel", não significa que é.
Comment: @GuilhermeNascimento correto, não sei se é possível mas seria legal então desmarcar a questão como duplicata e apagar seu comentário de duplicata, Obrigado.
Comment: Se usar a API que dessa resposta https://pt.stackoverflow.com/a/117122/3635 com urllib (python), vai conseguir facilmente pegar os resultados.
Comment: @GuilhermeNascimento mas de onde vêm esses dados? Como monto uma query no YQL pra pegar a temperatura/humidade do ar de 2015 por exemplo, por lá eu consigo a previsão, assim como consigo pela openweathermap, mas dados históricos eu sinceramente não consigo encontrar. A parte de urllib/jsonparser, até onde eu sei, seria util apenas se eu tivesse os dados, mas eu não tenho e é exatamente isso que eu estou procurando
Comment: Agora de uma pergunta generica vocÊ esta tornando a duvida bem mais complexa, recomendo que edite sua pergunta, pois claramente o que você quer é muito além de indicarem APIs, este site não é para indiciar serviços e etc, se sua duvida é pegar a temperatura de uma data especifica .... PS: o urllib é para baixar os dados da API ;)
Comment: Não foi minha intenção deixar a duvida complexa. O exemplo foi apenas para tentar te ajudar a entender o que eu quero. O foco é: "*Uma API que forneça dados históricos climatológicos*. Como usar a API, como vou recuperar esses dados, isso eu me viro e é questão pra outra pergunta caso eu não consiga. Nesse tópico a única coisa que quero é a bendita API com históricos climatológicos. Isso é bem difícil de achar, se é que existe. Por isso postei aqui, já pesquisei em dezenas de sites e nas comunidades brasileira e gringa do SO, nada fornece o que preciso de forma gratuita.
Comment: Qual api que vc disse que tem os dados mas não consegue pegar?
Comment: openweathermap, é so ir em bulk history ou history, qualquer uma das 2 me serviria, mas nao consigo usar pois é pago e pelo que pesquisei não tem "conta de estudante"
Comment: blza, muito obrigado!
Comment: @MarceloBoni é exatamente isso que eu comecei a fazer, infelizmente vou ter que montar o meu proprio historico se não quiser pagar... E obrigado pela ajuda! To vendo uns negocio sobre aquele django-crontab pra ficar coletando esses dados
Answer: Openweathermap:
"Nosa API é simples, limpa e digratis. Nós oferecemos suporte em alto nível (planos pagos). Para acesso a API, voce precisa criar uma conta para obter um API Key."

Link para o site.
Comment: Então a proprganda é enganosa? No texto inicial da pagina diz que é free e só cobra pelo suporte.
Comment: Eu já usei esse serviço a algum tempo (menos de dois anos) e, sim, era de graça qq acesso, lembro que era meio complexo, mas era **digratis** sim. Devem ter mudado a pouco tempo.
Comment: Obrigado pela resposta @Sidon porem a openweathermap cobra 10 doletas pra fornecer o historico de uma localização :/
Comment: hahaha, se dizem que só cobram pelo suporte é propaganda enganosa sim. A API no geral, pra ver previsões de tempo é grátis sim, mas histórico infelizmente não, dei uma BOA pesquisada já pela internet e achei alguns sites já que fornecem o que eu quero, mas todos são pagos  =/


How to solve ~(P → Q) : P & ~Q by natural deduction?

Question: I'm trying to solve the following by natural deduction:
~(P → Q) : P & ~Q
It's a trivial problem if identities are used, as can be seen by the following:

{1}      1.   ~(P → Q)                    Prem.
{1}      2.   ~(~P ∨ Q)                   1 Mat. Impl.
{1}      3.   ~~P & ~Q                    2 De Morgan's
{1}      4.   P & ~Q                      3 DNE

Starting from step 2 of the previous proof, it's also fairly straightforward to reach a conclusion using natural deduction; i.e. starting from ~(~P ∨ Q), which is an identity of ~(P → Q):
~(~P ∨ Q) :  P & ~Q

{1}      1.   ~(~P ∨ Q)                   Prem.
{2}      2.   ~P                          Assum.
{2}      3.   ~P ∨ Q                      2 ∨I
{1,2}    4.   ~(~P ∨ Q) & (~P ∨ Q)        1,3 &I
{1}      5.   P                           2,4 RAA
{6}      6.   Q                           Assum.
{6}      7.   ~P ∨ Q                      6 ∨I
{1,6}    8.   ~(~P ∨ Q) & (~P ∨ Q)        1,7 &I
{1}      9.   ~Q                          6,8 RAA
{1}      10.  P & ~Q                      5,9 &I

I also found that it's fairly easy to conclude ~Q:

{1}      1.   ~(P → Q)                    Prem.
{2}      2.   Q                           Assum.
{3}      3.   P                           Assum.
{2,3}    4.   P & Q                       2,3 &I
{2,3}    5.   Q                           4 &E
{2}      6.   P → Q                       3,5 CP
{1,2}    7.   ~(P → Q) & (P → Q)          1,6 &I
{1}      8.   ~Q                          2,7 RAA
...
{1,2}    12.  P & ~Q

In spite of how easy it looks, I can't figure out how to do it. I believe it can be done in 12 steps. Thanks!
Comment: I hope [this](http://math.stackexchange.com/a/61781/94817) truth table helps.
Answer: We need Double Negation and I need 13 steps:
1) $\lnot (P \to Q)$ --- premise
2) $Q$ --- assumed [a]
3) $P \to Q$ --- from 2) by $\to$I
4) $\bot$ --- from 1) and 3)
5) $\lnot Q$ --- from 2) and 4), discharging [a]
6) $\lnot P$ --- assumed [b]
7) $P$ --- assumed [c]
8) $\bot$ --- form 6) and 7)
9) $Q$ --- from 8) by $\bot$E: $\bot \vdash \varphi$
10) $P \to Q$ --- from 7) and 9) by $\to$I, discharging [c]
11) $\bot$ --- from 1) and 10)
12) $P$ --- from 6) and 11) by Double Negation, discharging [b]

13) $P \land \lnot Q$ --- from 5) and 12) by $\land$I.
Answer: Although some identities such as material implication are not defined as inference rules in natural deduction systems, one can always derive the desired result when needed. It is useful to know how to do that.
Consider the following proof in a Fitch-style proof checker:

Although you were able to reach line 10 in one move using equivalences it took lines 2-9 for me to derive the same result.  What is important is that I was able to derive the result. What is useful to know is that one can convert from conditionals to disjunctions and negations if one has to.
Note that this subproof would have been shorter if I had something like "double negative introduction", but all I have is double negative elimination (DNE) which I used on line 13. That meant that I had to derive line 6 from a subproof on lines 4 and 5 rather than reference an inference rule.
Still, what is important is that I was able to derive those results. The natural deduction system is complete. It can derive every formula that is true.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


Why does Paired t-test show not significant?

Question: I have a two-column and three-row paired data (data3)
138.2   13.64
64.00  12.76
81.36  14.90

I conducted the following analysis using R:
shapiro.test(data3[,1] - data3[,2])
#    Shapiro-Wilk normality test
#
#data:  data3[, 1] - data3[, 2]
#
#W = 0.89766, p-value = 0.3781

t.test(data3[,1], data3[,2], paired = T)

#   Paired t-test
#data:  data3[, 1] and data3[, 2]
#t = 3.6148, df = 2, p-value = 0.06873
#alternative hypothesis: true difference in means is not equal to 0
#95 percent confidence interval:
# -15.36643 176.87310
#
#sample estimates:
#mean of the differences
#           80.75333

I am wondering why the paired t-test shows no significant difference but when looking at the data we can see the first column > the second column.
Comment: Just as a rough sense .... consider if each comparison was a coin toss. Would you be stunned by three heads in three tosses?
Comment: Paired t-test after log transforming yields p=0.01 though. CC @MartijnWeterings.
Comment: https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks
Comment: The decrease values -124.56  -51.24 and -66.46 are all negative (p=0.125 for a sign test) but their variance/spread is high making the parametric test not much better (your calculated value p=0.06873). --- The p-value of 0.0687 is actually relatively low. Your result is only occurring once every fourteen times. This **conservative** rule of low p-values as boundary is possible because, if there is an effect then you would be unlikely to not get a low p-value. However your sample size is such low that you have little power and also with a considerable effect size you would get high p-values.
Comment: @amoeba Yes, previous knowledge about what kind of process is going one helps.
Answer: There are two parts to your analysis. Let's look at them one at a time.
(1) Shapiro-Wilk test for normality. Failure to reject does not mean that
the data are normal.
In particular, you look at three differences, but $n = 3$ is too small
a sample size for the test to have a useful probability of detecting
non-normality, if it exists. So there is no particular reason to believe
that the differences are from a normal population. Thus there is no
particular reason to suppose that results from a t test would be accurate.
An exponential population is very far from normal,
yet in 10,000 sets of $n = 3$ from $\mathsf{Exp}(1),$ the Shapiro-Wilk test
rejected the null hypothesis of normality only 748 times. That is to say,
the power of the test against the alternative that data are exponential
is only about 7.5%. (Simulation in R.)
set.seed(701);  m = 10^4
pv = replicate(m, shapiro.test(rexp(3))$p.val)
mean(pv < .05)
[1] 0.0748

(2) Paired test. It is true that the differences for the three pairs average about 81. This may seem a large value, but it is not a statistically significant value.
You have correctly shown that the (questionable) t test does not find significance at the 5% level.
Moreover, because there are only three differences, no reasonable rank-based, sign test, or permutation test can show a P-value for a two-sided
alternative smaller than 0.25. For a one-sided test (that column 1 is bigger than
column 2) no P-value can be smaller than 0.125.
To achieve a P-value below 5% with any of these tests (one-sided), you would need $n = 5$ differences (all positive or all negative).
d = c( -124.56,  -51.24,  -66.46)
wilcox.test(d)

        Wilcoxon signed rank test

data:  d
V = 0, p-value = 0.25
alternative hypothesis: true location is not equal to 0

Comment: FWIW paired t-test after log transforming yields p=0.01.
Answer: Because your sample size is very small and the variance of the differences is very big. And because you evaluated the size of the difference using p values, which are heavily influenced by sample size.
Answer: Yes there is a difference, but is the difference large enough to say that the population means are different?
As with every statistical test that relies on P-values for interpretation it is important to understand what a p-value is. Remember that we are trying to make inferences about the population based on a sample.
a P-value is : "the chance that a given estimate would be found in the sample if the H0 would be true in the population".
The H0 for a t-test is that the means of the respective populations are the same.
That paired t-test calculates that p-value. So the chance of finding these means in the sample, when the population means are the same is 0.068.
Assuming that you decided upon a significance threshold of p<0.05 the conclusion of this test is that the difference found in your sample is coincidence.
Think of it in this way. You want to test if younger siblings are systematically shorter in height than their older brother and sisters. To eliminate age you only question adults.
You take a sample from three families and end up finding something like this:
younger  older
192      198
175      176
186      190

Clearly in the sample the older siblings are taller right? But could they have come from the same population mean? Ie could the mean in the population of younger siblings and older siblings be the same number?
Given the variance and means in the (very small) sample the t-test shows a non significant difference. If the t-test is non-significant you conclude that it could.


How to add javascript library that does not need a module, but is required by modules?

Question: I have a JavaScript library written for my project. It is just that - helper library without configuration. I don't like the idea of empty .module file loading each time. On the other hand, I need it to be versioned and I need to be able to require it in other modules, with version specification. Libraries API looks like a bit of overkill as my script is from the ground written for Drupal and is no way "external" - and using empty .module file would be easier and faster anyway.
So, what's the best practice to include JS-only code?
How to include a JavaScript library, with CSS, in Drupal 7 without using a module? is about JavaScript needed by theme, so it looks similar but is unrelated to my question.
Answer: A module is really the only appropriate place for something like that; Drupal doesn't provide any way of making a module dependant on a JS library. You can only make a module dependant on another module, so if you want to enforce a dependancy to your JS code you'll have to create a module to contain/reference it.
If you're worried about having an empty module file, don't be...to formalise your library and describe it to the system properly, most likely you should be implementing the core hook_library() anyway. Then your dependant modules can simply call
drupal_add_library('mymodule', 'library');

to add your library. Putting the JS library files themselves into the sites/all/libraries folder, and referring to them from hook_library(), would probably be the best solution.


Different ways to calculate Rsquared after Regression with complex survey data in R

Question: I'm struggling to find out the differences or the "right way" to calculate R² after regression with complex survey data in R. My data includes missings and though I know this is not really state of the art, I chose a complete cases only approach. The data is also clustered. In a very related question How to run svy: regress in R or get R-squared for complex survey data, I found out about two ways to calculate R². One proposed by Thomas Lumley author of the survey package (Version 1) and another one proposed by Innate Imunity is the way (Version 2). I also found a third one using the long approach calculating mean sum of squares and residual sum of squares by inspecting the summ function from jtools (Version 3).
While Version 2 and 3 yield the same result Version 1 is a little bit different as you can see in the following example. Maybe these are different Pseudo-R²? Help and/or clarification would be very much appreciated. Thank you very much!
packages, data and regression
library(survey)

airqual <- data.frame(airquality)

airqual_cplx <- svydesign(ids=~Month, data = airqual, weights = ~Wind)

svy_reg <- svyglm(Temp ~ Solar.R + Ozone, airqual_cplx)
sum_reg <- summary(svy_reg)

Version 1: Thomas Lumley
R²=0.4903556
temp_var <- svyvar(~Temp, design=svy_reg$survey.design)[[1]]
disp_reg <- sum_reg$dispersion[[1]]
Rsq1 <- 1-disp_reg/temp_var
print(Rsq1)

Version 2: Innate Imunity is the way
R²=0.489439
deviance.null <- svy_reg$null.deviance
deviance.model <- svy_reg$deviance
Rsq2 <- 1-deviance.model/deviance.null
print(Rsq2)

Version 3: summ in jtools
R²=0.489439
r <- svy_reg$residuals
f <- svy_reg$fitted.values
w <- svy_reg$weights
m <- sum(w * f/sum(w))
mss <-  sum(w * (f - m)^2)
rss <- sum(w * r^2)
Rsq3 <- mss/(mss + rss)
print(Rsq3)

Answer: These are all estimating the same thing, they just use slightly  different estimators.
The survey package works from the characterisation of $1-R^2$ as the residual variance divided by the marginal variance, with both of these being well-defined population quantities that are then estimated.
The other approach is to work from the characterisation of $1-R^2$ as the residual sum of squares divided by the total sum of squares. Again, these can be defined as population quantities and then estimated.
I have an aesthetic preference for treating the variances (which are independent of sample size and population size) as the basic quantities, but it really doesn't matter. The differences will be in $n$ vs $n-1$ vs $n-p$ scaling somewhere in the formulas


Early stopping vs cross validation

Question: I'm currently using early stopping in my work to prevent over fitting. Specifically those taken form Early Stopping But When?.
I'm now wanting to compare to other classification algorithms where it appears that 10 fold cross validation is widely used.
However I'm confused about whether cross validation is a method for preventing over fitting or selecting good parameters. (or maybe this is one and the same?). I'm also confused whether early stopping methods and cross validation can be used in place of one another or in combination.
So the question is: what is the relationship between early stopping and cross validation?
Answer: Cross Validation is a method for estimating the generalisation accuracy of a supervised learning algorithm.
Early stopping is a method for avoiding overfitting and requires a method to assess the relationship between the generalisation accuracy of the learned model and the training accuracy.
So you could use cross validation to replace the validation set, mentioned in the paper you cite,  within an early stopping framework. Ten fold cross validation for instance would be more accurate than using a single validation set, and would normally be a better  estimate of generalisation error.
So to summarise, cross validation is a generalisation accuracy measure which could be used as part of an early stopping framework.
Comment: That all makes sense, cheers. But form what I can tell 10 found cross validation seems to be used to choose the parameters for a given method, not to stop early when using that method. So I think I must still be missing something.
Comment: @AndyT Maybe the thing to focus on here is generalisation estimation. Both parameter selection and early stopping require a good estimator of generalisation error. N fold cross validation is one such estimator. There are others, such as repeated hold out and bootstrapping, or a simple validation set. What you are trying to do in both cases, parameter selection and early stopping is assess how the model will perform on unseen data so you can choose a good model. To do this, in both cases you use a generalisation estimator. Does that help  ?
Comment: Yes that's clear. Thank you very much for your time! It's much appreciated.
Comment: @AndyT No trouble, I hope your project goes well!
Answer: In addition to the two generalization approaches you mention, there are many others.

adding regularization terms in your loss (cost) function that minimize the number and magnitude of your nonzero model parameters
randomly dropping (zeroing out) some portion of the weights/parameters in your model with each training epoch
adding a layer of stochastic nodes in your model (e.g., sampling from the "probabilities" given by the outputs of logistic functions)

Many of these approaches (including your cross-validation and early-stopping approaches) can be combined together to maximize model performance on unseen data (generalization performance).
One note on the early-stopping approach. For neural nets, Geoffrey Hinton recommends stopping training when the test set accuracy reaches its maximum (test set loss, excluding regularization terms, is at a minimum). One additional "tweak" to Hinton's approach is to not stop if the test_set accuracy is better (loss is smaller) than for your training set, even if the test set accuracy has stopped improving (test set loss has stopped declining). This is unlikely to gain you more than one epoch of training, but sometimes that can help a bit, especially for small test_sets. Don't do this for extremely small test sets (smaller than a representative sample set, like is sometimes used in K-folds training and cross-validation).
Answer: you cannot use early stopping and K-fold cross validation in combination. because the early stopping select best model from validation set, the performance needs to be verified by test set. but in K-fold cross validation, there is not test set, if you using early stopping to select best model from validation set, and it will verified again in validation set. the K-fold cross validation is getting the average performance (measured by accuracy) of best model, and it is meanless.
Comment: The way to do it would be 1) Train for some number of iterations on every fold (e.g. up to a given maximum). 2) Compute the average validation set error (across folds) as a function of the number of iterations. 3) Select the number of iterations that minimizes the average validation set error.
Comment: Here is my solution:1. shuffle all data, 2. do 10-fold by sklearn, kfold = StratifiedKFold(n_splits=10, shuffle=False) 3, set callback: callbacks_list = [EarlyStopping(monitor='val_loss', patience=50, verbose=0, mode='min')] 4. choose  best model by early stopping.  history = model.fit(X[train], Y[train], epochs=250, batch_size=512, verbose=1 ,callbacks=callbacks_list,  validation_split=0.1,shuffle=False) set another auto split validation set from X[train],Y[train].  5. test the performance by X[test]andY[test] : scores = model.evaluate(X[test], Y[test], verbose=0)
Comment: The number of training iterations can be treated as a hyperparameter, and selected using cross validation, just as any other hyperparameter. One could reasonably call this "early stopping".
Comment: when using early stopping in K fold cross validation, the number of epoch is fixed by validation set and different for each split. This will make the network choose best model in each splits, which is not stand for the average performance.

Early stopping vs cross validation


Do descending drop chord voicings in the blues work?

Question: Here are two well known descending chord patterns:
Diatonic seventh chords.

Sequence of dominant seventh chords.

The voice leading is smooth in both and basically each voice just steps down to the next closest chord tone.
If I do something similar, but on a blue chord pattern I7 IV7 I7 I7 | IV7..., I get this...

Does anyone play voice leading like that in blues, does it work?
Parts of it obviously work. The I7 IV7 moves are just segments of the sequence of dominant seventh chords and the I7 I7 change is just an exchange of voices. IV7 I7 is then the odd move.
For a "classical" ear IVb7/4/3 Ib7/4/2 doesn't make sense, they would be called irregular resolutions, but all the voices - except the "alto" -  move by descending step so it is relatively smooth.
I'm stuck between thinking it sounds OK - blues style isn't concerned with classical concepts of irregular resolution even if it does sometimes conform to those concepts - or worrying that no one plays blues this way so idiomatically it's bad blues playing.
Personally, when I play this way - descending or ascending - the root position and 2nd inversion chords (fifth in bass) sound stable and the 1st and 3rd inversions sound unstable. The classical voice leading would basically resolve the chord thirds up by step and the sevenths down by step. With this pattern I don't follow those conventions and just keep moving in the same descending/ascending direction to the next closest chord tone. If I do that and start and end the whole 12 bar blues on either root position or 2nd inversion chords, it seems OK to me.
In terms of rhythm I'm just playing the whole chord on the beat or simple broken patterns between the two hands, just vampings.
Comment: It seems that there is parallel harmony on the top voices which I would think is not perfered in any style.  But the basic chord structure is very common on guitar so I'd think it's possible someone uses it.
Comment: which part are you talking about? there are parallel tritones all over
Comment: I misread the top three notes in the progression in 36.  It clearly is not parallel though the movement is steady descending in all voices.  I am not sure how anything in the blues matches what a "classical ear" expects.
Comment: Depending on the particulars blues progression can be perfectly compatible with a classical sense of harmony/voice leading. Like `| Ⅰ | Ⅰ | Ⅰ | Ⅰ7 | Ⅳ... `
Comment: Depends on what you call blues versus a cleansed version on the same.  It is common to play all chords as 7ths and there is plenty of chromaticism in that choice but that doesn't mean that you'll find it following the standard practices in most harmony work books.
Comment: I played your arrangement of chords and it is very nice.  Not sure there is a literal answer to the question "does anyone play..." as that is very specific.  Are you asking about 'this' or the stacking of intervals in general?  As I stated, guitarists use similar voicings, it felt natural in my hand to play it.  Doesn't mean that Joe Pass recorded it though.
Comment: @ggcg, I made a few edits in my question. My concern is not the vertical stack - the voicings - but the linear the voice leading.
Comment: Linear voice leading works if that's where you want to go.  It sound great in some places.  I would suspect that players use a combination of approaches.  The type of movement you have posted sound familiar and I would think that some solo guitarists have used it.
Answer: It sounds kind of OK, but it is not in the blues idiom to my ears. One reason is that you are filling in all the elements of the chords. In jazz/blues playing it is really common to omit the fifth from a lot of these chords, and start from what is called a "shell" voicing, which contains the root, third and seventh (whether dominant or maj7) and then possibly add various colour tones (9, b9, #9, 11, #11, 13 ...) and so on. Quite often this results in "clusters" of notes that are quite close together - out of context it might be quite dissonant, but all the skill lies in making it sound good in context of course. (That often comes down to voice leading through the sequences of chords.) That's not to say that the fifth is never played but it is frequently omitted - often making space for these "colour tones".
Of course "anybody" is a whole lot of people - but no, I can't think of any pianists associated with blues who typically play the kind of voicings you have written.
Comment: "the kind of voicings you have written" are you talking about just the third "blues" example, not the first two sequences?
Comment: i am talking about all of them.
Comment: I'll post a new version of my question. All the attention is on the vertical aspect of the voicings instead of the voice leading.


How to Include External JavaScript Libraries In An Angular 4 TypeScript

Question: I try implemented my angular project this js lib but it's doesn't work. How to implement 3rd party js libs Angular 4 project and how to use in my component?
Answer: You use it just like how they say in the instructions. In project directory:
npm install drift-zoom --save

then add this to the component you want to use it in:
import Drift from 'drift-zoom';

then whenever you want to call it, just use:
const draft = new Draft('whatever params you need');

Comment: I try this and more its return all time `new Drift` requires a DOM element as its first argument.
Comment: Yes. You need to pass it a DOM element. That's how drift works. I don't understand your question.
Comment: [link](https://stackblitz.com/edit/angular-x1gmkp) i create this sample its works here but my app inside component doestn work. I set it DOM element @ViewChild or document.querySelector but its not accept it. Return all time "TypeError: `new Drift` requires a DOM element as its first argument." this error.


É possível inserir, no mesmo DropdownList, dois resultados? C#

Question:
No meu código, existe uma página para o cadastro de vendas onde é necessário digitar algumas informações como por exemplo qual cliente fez a compra.

Controller Venda:
// GET: Vendas/Create
        [Authorize]
        public ActionResult Create()
        {
            ViewBag.ClienteId = new SelectList(db.Clientes, "Id", "CPF");
            ViewBag.ProdutoId = new SelectList(db.Produtos, "Id", "Nome");
            return View();
        }

        // POST: Vendas/Create
        // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
        // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Data,Fiado,QtdVendida,ValorVenda,ClienteId,ProdutoId")] Venda venda)
        {
            if (ModelState.IsValid)
            {
                db.Vendas.Add(venda);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ClienteId = new SelectList(db.Clientes, "Id", "CPF", venda.ClienteId);
            ViewBag.ProdutoId = new SelectList(db.Produtos, "Id", "Nome", venda.ProdutoId);
            logger.Info("Criou uma nova Venda.");
            return View(venda);
        }

View Create:

Cliente

                @Html.DropDownList("ClienteId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ClienteId, "", new { @class = "text-danger" })

Para isso eu uso um DropDownList que exibe os CPF's dos clientes já cadastrados, porém eu queria saber se nas opções dos CPF's também é possível exibir os nomes dos respectivos clientes ao lado do CPF.
Answer: Sim, basta você compor o atributo Text da SelectList, digamos que o nome do Cliente esteja na propriedade Nome..
var clientesDropList = db.Clientes
                        .Select(x => new { Id = x.Id, Descricao = $"{x.CPF} - {x.Nome}" })
                        .ToList();

ViewBag.ClienteId = new SelectList(clientesDropList, "Id", "Descricao", venda.ClienteId);

Comment: @João Conseguiu resolver?


Integrate the expression

Question: There is a task given, but I am not sure if it is right, because I don't have a clue on how to solve it. Even tried to put it on wolfram to get any result, but no chance. Would appreciate your help:
$$\int \sin^42\cos^22x\ \mathrm dx$$
Comment: Wouldn't the integrand be $\sin^42x \cos^22x$?
Comment: But you notice that your expression is pretty ambiguous without parentheses?
Comment: If it is $\sin^4(2\cos^2(2x))$, then I doubt there is an elementary antiderivative.
Comment: I wrote it down as it is in the task =( Seems to be that there is a mistake in task
Comment: Nope, the powers are 4 and 2 respectively and there is 2 coefficient for cosine and for x, as written above.
Comment: yes, I do understand that. That's what made me confusing as well. And that's why I have posted it here =(
Answer: Assuming that the integral is:

$$\int\sin^4 (2\color{red}x)\cos^2(2x)dx$$

Hint:
Substitute $t=2x$ and $dt=2dx$
$$=\frac 1 2\int \sin^4 t \cos^2 t dt$$
Write as:
$$=\frac 1 2\int \sin^4 t(1-\sin^2 t)dt$$
$$=-\frac 1 2\int \sin^6 t dt +\frac 1 2\int\sin^4 t dt$$
Using the reduction formula:
$$=\frac{1}{12}\sin^5 t\cos t+\frac{1}{12}\sin^4 t dt$$
Reduction formula again:
$$-\frac{1}{48}\sin^3 t\cos t+\frac{1}{12}\sin^5t\cos t+\frac{1}{16}\int \sin^2 t dt$$
Now use the fact that
$\color{green}{\sin^2 t=\frac 1 2-\frac 1 2 \cos(2t)}$ and now it is easy to finish.
Answer: Interpreting as:
$$\int (\sin^4 2)(\cos^2 2x)dx$$
Than $\sin^4 2=a \approx 0.6836343..$ is a constant and the integral becomes
$$\int a\cos^2 2xdx$$
that can be integrated noting that $$\cos^2 2x=\frac{1}{2}(\cos 4x-1)$$
and substituting $4x=t$

Integrate the expression


How to get id from text

Question: I have value text:
<code>{
  "4384": {
    "idRoomSv": 4384,
    "NumRoom": 2,
    "RoomId": 269
  }
}
</code>
I want to get RoomId. It is return :269.
Can you help me? Thank very much!
Comment: What have you tried? We can't help you if we don't see your code.
Comment: It is a string in a field as: {"4384":{"idRoomSv":4384,"NumRoom":2,"RoomId":269}} . I want get value of RoomId. True rerult is: 269. Are you understand?
Comment: I using Mysql Database?
Answer: If you have a recent version of MariaDB or MySQL, you can use the JSON_EXTRACT function.
Edit: try on your sql client the code below
<code>SET @json = '{
  "4384": {
    "idRoomSv": 4384,
    "NumRoom": 2,
    "RoomId": 269
  }
}';
SELECT JSON_EXTRACT(@json, '$.*.RoomId');
</code>
And the result is :
<code>    JSON_EXTRACT(@json, '$.*.RoomId')
1   [269]
</code>
The JSON_EXTRACT function accepts a JSON document for the firtst parameter. The second parameter is a JSONPath expression :

$ : is the root element
* : wildcard = all elements regardless their names
RoomId : value of that field
Comment: i using Mysql.I think it is usefull

How to get id from text


debian mirror : Hash Sum mismatch

Question: I have a mirror server that I maintain in school.
$ uname -a
Linux CSE-Cloud01 4.0.0-1-amd64 #1 SMP Debian 4.0.2-1 (2015-05-11) x86_64 GNU/Linux
$ sudo apt-get update
......
 W: Failed to fetch http:// mirror.cs.nchu.edu.tw/debian/dists/jessie/main/source/Sources  Hash Sum mismatch
    W: Failed to fetch http:// mirror.cs.nchu.edu.tw/debian/dists/jessie/main/binary-amd64/Packages  Hash Sum mismatch

W: Failed to fetch http:// mirror.cs.nchu.edu.tw/debian/dists/jessie/non-free/binary-amd64/Packages Hash Sum mismatch

W: Failed to fetch http:// mirror.cs.nchu.edu.tw/debian/dists/jessie/main/i18n/Translation-en  Hash Sum mismatch

E: Some index files failed to download. They have been ignored, or old ones used instead.

In mirror itself or some of my machines, It failed in the end.(some work properly.) I had tried to do the below commands that recommended, and won't work
$ apt-get clean
$ rm -rf /var/cache/apt/*
$ rm -rf /var/lib/apt/lists/*
$ apt-get update

I can't find other solution on the internet. Did anyone know how to solve this problem?
Comment: This solved my issue
Answer: If deleting /var/lib/apt/lists/* does not work...
(esp. if you're behind a proxy), fix "Hash Sum Mismatch" like this:
Create file
/etc/apt/apt.conf.d/99fixbadproxy
with this content
Acquire::http::Pipeline-Depth 0;
Acquire::http::No-Cache true;
Acquire::BrokenProxy    true;

See also here
Comment: Removing .../lists/* solved it for me.
Answer: I had a similar problem and it seemed to be a problem on the mirror.
As stated here remove the files "InRelease" on the server and try again.

In the /debian/dists/jessie directory there was a file called InRelease. It had a date several months back from the other files (which were mostly dated today's date).
Answer: I this case the problem always is the difference between the hashsum stated in the InRelease and Release files located in dist/[name-of-your-distro]/ folder.
This files are used to verify that others like Packages.xz hasn't been altered. When the hashsum mismatch you get the error. Unfortunately rehashing and writing the new value is not enough, because you will also need to sing both *Release files with a private key that you don't own... a real tedious job.
In my case I solved the problem (which in the first place was just use the local downloaded mirror) by removing the release files:
rm dist/[name-of-your-distro]/*Release*

and adding a trusted switch to the line corresponding to this repo in APT sources:
deb [trusted=yes] file:/path/to/your/local/mirror/ubuntu xenial main

Note the [trusted=yes]
Hope this helps, and even help me in the future :)
Answer: Following helped me (considering you are su)

apt-get clean
apt-get autoclean
apt-get remove
apt-get autoremove
Answer: I had such a problem while upgrading from wheezy to jessie. The solution was to temporarily remove xz-utils package. Wheezy can't manage .xz package lists because of the old version of apt.
apt-get remove xz-utils
apt-get update
apt-get upgrade
apt-get install xz-utils

Answer: Try removing all network connections other than the internet connection before trying to update or install files.
I just resolved this issue now. I was using wifi to connect to the internet, but also had an ethernet cable attached to a switch which was connected to another computer. I removed the ethernet cable and the hash mismatch error disappeared. It is possible that the local area network was preventing the laptop from connecting to the internet because I wasnt able to even ping google. The browser would not open websites either.

debian mirror : Hash Sum mismatch


Implicit Differentiation Misunderstanding.

Question: Say we are given the unit circle, defined by all real numbers $x,y$ such that $x^2+y^2=1$. Now, if one tried to solve explicitly for $y$, one would get that $y=\pm{\sqrt{1-x^2}}$ and this is obviously not a function, so traditional calculus techniques cannot be used. As $x^2+y^2=1$ defines our curve, we can take the derivative of all terms with respect to $x$ to get that $2x+2y\frac{dy}{dx}=0$, as by the chain rule $\frac{d(y^2)}{dx}=\frac{d(y^2)}{dy}\frac{dy}{dx}$, and one can therefore do some algebraic manipulation to get that $\frac{dy}{dx}=-\frac{x}{y}$. However, I have a few questions:
1) I thought the whole point was that $y$ is not a function, and so $\frac{dy}{dx}$ does not make sense as this notation is defined only when $y$ is a function (or am I wrong in this regard?)
2) Why are we allowed to take the derivative with respect to $x$ on both sides of the equation, but not for example to solve $x^2=1$ to get $2x=0$ which would produce the wrong answer that $x=0$ (my inkling tells me that this is because $x^2=1$ is not an identity but an equation, but I just want to check up on this...)
Comment: $y=\pm{\sqrt{1-x^2}}$ is a collection of 2 functions.
Comment: @LoveInvariants Therefore.... and what about for more complex implicit curves
Comment: They too are are collection of functions because function is defined only for linear $y$ i.e. one value of $y$ for a value of $x$
Comment: $y=\pm{\sqrt{1-x^2}}$ isn't a function but $y=\sqrt{1-x^2}$ and $y=-\sqrt{1-x^2}$ are functions.
Answer: Good question!
1) You're right that the equation $x^2+y^2=1$ does not define $y$ as a function of $x$ globally.  However, if you zoom in on certain points of the curve, what you see does look like the graph of a function.  Because zooming in will allow you to ignore that "other" branch of the circle.
The fancy way to say this is that for most points on the curve, we can find a neighborhood of the point for which the intersection of the curve and the neighborhood is the graph of a function.  And the derivative of that function is what's predicted by the implicit differentiation process.
But not necessarily every point on the curve.  For instance, on the circle near $(-1,0)$, no amount of zooming in will make that look the like the graph of a function.  And it's no coincidence that the tangent line is vertical there.
I have some slides with pictures up on this topic from several years ago.
2) The equations $x^2+y^2=1$ and $x^2=1$ are much different than they appear.  The first equation relates two variables $x$ and $y$: for any value of $x$ we can find ("solve for") all related values of $y$.
The second equation is not a relation among variables; there's only one variable after all.  It's an equation describing specific, unknown numbers $x$.  We can only differentiate functions (or implicitly differentiate certain relations).  Since $x^2=1$ is not an equation of functions, differentiating doesn't apply.  To give an even more ludicrous example:  Suppose we have the equation $2x=4$.  If we differentiate both sides, we get $2=0$, a contradiction, which would indicate there was no solution at all.  Of course this is wrong since $x=2$ satisfies the equation.
Comment: Thank you for your answer and powerpoint. So why is it exactly that you can't take the derivative of both sides for $x^2=1$, however you can for an identity of functions.
Comment: @Daniele1234: I expanded on the second point; hope it helps.  If not, you might consider asking a separate question about it.  It probably deserves to be answered on its own.
Comment: @MatthewLeingang can we say like when we differentiate function (you given above) ,then our domain of interest in only those nbhd where it is indeed a function? i.e in our case it will not be diff. at (1.0) and (-1,0)? am i right ?
Comment: @MEETPATEL I don't usually think of "domain of interest" in the context of implicitly defined functions. But you're right that there's no way to treat the curve as the graph of a differentiable function of $x$ at $(1,0)$ and $(-1,0)$.
Comment: @MatthewLeingang can u explain what exactly going on when differentiate such a equation whose solution set does not represent any function !
Comment: @MEETPATEL I think you should ask a separate question in order to state it at the level of detail which will attract good answers. Feel free to link to that question from here and I'll take a look.
Answer: To be differentiable, an object doesn't have to strictly be a function. There are a large family of curves and other objects which are not functions but can be approximated by tangent lines(or planes, etc).
As for your second question, it is not true in general that if we have an equality in an equation, this will hold true when the equation is differentiated. (This is due to the fact that differentiation 'gets rid' of information one can say).
Comment: @Daniele1234 $\frac{\text d}{\text dx}[f(x)+C] = \frac{\text d}{\text dx}[f(x)]$ for any constant $C$. In other words, $f'(x) = g'(x)$ does not necessarily mean that $f(x) = g(x)$. Thus, some distinguishing information is lost in the process of differentiation.
Comment: What do you mean by "differentiation gets rid of information" - that is, why can't one take the derivative of both sides of an equation