How do I zoom in on a location using mapkit in swift 2 (xcode)

Question: I am trying to zoom into a point on the map when a user inputs an address, for example, one infinite loop. I want it to zoom in to the location to the street level but I cannot for the love of God get it to zoom in. I have tried messing with the region, the span, etc. but no luck. Here is what my code looks like (I have nothing in the view did load func)... you will see i have commented out some code because I tried it and nothing happened.
my code and here is what the output is on the simulator the output on simulator
Answer: Why do you define func in geocodeAddressString closure?
How about the following code?
    geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
        if (error != nil) {
            print("Error", error)
        }

        if let placemark = placemarks?.first {
            let span = MKCoordinateSpan(latitudeDelta: 0.0001, longitudeDelta: 0.0001)
            let coordinate = placemark.location!.coordinate
            let region = MKCoordinateRegion(center: coordinate, span: span)
            self.mapView.setRegion(region, animated: true)
        }
    })

Result:
Answer:
Use var for span and region rather than let.
You need to get rid of the self in front of Map.setRegion
Also try a bigger number for the span coordinates something like 0.4 or 0.5
or you could still use 0.0001 that doesn't really matter.

span = MKCoordinateSpanMake(0.4,0.4)
var region = MKCoordinateRegion(center: **location variable goes in here** , span = span )
Map.setRegion(region, animated: true)

Comment: Thanks for your help, the method works but for some reason (and It could just be my simulator) but when it zooms in to the location, all I see are yellow squares ( as if the actual map is not loaded yet.)  - any advice?
Comment: I  noticed that sometimes the simulator just takes a really long time to  load I had the same issue with the WatchKit;  it took me at least 10 minutes for the simulator to load. It's probably an IOS 9 bug
Comment: Thanks, just had to wait a bit! great help everyone


Can we use two convolutional layers without a activation layer in middle of them?

Question: Recently I trained a model for more than 100,000+ images. I forgot to use a activation layer in between two convolutional layers, but model trained better with good accuracy (99%). So I want to know is it a bad approach or can we do like this?
Comment: Did you use pooling between them? Or downsample using striding?
Comment: @jonnor I didn't use pooling between them. I used as follows                                      `model.add(Conv2D(16, (3, 3), padding='same', input_shape=input_size))
 model.add(Conv2D(32, (3, 3), padding='same'))`
Answer: Since convolution is a linear operator, two consecutive convolutional layers can be realized by a single convolutional layer if there is no non-linear activation layer between them. Then, it is trivial to train one extra layer which has no positive effect on the representational power of your model.
Comment: They should eventually converge to the (approximately) same solution unless it overfits. However, you should note that adding/eliminating a layer changes the model architecture and affect the whole model parameters through backpropagation during training. Then, an identical training phase might lead to different results.
Comment: I thought same thing, but there was a improvement in accuracy than using just one conv layer.
Comment: There I didn't notice overfitting. As you explained, this improvement can be caused by the change of the model architecture and the weights.
Answer: Stacking convolutions is equivalent to convolution, but with different filter size. It might be that the effectively bigger filter gives you different results, but there exists appropriately sized conv layer that is equivalent wiith two conv layers (if the boundary conditions are right)
Comment: Nobody stacks convolutional layers without nonlinearities because of what I mentioned. To get the feeling of convolutions I encourage you to check out [guide to convolutional arithmetic](https://github.com/vdumoulin/conv_arithmetic), find appropriate equations and do the math (you might want to check out some NN course that calculates number of weights of Conv layers to be sure).
Comment: can you share a good article to read about stacking convolutions (if it is possible)? In my model I have used  `model.add(Conv2D(16, (3, 3), padding='same', input_shape=input_size))
model.add(Conv2D(32, (3, 3), padding='same'))`  Also I want to know what is the effect of following layers  `  model.add(Conv2D(64, (3, 3), padding='same'))  model.add(Conv2D(64, (3, 3), padding='same'))`
Comment: yes @jakub. By mistake, I haven't used non-linearity layer between Conv layers, but it gave a good accuracy with good predictions. That is why, I thought whether this gives some effect to the model, because when I retrain the model after adding non-linearity layer, it didn't show better performance than previous. Thank you again for the guide, I follow this today it self.


Prove that $\mathbb R_N [X]$ with $\langle \cdot, \cdot \rangle$ is a Hilbert space

Question: Good night, I'm trying to solve this problem about Hilbert space.

Let $\mathbb R_N [X]$ be the vector space of polynomials whose their degrees are less than or equal to $N$. On $\mathbb R_N [X]$, we define the inner product $\langle \cdot, \cdot \rangle$ by $$\langle p,q \rangle = \int_0^1 p(x)q(x) \, \mathrm{d}x, \quad p,q \in \mathbb R_N [X]$$ Prove that $\mathbb R_N [X]$ with $\langle \cdot, \cdot \rangle$ is a Hilbert space.

My attempt:
For $p \in \mathbb R_N [X]$, the induced norm is $\| \cdot \|$ such that $$\| p \| = \sqrt {\int_0^1 p^2(x) \, \mathrm{d}x }$$
Let $(p_n)_{n \in \mathbb N}$ is a Cauchy sequence in $\mathbb R_N [X]$ where $p_n = \sum_{k=0}^N p^{n}_k X^k$ for all $n \in \mathbb N$. It follows that $$\forall \epsilon >0, \exists M \in \mathbb N,\forall n,m> M:\| p_n - p_m \| = \sqrt {\int_0^1 \left (\sum_{k=0}^N (p^{n}_k - p^{m}_k) X^k \right)^2 \, \mathrm{d}x}  < \epsilon$$

I guess that $(p_k^n)_{n \in \mathbb N}$ is Cauchy sequence in $\mathbb R$ for all $i = \overline{0,N}$, but I fail to get the desired result.
Could you please shed me some light? Thank you so much!
Comment: More generally, every finite-dimensional inner product space is complete, hence a Hilbert space.  Indeed, a $d$-dimensional inner product space is isometrically isomorphic to $\mathbb{R}^d$ with its standard Euclidean inner product, which of course is complete.  So it is a little bit silly to go around trying to prove that a *specific* finite-dimensional inner product space is complete...
Comment: Out of curiosity: is it important that the term $p(x)q(x)$ can have a degree of at most $2N>N$?
Comment: Hi @mrtaurho, I'm sorry, but I'm unable to understand your comment. Because $\operatorname{deg} (p), \operatorname{deg} (q) \le N$, $\operatorname{deg} (pq) \le 2N$ :)).
Comment: Yes, sure. I was just confused that the space is defined as having only polynomials of degree $\leqslant N$ but the defintion of the inner product enables one to get higher degree polynomials as an intermediate. I do not think this is of any importance while now thinking about it. (BTW, this has nothing to do with the solution to the problem).
Answer: Let $\|P\|_{\infty}=\underset{x\in[0,N]}{\sup}{|P(x)|}$. First notice that if $P\in\mathbb{R}_N[X]$, then
$$ P=\sum_{k=0}^N{P(k)L_k} $$
where $L_i(j)=\delta_{i,j}$ for all $0\leqslant i,j\leqslant N$. Thus if $\|P_n-P_m\|_{\infty}<\varepsilon$, in particular $|P_n(i)-P_m(i)|\leqslant \|P_n-P_m\|_{\infty}<\varepsilon$ and $(P_n(i))_{n\in\mathbb{N}}$ is a Cauchy sequence and thus converges toward $\ell_i$. Finally
 $$ \forall n\in\mathbb{N},\,\left\|P_n-\sum_{k=0}^N{\ell_k L_k}\right\|_{\infty}\leqslant \sum_{k=0}^N{|P_n(k)-\ell_k|\|L_k\|_{\infty}}\underset{n\rightarrow +\infty}{\longrightarrow}0 $$
and $$ \lim\limits_{n\rightarrow +\infty}P_n=\sum_{k=0}^N{\ell_k L_k}\in\mathbb{R}_N[X] $$
Since $\dim\mathbb{R}_N[X]<+\infty$, this works with $\|\cdot\|$ instead of $\|\cdot\|_{\infty}$ as well.
Comment: How does the interval $[0,N]$ enter the discussion? The polynomials are of degree at most $N$ and defined in $[0,1]$. Also, what is the point of presenting an argument for a different norm without proving that it suffices for the relevant norm?
Comment: The reason I chose the norm $\|\cdot\|_{\infty}$ is to have the inequality $|P_n(i)-P_m(i)|\leqslant\|P_n-P_m\|_{\infty}$ for all $i\in[\![0,N]\!]$ which is not necessary true with $\|\cdot\|$. Moreover, I defined $\|\cdot\|_{\infty}$ with the $\sup$ on $[0,N]$ because I want that the inequality $|P_n(i)-P_m(i)|\leqslant\|P_n-P_m\|_{\infty}$ holds for all $i\in[0,N]\cap\mathbb{N}$,
any interval can define this norm, but this would not necessary give me the desired inequality.


Why the geometrical mean of the slope of the two regression lines can be a measures linear correlation between two variables?

Question: The Pearson correlation coefficient is the geometrical mean of the slopes of the two regression lines. For me it is difficult to understand how a geometrical mean of the slope of the two regression lines can be a measure of the linear correlation between two variables X and Y.
I found this paper fantastic, Bravais-Pearson and Spearman correlation coefficients: meaning, test of hypothesis and confidence interval by Artusi and coll., in explaining the Pearson coefficient, but I have difficulties in doing the last deduction.
Answer: Let's regress $Y$ on $X$ and write $b_{0x} + b_{1x} x$ for the regression line, where $b_{1x}$ is the slope. Then Pearson correlation coefficient is $r = b_{1x} \frac{s_x}{s_y}$,  $s_x$ and $s_y$ being the standard deviations of $X$ and $Y$, respectively. If, on the contrary, we regress $X$ on $Y$, the regression line is defined by $b_{0y} + b_{1y} y$, thus $r = b_{1y} \frac{s_y}{s_x}$.
Then it follows that $r^2 = b_{1x} b_{1y}$, i.e. $r = \sqrt{b_{1x} b_{1y}}$, which is the geometric mean of the two slopes.
Answer: This is an interesting article with different interpretation of the corr. coeff.
https://www.stat.berkeley.edu/~rabbee/correlation.pdf
This does not give an answer to your question, but maybe you can find other interpretation
Comment: Thank you for your answer. But also there I cannot find the last deduction that I have asked


Build Form with Single Table Inheritance

Question: I have my entity Article and one single table inheritance like this :
/**
 * Article
 *
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="PM\PlatformBundle\Repository\ArticleRepository")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="media", type="string")
 * @ORM\DiscriminatorMap({"article" = "Article", "movie" = "Movie", "image" = "Image", "text" = "Text"})
 */
class Article
{
    protected $id;
    protected $title;
    protected $description;
    protected $author;
    //other attributes and setters getters
}

class Image extends Article
{
    private $path;
    //getter setter
}

 class Movie extends Article
{
    private $url;
    //getter setter
}

So my article's object type is either Image or movie or text only. Ok now I would like build a form wherein users can post a new article : in this form, the user has to choice between tree type (3 radios button) : image OR movie OR text only and of course the other fields : title and description. How I can do that ? Because with the command

php bin/console doctrine:generate:form myBundle:Article

The form rendered is :
class ArticleType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title',          TextType::class)
            ->add('description',    TextareaType::class)
            ->add('save',           SubmitType::class);
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PM\PlatformBundle\Entity\Article'
        ));
    }
}

I don't know the way to implement my STI relation in this form. Because I have not field in my Article entity/object for the type (only in my table).
I have to add a Custom ChoiceType() field but it require a attribute.
When I try to add this in the form :

        ->add('path',           SearchType::class)
        ->add('url',            UrlType::class)

I got this error :
Neither the property "path" nor one of the methods "getPath()", "path()", "isPath()", "hasPath()", "__get()" exist and have public access in class "PM\PlatformBundle\Entity\Article".
Because I have create an instance of Article, not an instance of Image or Movie. Initially I created a STI thinking a new instance of Article would allow me also to define the "type" of article. But not ? Right ?
Comment: Add `mapped:false` option for form fields that shouldn't be mapped to attribute of underlying object (Article). Then you will have to find a way to handle this form properly on your own.
Comment: Hm I don't know if it's a good idea to use mapped:false. What should I do to recover path and url properly, because they really exists in my database and in my object (but via inheritance) ?
Comment: But you don't have `Image`/`Movie` object there, do you? No, you don't. So how should it work in your opinion (never mind if it's possible or not)?
Comment: Yes I have, look my first post above ! I have one class Movie and one Image (extends article).
Comment: You have a **class**, not an **object instance** passed to the form.
Comment: Yes but an object instance "article" which contains 2 others classes ? Not ?
Comment: Not. Why would it. You better get some basics of OOP first before diving info more advanced topics.
Answer: I agree with dragoste in the comments: you can't expect the form to deduce by himself the type of class you want to instantiate based on a value.
Roughly, Image and Movie are the same type as Article, but an Article is not an Image and/or a Movie.
You will have to check that manually. You can do that server side like explained in the comments, with a field using mapped: false to determine the type of entity you need to instantiate, or client side with javascript by using three forms (one for a movie, one for an article, one for an image) and by displaying the correct one based on your radio button.

Edit: How to display the correct form in JS?
I created a JSFiddle to show you how you can do this using jQuery : https://jsfiddle.net/61gc6v16/
With jQuery documentation, you should be able to quickly understand what this sample do, and to adapt it to your needs. :)
Comment: Okay thank for your explaination! I would like to build this form system using javascript. But I have not the knowledge on JS or Jquery for this. It requires a lot of JS code?
Comment: I edited my answer. :) JavaScript is a good way to enhance your users experience and, in the same time, it can prevent you some headaches on how to handle things server side. You should take a look at it, as it is almost indispensable for web developers now, back or front. jQuery is a good start to catch the logic behind the language as it is pretty easy to learn and has great functionnalities. Nevertheless, keep in mind that knowing jQuery is not knowing JavaScript, and that there's a lot more frameworks that can provide you a lot more wonderful things. :)
Answer: You will have to make three forms (one for an Article, one for a Movie and one for an Image). Then, in your controller, you have to options to deal with them:

Either you use one action to handle the three forms (you can check wich one is submitted by using $form->isSubmitted())
You create one action by form, and set the form action URL for each form to the correct controller.

Finally, in your template, you encapsulate your forms in a div, and use the example in my previous post.
{% extends "CoreBundle::layout.html.twig" %}

{% block title %}{{ parent() }}{% endblock %}

{% block btn_scrollspy %}
{% endblock %}

{% block bundle_body %}

            <input type="radio" name="form-selector" value="article-form"> Article
            <input type="radio" name="form-selector" value="movie-form"> Movie
            <input type="radio" name="form-selector" value="image-form"> Image

            {{ form(articleForm) }}

            {{ form(movieForm) }}

            {{ form(imageForm) }}

{% endblock %}

Comment: Can you explain me more precisly how do "one action by form, and set the form action URL for each form to the correct controller." ? Because I built 3 forms like you say and used bootstrap Toggelable option for view (replace your JS code for hide/show the correct form). It works great, but I can not make the system: one action by form because initially I have one route for one controller for one view and now I have 3 actions for 3 route for ONE view.
Comment: It's explained in the link in my answer how to define the action (=> URL which will be called when you submit your form) for your form. So in your forms, you just have to set the route that matches the right controller.
Answer: @Boulzy I did this and it works:
    class ArticleController extends Controller
    {
        public function addAction(Request $request)
        {
            $form1 = $this->get('form.factory')->create(TextOnlyType::class);
            $form2 = $this->get('form.factory')->create(ImageType::class);
            $form3 = $this->get('form.factory')->create(MovieType::class);
            return $this->render('PMPlatformBundle:Article:add.html.twig', array(
                'ArticleTextform' => $form1->createView(),
                'ArticleImageform' => $form2->createView(),
                'ArticleMovieform' => $form3->createView(),
            ));
        }

        public function addArticleTextAction(Request $request)
        {
            $ArticleText = new TextOnly;
            $form = $this->get('form.factory')->create(TextOnlyType::class, $ArticleText);
            if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
                $ArticleText->setAuthor(5);
                $ArticleText->setLikes(0);
                $em = $this->getDoctrine()->getManager();
                $em->persist($ArticleText);
                $em->flush();

                $request->getSession()->getFlashBag()->add('notice', 'Annonce bien enregistrée.');

                $listComments = $ArticleText->getComments();
                return $this->render('PMPlatformBundle:Article:view.html.twig', array(
                    'article' => $ArticleText,
                    'listComments' => $listComments
                ));
            }
            return $this->render('PMPlatformBundle:Article:add.html.twig', array(
                'form' => $form->createView(),
            ));
        }

        public function addArticleImageAction(Request $request)
        {
           //the same system as TextOnly
        }

        public function addArticleMovieAction(Request $request)
        {
           //the same system as TextOnly
        }
}

(I override action directly in my template. With POST method.)
addAction is my contoller which is called by route for display the view of three forms. As you can see this code works as long as there is no error on submitted form. Because, in this case (when error occured when a form is submitted) each controller needs to return the initial view with the 3 forms. How I can do that ?
Comment: Take a look at these documentations, pick the one that seems the most interesting to you: http://symfony.com/doc/current/controller/forwarding.html, https://symfony.com/doc/current/controller.html#redirecting. I'm glad that I can help, but you know I'm not going to code your entire website, right? I mean, trying, failing, trying again, doing mistakes and persisting are an immortant part of the learning process. You should try more solutions, do more research before comming here asking for help. You will learn better and faster this way.


From SAS to R - what are "must" packages for reporting

Question: One big advantage of SAS over R is arguably its ability to produce quite complex reports with few statements; think of PROC SUMMARY or PROC TABULATE for instance.
My heart goes to R because of its openness and vibrant community. But I must admit that SAS's PROCS are quite powerful out-of-the-box. To partially address those issues I wrote an R package titled summarytools which provides ways to generate decent looking and translatable (thanks to pander, Pandoc implemented in R) simple reports (frequencies, univariate stats, codebook, for the essential part) to various formats like RTF, pdf, and markdown.
However, even with the use of by() to stratify the stats (be it frequencies or univariate numerical stats), I feel I'm still miles away from generating as flexible and complete tables such as with PROC TABULATE or PROC MEANS. So my question is: what R packages do you find are "musts" for needs of extracting essential stats from dataframes, splitting on this variable and filtering on that other one. I hope this is not judged as too broad a question; I have made my homework and tried finding the answer to this question before posting here. I'm sure there are some really really well-made packages that address those issues, and I simply haven't seen them around ... yet.
Comment: I believe SAS reports are inferior to Rs, you just need to find the correct packages and functions to use. I use packages tableone, Hmisc, sjPlot for these tasks.
Comment: I like the sjPlot approach a lot since it gives absolutely beautiful results without having to go through additional steps.
Answer: The problem with R is that there are so many ways to construct great reports, and so many R packages that are helpful for this task.  One approach, though getting out of date, is shown in http://biostat.app.vumc.org/wiki/pub/Main/StatReport/summary.pdf . Note that some of the functions there have been updated as shown in http://hbiostat.org/R/Hmisc [and really take note of the tabulr function]. That approach revolves around $\LaTeX$, and I believe you'll find that for producing advanced tables (includes ones containing micrographics and footnotes), $\LaTeX$ has many advantages over the markdown-pandoc approach.
But I believe that we should replace almost all tables with graphics.  The new R greport ("graphical report") and hreport ("html report") packages takes the philosophy that graphics should be used for the main presentation, and graphs should be hyperlinked to supporting tables that appear in an appendix to the pdf report.  See http://hbiostat.org/r. These packages use new functions in the Hmisc package for graphing categorical data (i.e., translating tables to plots) and for showing whole distributions of continuous variables.
Comment: I'll look into `greport`, thanks. The all-graphics avenue seems like a promising one indeed. I also found that `gplots`, `sjPlot` (as mentionned by @Adam Robinson) and `gridExtra` all provide functions that generate graphic tables.
Answer: It seems like reporting and filtering/splitting data by variables are two orthogonal tasks. And people usually use different packages for those.
For managing the data there are few really popular packages: dplyr and data.table.
For reporting tables one package that stands out for me is stargazer
Here are some demonstrations: http://cran.r-project.org/web/packages/stargazer/vignettes/stargazer.pdf
It covers both latex and html (and ASCII, but haven't used that).
I have never used SAS so I don't know if this will cover all the functionality you wanted.
Comment: I am quite aware of the existing tools to manipulate data. I'll look into stargazer, thanks for the suggestion.
Comment: Stargazer is nice, but i prefer Tableone because it provides similar functionality for regression results (ShowRegTable function) but also baseline tables (CreateTableOne function). I've sometimes obtained somewhat different confidence intervals in stargazer, as compared to package used for calulating point estimates. Its nice though that it provides AIC, observations used etc...
Comment: I haven't used tableone, but after a quick look it seems to be more about getting tables themselves, while stargazer is more about exporting those tables to html/latex with predefined styles. It might be possible to use tableone for obtaining the table and stargazer for exporting it to documents. like `stargazer(ShowRegTable(obj))`
Comment: As Frank put it, there are so many possible ways to achieve great things with R. I'm still thinking the ascii + markdown avenue has a lot to offer for little investment. But I appreciate your input and will continue experimenting.
Answer: In 2020 the reporter package was released, which operates much like proc report.  You get the data and statistics you want using other R packages, and then send the resulting data frame into reporter.  Like this:
library(reporter)

# Create temporary path
tmp <- file.path(tempdir(), "example3.pdf")

# Read in prepared data
df <- read.table(header = TRUE, text = '
      var     label        A             B
      "ampg"   "N"          "19"          "13"
      "ampg"   "Mean"       "18.8 (6.5)"  "22.0 (4.9)"
      "ampg"   "Median"     "16.4"        "21.4"
      "ampg"   "Q1 - Q3"    "15.1 - 21.2" "19.2 - 22.8"
      "ampg"   "Range"      "10.4 - 33.9" "14.7 - 32.4"
      "cyl"    "8 Cylinder" "10 ( 52.6%)" "4 ( 30.8%)"
      "cyl"    "6 Cylinder" "4 ( 21.1%)"  "3 ( 23.1%)"
      "cyl"    "4 Cylinder" "5 ( 26.3%)"  "6 ( 46.2%)"')

# Create table
tbl <- create_table(df, first_row_blank = TRUE) %>%
  stub(c("var", "label")) %>%
  define(var, blank_after = TRUE, label_row = TRUE,
         format = c(ampg = "Miles Per Gallon", cyl = "Cylinders")) %>%
  define(label, indent = .25) %>%
  define(A, label = "Group A", align = "center", n = 19) %>%
  define(B, label = "Group B", align = "center", n = 13)

# Create report and add content
rpt <- create_report(tmp, orientation = "portrait", output_type = "PDF") %>%
  page_header(left = "Client: Motor Trend", right = "Study: Cars") %>%
  titles("Table 1.0", "MTCARS Summary Table") %>%
  add_content(tbl) %>%
  footnotes("* Motor Trend, 1974") %>%
  page_footer(left = Sys.time(),
              center = "Confidential",
              right = "Page [pg] of [tpg]")

# Write out report
write_report(rpt)

The report can be output in text, RTF, or PDF.  Here is the PDF version:

The advantage of this package is that you can create almost any kind of report.  It will take more work than table1 or stargazer.  But since it only generates the report, and doesn't try to generate the statistics, you are free to use any R statistical package.  So more work, but more freedom.


How would I go about figuring out which set is equal to A∖(B∖C)?

Question: How would I go about figuring which set between C∖(A∪B), (B∖A)∪(C∖A), (A∖C)∪(B∖C) and (A∖B)∪(A∩C) is equivalent to A∖(B∖C)? I've already attempted to create a venn diagram for all of these sets however none of them were equivalent to A∖(B∖C) leaving me confused.
Comment: Easy way to eliminate the other options is to take $B=C$ then the first $3$ options are not equal to $A$ so the 4th is the only possibility.
Answer: $$x\in A\backslash(B\backslash C)\iff$$
$$x\in A \wedge x\notin (B\backslash C)\iff$$
$$x\in A \wedge (x\notin B \vee x\in C)\iff$$
$$(x\in A\wedge x\notin B) \vee (x\in A\wedge x\in C)\iff$$
$$x\in (A\backslash B) \vee x\in A\cap C \iff$$
$$x\in (A\backslash B ) \cup A\cap C$$
thus
$$A\backslash (B\backslash C)=(A\backslash B) \cup ( A\cap C)$$
So, the last answer is the correct one.
Answer: The fourth option works. The others don't.
You got 4 possible answers. $C\backslash (A\cup B)$,
$(B\backslash A)\cup (C\backslash A)$, $(A\backslash C)\cup (B\backslash C)$ and $(A\backslash B)\cup (A\cap C)$ and you want to see which one is $S=A\backslash (B\backslash C)$. The set $S$ is clearly a subset of $A$. So the first three options don't work. The fourth option works . Indeed, if $x$ is in $A\backslash B$ then $x$ is in $S$ and if $x\in A\cap C$, then $x\in S$. So $(A\backslash B)\cup (A\cap C)\subseteq S$. Now if $x\in S$ then it is in $A$. If it  is not in $A\backslash B$, then it is in $A\cap B$. But it is not in $B\backslash C$. So it must be in $A\cap C$. So $S\subseteq (A\backslash B)\cup (A\cap C)$.


How to get the id using alpine @click

Question: I have this url tag

<a id="day-{{$index+1}}"
  @click="console.log($event.target.getAttribute('id'))"

              Day {{$index+1}}

but if I click on the url I get "undefined" because it will try to log the child element id, I want to get the "a" element id
Answer: Assuming your {{$index+1}} is server side code.
You do not need to do a getAttribute() on the $event.target ...
You are looking for the .parentNode
<a id="day-{{$index+1}}"
  @click="console.log($event.target.parentNode.id)"

              Day {{$index+1}}

I find it useful to console.log the entire object and then look at the details of the object in the console to find the "attributes" I'm looking for.

How to get the id using alpine @click


Como funcionam módulos locais em Go?

Question: Vi nesta pergunta que é possível definir módulos locais em Go usando o GOPATH. No entanto, na solução da referida pergunta, não se utiliza o arquivo go.mod Para que serve esse arquivo? Existe uma forma de importar pacotes definidos dentro de uma pasta sem precisar adicionar o código fonte no GOPATH?
Answer: Para criar um módulo, basta usar:
go mod init github.com/seunome/seumodulo

Isso criará o go.mod. Suponho que faça um push desse pacote contra o github.com/seunome/seumodulo, você poderá pegar esse pacote de lá, futuramente.
Note: você pode ter vários pacotes dentro de um único módulo, então ao criar novos módulos você deve ter uma boa razão para fazer isso. Você não precisa criar um módulo para cada pacote. Pessoalmente, eu só crio módulos quando pretendo compartilha-lo, ou reutilizar em outros projetos.

Então, vamos supor que você tenha o meuprojeto que quer usar o seumodulo: primeiro o meuprojeto também deve ser um módulo, ou seja, também use:
go mod init github.com/seunome/meuprojeto

Para consumir o "meumodulo" criado anteriormente, você pode simplesmente usar:
go get github.com/seunome/seumodulo

Esse comando deve ser executado dentro da pasta que há o go.mod, se não vai dar errado. Dessa forma, o seumodulo estará disponível para uso dentro do meuprojeto.

Se o seu pacote estiver em outra pasta, localmente armazenado, você pode usar o replace no go.mod:
replace github.com/seunome/seumodulo => ../caminho/para/o/seumodulo

Dessa forma, ao invés de obter e usar a informação do repositório do GitHub, você usará a da pasta especificada. Isso é útil caso esteja fazendo trabalhado num branch/fork para o seumodulo.

Se os eu repositório for privado, você pode usar algo como:
set GOPROXY=https://proxy.golang.org,direct
set GOPRIVATE=github.com/seunome/*

Dessa forma, conseguirá dar o go get num repositório privado.
Answer: A solução da pergunta está correta e funciona mesmo nas versões mais recentes de Go. No entanto, desde a versão 1.11 é possível usar um gerenciador de módulos que faz com que seja possível definir pacotes dentro de uma pasta em particular, sem recorrer ao GOPATH.
Digamos, por exemplo, que você quer criar um módulo chamado mymath para definir operações matemáticas personalizadas. Para isso, crie um novo diretório com o nome do módulo, e navegue até ele:
mkdir mymath
cd mymath

Para iniciar o módulo use:
go mod init mymath

Esse comando irá criar um arquivo chamado go.mod.
Agora você pode começar a criar os pacotes. Como exemplo, vamos definir power como um pacote para operações envolvendo expoentes. Para isso criamos um arquivos chamado operations.go (esse nome não é importante) dentro de um subdiretório chamado power:
package power

func Power2(number int) int {
    return number*number
}

Para testar que nosso pacote está funcionando, basta criar um arquivo (digamos, main.go) na raiz do diretório mymath:
package main

import (
    "fmt"
    "mymath/power"
)

func main() {
    fmt.Println(power.Power2(9))
}

Para confirmar que a importação funciona rode:
go run main.go

81

Como funcionam módulos locais em Go?


IntelliJ does not refresh Spring autoconfigurations in multi-module tests when running all tests

Question: I have a multi-module Maven project with three modules A,B,C, all of them are Spring-Boot modules.

B is an autoconfiguration class, uses A. It has a conditional on a certain bean.
C is also an autoconfiguration class, uses A as well, it doesn't have any conditionals because it's a very small module, and if you put it in your pom, you want the autoconfiguration.

When running the tests:

mvn clean install works and everything passes.
When I run the JUnit tests of each individual module from Intellij, everything also passes.

The problem is that when I try to run all the tests from IntelliJ, module A (the one that does not depend on anything) fails because it claims it cannot find a bean that module C needs! I can't even exclude the autoconfiguration because module A has no dependency on C so it doesn't know the class.
Anything that I am missing regarding how IntelliJ loads the context when you have autoconfigurations?
Comment: What run configuration do you use? What is the exact error? Could be related to how the classpath is configured. Normally the IDE uses the classpath of the module specified in Run/Debug Configurations | **Use classpath of module** of JUnit Run Configuration (if you use JUnit Configuration).
Comment: This sounds like https://youtrack.jetbrains.com/issue/IDEA-222014 report.
Answer: Answering my own question for posterity. This is a partial answer that assumes that all your modules share the same root package. In my case, all the modules share a.b.c where the first module's package is a.b.c.first, the second module is a.b.c.second and so on. If you have a better solution I'll happily change the accepted answer.
The problem, as suspected, is how you define the test configuration. Since this is a multi-module project, and I want all the tests to run, there are two ways of defining it:
The problematic way: Defining a pattern on the entire project. This solution is described in this StackOverflow answer.

Running this configuration will cause the problems described in the question - unrelated auto-configurations of dependencies the module doesn't have will start to fail and therefore the tests will fail as well.
The way that works: This way works under the said assumption that all modules share the same package. Create a new Run Configuration as follows:

Test kind: All in package
Package: The share root package of all your modules, e.g. a.b.c in the example I gave in the beginning of this answer.
Search for tests: In whole project

This will run all your tests with the correct auto-configurations.


How to add classes to a specific bean w/ display suite template

Question: On the website home page that I'm working on, we have 4 call-to-actions.
Below is the DS template file which is used when rendering each of them:
<?php

/**
* @file
* Display Suite 2 column template.
*/
?>

<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-2col <?php print $classes;?> cta-body clearfix" style="background: #<?php print $field_bg_colour[0]['value'] ?>">

<?php if (isset($title_suffix['contextual_links'])): ?>
<?php print render($title_suffix['contextual_links']); ?>
<?php endif; ?>

<?php if (isset($field_more_link)): ?>
  <a href="<?php print $field_more_link[0]['url']; ?>">
<?php endif; ?>

  <<?php print $left_wrapper ?> class="group-left<?php print $left_classes; ?>">
    <?php print $left; ?>
  </<?php print $left_wrapper ?>>

  <<?php print $right_wrapper ?> class="group-right<?php print $right_classes; ?>">

<?php print $title ?>

      <?php print $right; ?>

  </<?php print $right_wrapper ?>>

<?php if (isset($field_more_link)): ?>

<?php endif; ?>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

Currently I'm adding a margin-right to each of these, but would like to remove the margin-right on the even number call-to-actions - so my layout works.
Is there any way I can add an odd/even zebra class or a better way to do this?
Many thanks
Comment: You might want to check out, Clive: http://drupal.org/project/bean
Comment: I've been racking my brains and come up with nothing...what's a 'bean'?!
Answer: A friend helped me solve this one. All I needed was the following PHP as a container class.
<?php print $zebra; ?>

I can now style the .odd containers!
Thanks all


How do I handle categorical dependent variables with low level percentages in multinomial logistic regression?

Question: I have a categorical dependent variable that involves four clusters of positions. In descriptive analysis, I noticed that first cluster covered about 5% of the participants, second 6%, third 60%, and fourth 29%. I have four continuous independent variables and I am thinking of using multinomial logistic regression.
Do you think that low percentages in the first two clusters would be a problem? Should I omit the first two and turn the model into a binary logistic regression model predicting the probability of belonging to either the third or fourth cluster?
Answer: It's not so much the percentage of participants as the number that is important. The rule of thumb is that you want 10 people in the smallest class per independent variable. So, with 4 IVs, you want at least 40 people in cluster 1 and 40 in cluster 2.
Whether you should combine clusters is really a substantive matter. Does it make sense to combine them?  Whether you should omit clusters is also a substantive issue: Do you want to distinguish between clusters 3 and 4? Would that be interesting?


php how to store monday to friday of the next 6 months begin from tomorrow in an array

Question: I am making a page to let the clients choose a date for an appointment, so I need to build a list of the dates like this :

always begin from tomorrow, end by 6 months
always from Mondy to Saturday, no Sunday
the day of the week need to be in chinese, like "Monday" is "星期一", but the timezone is in France

Here is the php
date_default_timezone_set('Europe/Paris');

$tomorrow = date("Y年m月d日 l", time() + 86400);
$end = date("Y年m月d日 l", time() + 86400 * 7); // just 7 days for a try
$interval = new DateInterval('P1D');

$daterange = new DatePeriod($tomorrow, $interval, $end);

foreach ($daterange as $date) {
    echo $date . '
';
}

This code is not working.
I need to build an array, which store all the dates of next 6 months, begin from tomorrow, without Sunday, the days need to be in chinese and the timezone needs to be in Europe, is that possible?
Answer: I think strtotime and array_push is what you are looking for. Try this:
$curDate = date('Y-m-d', strtotime('+1 day'));
$endDate = date('Y-m-d', strtotime('+6 months +1 day'));

$myArr = array();
while ($endDate >= $curDate) {
    if (date('w', strtotime($curDate)) !== '0') array_push($myArr, $curDate);
    $curDate = date('Y-m-d', strtotime($curDate . " +1 days"));
}

var_dump($myArr);

For the Options, create an array from sunday to saturday.
$weekdays = array('Sunday', ..., 'Saturday');
echo date('Y/m/d', strtotime($curDate)) . ' ' . $weekdays[date('w', strtotime($curDate))];

Comment: It's done! I add weekdays every time it push a date in $myArr, now I have what I want as in the first image !
Comment: your code works well, except the weekdays, I do a `for` to loop $myArr to `echo` in the `` of `` tag, in this case, `$curDate` is the final date + 1, it' a Wensday, so it gives a fixed 3 to `$weekdays`, I have the correct dates but always Wensday, how to give the `$weekdays` the correct index?


Em PHP, qual a melhor maneira para imprimir uma variável através de uma função?

Question: Vamos supor que tenho a seguinte função:
private function teste()
{
    return 'teste';
}

Para que eu imprima na tela, eu poderia simplesmente utilizar:
echo $this->teste();

Porém em alguns casos eu vejo que primeiro atribuem a uma variavel e somente após isso imprimem, da seguinte forma:
$variavel = $this->teste();
echo $variavel;

Criar uma copia(variável) desnecessária do resultado da função não seria desperdício de processamento e memória?
Em quais casos devemos utilizar diretamente e atribuindo a uma variável?
Comment: A sua função `teste` não retorna nada, e mesmo que se retornasse por exemplo a string 'teste', a variavel de dentro da função logo ia ser liberada da memória assim que a função acabasse, consequentemente não teria problema com desperdicio de memória.
Comment: Acabei me confundindo. O correto é dar um return e não echo na função teste.
Answer: private function teste()
{
    echo 'teste';
}

Esse método apenas imprime algo não retorna valor, para a seguinte linha fazer sentido
$variavel = $this->teste();

Você deve alterar o método teste para a seguinte forma
private function teste()
{
    return 'teste';
}

E em relação ao desperdício de memória você estaria enganado pois assim que o método ou função chegar ao primeiro return ou no final do seu corpo, todos as variaveis que estão no seu escopo seriam liberados da memória.
Variaveis declaradas dentro de uma função são chamadas de variáveis locais da função. Para saber mais pesquise sobre escopo de variáveis.
De acordo com a atualização da descrição da pergunta, você sempre atribui um valor a uma variável quando você tem a intenção de reutilizá-lo mais de uma vez, ou também para deixar o código mais legivel.
Atribuir a uma variável apenas para dar mais legibilidade não seria desperdício de memória,  pois como eu disse as variaveis apenas vai estar em memória enquanto o contexto em que ela estiver sido declarada, estiver sendo executado (exemplo uma função ou método).
Se fosse algumas décadas atrás, a resposta seria sim devido as limitações do hardware, mas hoje isso não é problema, a legibilidade do código é mais importante.
Comment: Me confundindo ao escrever a função. O correto é dar um return em uma string como você mesmo disse.
Comment: Ok. De memória não teria desperdício, porém desperdício de processamento, fazendo o PHP armazenar o retorno da função "teste" na variável de nome "variavel"? Aí que surge minha dúvida de imprimir direto da função em relação a criar uma nova variavel para atribuir o retorno a ela para só após isso imprimir.
Comment: Não é beeem um função, tem mais cara de ser um método por ter um `private` antes do nome.
Comment: Perfeito. Como você mesmo disse: "você sempre atribui um valor a uma variável quando você tem a intenção de reutilizá-lo mais de uma vez, ou também para deixar o código mais legível.". Exatamente em utilizar apenas pra ser legível que parei pra pensar se realmente isso trairia desperdício de performance, sendo que o PHP teria que atribuir um valor a uma variável sem necessidade. Obviamente se ela for utilizada posteriormente, seria necessário utiliza-la. O escopo da variável tem algo a ver com essa parte de performance? Não existe uma copia de valor na memoria como estou pensando?
Answer: private function teste()
{
    echo 'teste';
}

O método teste imprime um valor, e não retorna nada, logo, echo $this->teste() é a mesma coisa que $this->teste().
$variavel = $this->teste();
echo $variavel;

No exemplo acima, você imprime teste, mas não pelo echo $variavel, mas sim pelo método pois contém echo 'teste'. no seu exemplo $variavel é null pois o método não retornou nada.
Fiz um exemplo no ideone, você pode ver a variavel como null.
Comment: Me confundi ao escrever a pergunta. O correto é return no lugar do echo dentro da função teste.
Answer: Depende do caso, se for apenas imprimir o valor não tem porque fazer a atribuição à uma variável. Basta echo $this->teste().
Se o retorno do método for utilizado depois para um calculo ou outra operações faz sentido sim jogar o resultado em uma variável.
$res = $this->teste();
$res = formataAlgo($res);
if($res ...) ...
echo $res;

Comment: Exatamente isso. O problema é que muitas pessoas atribuem o valor do retorno da função para uma variável pra deixar o código mais organizado quando o nome da função for utilizado em diferentes algoritmos, corrigindo criando uma nova variável com um nome mais apropriado. Ai então que está minha dúvida: isso seria desperdício de processamento e memória então?


get const char from nsdictionary

Question: I am trying to read const char * from an nsdictionary
so far I have tried
NSLog(@"input1 %s",(const char*)inInputData);
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
NSValue* inputData = [NSValue value:&inInputData withObjCType:@encode(const char)];
[myDict setObject:inputData forKey:@"inInputData"];
NSValue* readVal= [NSValue value:[myDict valueForKey:@"inInputData"] withObjCType:@encode(const char)];
NSLog(@"input2 %@",[myDict valueForKey:@"inInputData"]);
NSLog(@"readVal1 %s",(const char*)readVal);
NSLog(@"readVal2 %s",(const char*)[myDict valueForKey:@"inInputData"]);

Results not matching
input1 !ã"—g¯ı0ã#àc†©Ä.2Ö£≤Áï7ª˚óm«Ûàut,‰aG≈ÈÜßx:◊Ætc´Ü£ªhg)8ÁÀ £Ø-<3©ô8>§
!…¨ÕøF∆'∏0'Ñ&,œ#∏?Ô
input2 <9d>
readVal1 `+#
readVal2 `+#

How can I get the input1 value correctly from the dict ?
Comment: Does `inInputData` represent a null-terminated C string, or is it a random array of bytes?
Answer: You pass const char as type, while the reference to input data is of type const char *.
const char * is used for C strings or binary dara. In the first case you should convert it to an instance of NSString.
But in your case it is obviously used for binary data. In such a case you should convert it to an instance of NSData.
NSData *data = [NSData dataWithBytes:inInputData length:youShouldReallyKnowThat];

Since instances of NSData are instance objects, you can store them into a dictionary.
Comment: isn't length should be `sizeof(inInputData)` ?
Comment: No, this is the size of a pointer. Where do you get it from? If it is no `\0`-terminated string, you need an extra length information.
Comment: An audio callback `- (void)handleAudioPackets:(const void *)inInputData
 numberBytes:(UInt32)inNumberBytes
 numberPackets:(UInt32)inNumberPackets
 packetDescriptions:(AudioStreamPacketDescription *)inPacketDescriptions`
Comment: Hmmm, what does `inNumberBytes` mean?
Comment: I think answer for the length is  `inPacketDescriptions[0].mDataByteSize` because of packet descriptions.

get const char from nsdictionary


itextSharp acrofields format as Number

Question: I use ITextSharp from c# code. I use acrofields to populate a form with data. I am just learnt how to format percentage. Next I need to learn how to format numbers.
Stream os = new FileStream(PDFPath, FileMode.CreateNew);
PdfReader reader = new PdfReader(memIO);
PdfStamper stamper = new PdfStamper(reader, os, '9', true);
AcroFields fields = stamper.AcroFields;
fields.SetField("Pgo", "1.0",  "100%");    // Works fine
fields.SetField("value", "1217000.000000",  "$1,217,000");    // Drops Dollar sign and comma

What am I doing wrong?
Comment: possible duplicate of [itextpdf acrofields format as Percentage](http://stackoverflow.com/questions/27695621/itextpdf-acrofields-format-as-percentage)
Comment: It's not really a duplicate, as it uses the answer of that previous question (see `// Works fine`). It's an extension of that original question asking about a different phenomenon: `// Drops Dollar sign and comma`. I'll answer it in the sense that the problem can not be reproduced. I'll also explain possible causes.
Comment: @Arne as a corollary: if you have a PDF with which your issue occurs, provide it with your question.
Answer: Please take a look at the FormatFields example. In that example, I took an ordinary form with a couple of ordinary fields, and I filled these fields in the exact same way as you did.
The result looks as expected:

iText has created two appearances (the /AP entry of the widget annotation) based on the display parameter we passed to the setField() method. One field shows "100$", the other field shows "$1,217,000". As you can see (and check for yourself here), the dollar sign and the commas are there.
However, the moment you click one of those fields, the appearance that was created by iText disappears and it's replaced by an appearance created by Adobe Reader (or any other PDF viewer) based on the value of the field (the /V entry of the field dictionary): "1.0" or "1217000.000000". This is expected behavior.
I am not claiming that your allegation is wrong, but maybe there is some JavaScript in your form that sets the focus to your value field. Maybe there's an open action that performs some JavaScript that formats the value field. Maybe something else is at play, but in any case: the reason for the phenomenon you describe is buried somewhere in your form. It is not a problem caused by iText: my example proves that the answer to the question itextpdf acrofields format as Percentage also works for currency values.
Comment: Thanks for our answer. Your example does not work for me. I will investigate.
Comment: Your example does not use Acrobat built-in formatting attributes
Comment: These are not triggered by iText as iText doesn't interpret the Javascript. As you didn't share your form, there was no way to know which of the pre-canned `AF_` functions are at play in your form.
Comment: 1. Created a test PDF form from scratch. The iText software now behaves well. I have long suspected there is  something wrong with my legacy PDF forms.
2. your example at http://itextpdf.com/sites/default/files/field_format.pdf does not use Acrobat built-in formatting and does not capture my problem.

itextSharp acrofields format as Number


Dynamically update Highcharts chart in react

Question: I am using highcharts-react-official in react-redux to create a drilldown chart.
However when I click on a bar to drilldown, I also update some props which causes the component to re-render - which seems to prevent the drilldown event.
I kind of gathered from Change series data dynamically in react-highcharts without re-render of the chart that I should use shouldComponentUpdate and getChart() to prevent re-render and instead dynamically update the data.
My issue is that getChart() doesn't seem to work for the official highcharts react package. I'm getting Uncaught TypeError: this.refs.chart.getChart is not a function
Is there an alternative I'm meant to be using to get and dynamically update the chart? Or some examples that I could look at?
Just including render and shouldComponentUpdate parts here:
shouldComponentUpdate(nextProps, nextState) {
    let chart = this.refs.chart.getChart();
    //dynamically update data using nextProps
    return false;
}

render () {

    const options = {
        chart: {
            type: 'column',
            height: 300,
            events: {
                drillup: (e) => {this.drilledUp(e)}
            }
        },
        plotOptions: {
            series: {
                events:{
                      click: (e) => {this.categoryClicked(e)}
                }
            }
        },
        xAxis: {type: "category"},
        yAxis: {title: {text: 'Amount Spent ($)'}},
        series: [{
            name: 'weekly spending',
            showInLegend: false,
            data: this.props.transactionChartData.series_data,
            cursor: 'pointer',
            events: {
                click: (e)=> {this.weekSelected(e)}
            }
        }],
        drilldown: {
            series: this.props.transactionChartData.drilldown_data

        }
    };
    return (
        <HighchartsReact
        highcharts={Highcharts}
        options={options}
        ref="chart"
        />
    )
}

Comment: I lived same problem, this can be easily corrected like this: https://stackoverflow.com/a/65821013/11302398
Answer: In highcharts-react-official v2.0.0 has been added allowChartUpdate option, which should work great in your case. By using this option you can block updating the chart with updating the component:
categoryClicked() {
  this.allowChartUpdate = false;
  this.setState({
    ...
  });
}

...

  <HighchartsReact
    ref={"chartComponent"}
    allowChartUpdate={this.allowChartUpdate}
    highcharts={Highcharts}
    options={...}
  />

Moreover, to get the chart instance use refs:
componentDidMount(){
  const chart = this.refs.chartComponent.chart;
}

Live demo: https://codesandbox.io/s/98nl4pp5r4
Comment: ah, now that you've written it out, its so blatantly in the readme as well. Thank you!
Answer: // react native functional

import React, {useState,  useRef,useLayoutEffect} from "react"
import HighchartsReactNative from '@highcharts/highcharts-react-native'

function chartcomponent(props){
   const [options, setoptions] = useState({});
   const chartRef = useRef(null);

  useEffect(() => {
     // create the options for your chart.
     setoptions({chart:{}, yaxis:{}, xAxis:{},})// etc.

  }, []);

  useLayoutEffect(() => {

        // new point to add, you can get new data via props, fetch, socket, etc.
        var x = new Date(hr.timestamp).getTime();
        var y = 10

        // these are the important parts here:
        var series = chartRef.current.props.options.series;
        if (!Array.isArray(series)){return;}
        var seriesdata = series[0].data;
        seriesdata.push([x,y]);
        // next line limits points in chart to 10, so new poitn replaces first point
        if (seriesdata.length>10){seriesdata.splice(0,1);}

        return () => {};
    }, [props]);

   return(
       <View style={styles.charting}><HighchartsReactNative styles={{height:300, width:600}}  options={options} ref={chartRef} ></HighchartsReactNative></View>

   )
}


Techniques to facilitate the process of marking which words are stressed/accented by beat

Question: I'd like to provide context first:
I'm currently pursuing a thesis project that uses a stylistic approach to rap music. I want to be able to prove that dividing rap bars by the (usually) four beats in a meter and then comparing a segment of words in between two beats (let's call them beat units) to another beat unit from the same/different bar uncovers deeper meaning via parallelism or contrast.
The thing is, with today's rap being by no means monotonous (or rather, mono-speed), I personally have a difficulty distinguishing just where the beat lands on a certain bar. I'd like to elicit suggestions that might facilitate this manual process. Is there any software, or even strategy, that could make it easier for me to determine where the beat lands on a certain lyrical meter?
EDIT: Title grammar
Comment: Examples of where the problem is would help us.
Comment: From the problem description, I can only tell you that beats land on beats. Like, always.
Comment: Like Lawrence suggests below, a better knowledge of your musical skill and why the "write the word you tap your foot on" doesn't work well for you. Sounds like an interesting thesis.
Answer: Rap specialises in cross-rhythms over a constant (usually, as you say 4/4) beat.  There IS 'beat-detection' software, the advanced sequencer programs such as Cubase offer this function.  If you already have such a program, give it a try.  But it shouldn't be too hard to tap your foot to the underlying beat of a rap song.  Your problem is in notating the complex cross-rhythms that rappers delight in! May we assume you have the basic musical skills for this job - familiarity with rhythmic notation and some facility in what music courses call 'aural tests' or 'musicianship'?
It's going to be difficult to address this without mentioning specific software.  My favourite is Transcribe!   You can slow the track down, add bar and beat markers, loop any section etc.   Nothing that you couldn't do in any DAW program, but all the tools for transcribing music collected in one convenient and inexpensive program.
You'll doubtless be able to detect and label sequence, fragmentation, diminution, augmentation etc.   Good luck in finding any deep meaning in it!
Answer: If it were me, I think I'd do a slow playback (programs like Audacity, Amazing Slowdowner, etc) so it's easier to keep a beat and hear where things fall.


Problemas com união de 2 vetores

Question: Eu tenho um problema para unir dois conjuntos de números inteiros em um vetor, sem a repetição de números que se encontrem no Conjunto A e no Conjunto B.
O seguinte erro é apresentado na linha 13:

error: unknown type name 'bool'; did you mean '_Bool'?|*

Trocando bool para Bool o código não é compilado, é algum erro de sintaxe?
Código:
#include <stdio.h>
#include <stdlib.h>

void PrintVetor(int Conjunto[], int Tamanho){
    int i;
    for(i = 0; i < Tamanho; i++)
    {
        printf(" %i ", Conjunto[i]);
    }
}

bool Existe(int x; int Uniao[], int k){ //Onde o erro se encontra
    int i;
    for(i=0; i < k; i++)
    {
        if(Uniao[i] == x)
            return true;
    }
    return false;
}

int main() {
    void PrintVetor(int Conjunto[], int Tamanho);
    bool Existe(int x; int Uniao[], int k);
    int Tam, i;
    int k=0; // Variavel que controla o tamanho do Vetor Uniao a cada vez que um novo termo é adicionado

    //Definindo o tamanho do conjunto
    printf("Qual o tamanho dos conjuntos?\n");
    scanf("%i", &Tam);
    int ConjA[Tam];
    int ConjB[Tam];
    int TamUniao = (Tam*2);
    int Uniao[TamUniao];

    //Alimentando o Conjunto A
    //Adicionando Conjunto A aoConjunto Uniao
    printf("Preencha o Conjunto A\n");
    for (i = 0; i < Tam; i++)
    {
        scanf("%i", &ConjA[i]);
        Uniao[i] = ConjA[i];
    }
    system("clear"); //Caso Seja Linux

    //Alimentando o Conjunto B
    printf("Preencha o Conjunto B\n");
    for (i = 0; i < Tam; i++)
    {
        scanf("%i", &ConjB[i]);
    }
    system("clear"); //Caso Seja Linux

    //#########################
    //Print dos Conjuntos
    printf("Conjunto A:[");
    PrintVetor(ConjA, Tam);
    printf("] \n\n");
    printf("Conjunto B:[");
    PrintVetor(ConjB, Tam);
    printf("] \n\n");

    //UNiao
    for(i=0; i<Tam; i++)
    {
        Uniao[i] = ConjA[i];
        k++;
    }

    for(i=0; i<Tam; i++)
    {
        if(!Existe(ConjB[i], Uniao, k))
        {
            Uniao[k++] = ConjB[i];
        }
    }

    printf("Conjunto Uniao:[");
    for(i=0; i < k; i++)
    {
        printf("%i ", Uniao[i]);
    }
    printf("] \n\n");

    return 0;

 }

Answer: O principal problema é que está faltando adicionar o cabeçalho que permite usar o tipo bool:
#include <stdio.h>
#include <stdbool.h>

void PrintVetor(int conjunto[], int tamanho) {
    printf("[");
    for (int i = 0; i < tamanho; i++) printf(" %d", conjunto[i]);
    printf(" ]\n");
}

bool Existe(int x, int uniao[], int tamanho) {
    for (int i = 0; i < tamanho; i++) if (uniao[i] == x) return true;
    return false;
}

int main() {
    int tamanho;
    printf("Qual o tamanho dos conjuntos?\n");
    scanf("%i", &tamanho);
    int conjA[tamanho];
    int conjB[tamanho];
    int uniao[tamanho * 2];
    printf("Preencha o Conjunto A\n");
    for (int i = 0; i < tamanho; i++) {
        scanf("%d", &conjA[i]);
        uniao[i] = conjA[i];
    }
    printf("Preencha o Conjunto B\n");
    for (int i = 0; i < tamanho; i++) scanf("%d", &conjB[i]);
    printf("Conjunto A: ");
    PrintVetor(conjA, tamanho);
    printf("Conjunto B: ");
    PrintVetor(conjB, tamanho);
    for (int i = 0, k = tamanho; i < tamanho; i++, k++) if (!Existe(conjB[i], uniao, k)) uniao[k] = conjB[i];
    printf("Conjunto Uniao: ");
    PrintVetor(uniao, tamanho * 2);
 }

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Algumas coisas adicionais que fiz:

Retirei o cabeçalho que não estava usando
Padronizei nomes das variáveis
Declarei as variáveis perto de onde são usadas e no menor escopo possível
Matei variável desnecessária
Matei declaração de função desnecessária
Matei uma lógica repetida
Organizei melhor o código para encurtar dando mais legibilidade (aumentando onde necessário)
E organizei para colocar a responsabilidade de cada coisa no lugar certo
Matei comentários, se eles são necessários é porque o código está mal escrito
Melhorei a apresentação estética
Mudei a formatação de dados para %d que é mais adequada para quase todos os casos.

O que não fiz, mas deveria ter feito:

Validar entrada de dados
Separar partes em funções até para manter a coerência, ou matar as funções auxiliares já que outras partes que são claramente ações separadas, mas estão na main()
Otimizações maiores que vai contra o que parece ser o propósito do exercício
Outros pequenos detalhes que vão mudar pouco

E não troquei o tipo para _Bool que funcionaria também.

Problemas com união de 2 vetores


Grab Data from non form elements and send as POST using AJAX

Question: I am looking for an alternative solution to the way my form is being submitted right now. The problem is that the validation function does not work because I gave the submit button on the form an attribute of onclick=return(false) and added the following AJAX code to listen for the submit button being pressed.
jQuery("#edit-submit-order").click(function() {
        var orderForm = jQuery("#order-form-form").serialize();
        var orderTable = JSON.stringify(hot.getData());
        var extraOrderTable = JSON.stringify(hot2.getData());
        var formType = jQuery("input:radio[name=form-type]:checked").val();

        jQuery.ajax({
            type : "POST",
            url : '/sites/all/modules/order_form/post-order.php',
            data : orderForm + "&orderTable=" + orderTable + "&extraOrderTable=" + extraOrderTable + "&formType=" + formType + "&orderTotal=" + parseFloat(updatePricing()).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),

            success : function(result) {
                if (result) {
                    jQuery('#order-form-form').empty();
                    jQuery('#order-form-form').append(result);
                    //jQuery("#order-form-form").html("
Submitted Order Form Successfully
");
                } else {
                    jQuery(".message").html("
" + result.message + "
");
                }
                jQuery(".message").children().fadeOut(5000);
            }
        });
    });

The orderTable and extraOrderTable are the elements I need to send with the POST request. They are part of an HTML table I am using called Hands on Table. It is a very nice excel like table editor. The getData() command returns an array of all values in the tables.
Ideally I would like to remove the onclick=return(false) from my submit button and have the order form submit using Drupal's AJAX method, making sure to validate the fields I marked as required but also submitting the table data in a single POST request. Can this be done or is the solution I have already made the best way to do it?
Comment: Hey would you mind showing your form code? It would be clear if you would do that but your question is some what related to this. http://drupal.stackexchange.com/questions/158303/get-divs-text-in-drupal-forms-api
Comment: @AlyssaGono I just answered the question with my method for solving the problem.
Answer: Hopefully this answer will help someone else looking for the same thing. I found a solution and it works great.
The way that I solved it was by creating two hidden elements with id's in my form. One hidden element for each table that I have in my form.
Below is how I created the hidden form element
$form['orderTable'] = array(
        '#type' => 'hidden',
        '#attributes' => array('id' => 'orderTable')
);

Below is how I created the container that holds the table and is used to generate the table from the Java Script file.
$form['middle']['order-table'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => array(
                'testing-table',
            ),
        ),
    );

The Excel like table that I used Handsontable has an excellent method called afterChange this gets fired after something on the form changes. So what I did is create another Java Script function that gets fired each time inside of the afterChange function.
 function updateHiddenFields() {
    var orderTable = JSON.stringify(hot.getData());
    jQuery("#orderTable").val(orderTable);
}

What this does if your not familiar with Java Script is turn the data from Handsontable into a JSON string and places it in the value field of the hidden element. By doing it this way all of the data is accessible when the form is submitted just like  I wanted and I was able to use the validation function.


Homotopy type of the realization of the order complex of a topology

Question: For any poset $P$, we can define an abstract simplicial complex $\Delta{P}$ called its order complex, whose vertices are the elements of $P$ and whose faces are chains (totally ordered subsets) of $P$.
The geometric realisation $\lvert \Delta{P} \rvert$ of this complex is a topological space. This is described in [1, p. 6].
A topological space $(X,T)$ has a homotopy class $[T]$.
As $T$ is a poset, we may also take the realization of the order complex of $T$, $S = \lvert \Delta(\mathcal{T}) \rvert$, and this has a homotopy class $[S]$.
Are $[S]$ and $[T]$ equal? If not, what is the relationship between them? I'm especially interested in the case when $(X,T)$ is a finite $\mathrm{T}_0$ space.
[1] Wachs, Michelle L. "Poset topology: tools and applications." arXiv preprint math/0602226 (2006). https://arxiv.org/pdf/math/0602226.pdf
Comment: Your $S$ is path connected. And so these cannot be homotopy equivalent if $X$ is not path connected. Moreover it is a simplicial complex, so it cannot be homotopy equivalent to something that does not have homotopy type of simplicial complex. Like Hawaiian earring.
Comment: What is $[T]$? And if the answer is, 'the homotopy class of $T$', then what do you mean by $T$?
Comment: @JeroenvanderMeer $T$ is the poset of open sets of the space.
Answer: The order complex of any poset $P$ with a greatest or least element $x$ is contractible.  Indeed, $|\Delta P|$ is the cone on $|\Delta (P\setminus\{x\})|$: each simplex in $\Delta(P\setminus \{x
\})$ (i.e., chain in $P\setminus\{x\}$) becomes a cone over that simplex with vertex $x$ (since you can add $x$ as an extra point to the chain), and it can be checked that these glue together to give a cone over the entire space $|\Delta (P\setminus\{x\})|$.  (There are other ways to see this as well; for instance, thinking of $P$ as a category, then $x$ is an initial or terminal object of $P$, and so gives an adjunction between $P$ and the terminal category which becomes a homotopy equivalence after taking nerves.)
So in particular, if $T$ is a topology, then $|\Delta T|$ is always contractible, and in particular is typically not (weakly) homotopy equivalent to the original space $X$.
(What is true is that if $X$ is a finite topological space or more generally an Alexandrov space, then $X$ is canonically weakly homomtopy equivalent to $|\Delta X|$ where $X$ is ordered with the specialization preorder, i.e. the order $x\leq y$ iff $y\in\overline{\{x\}}$.  This is a theorem of McCord which you can find in the paper McCord's paper Singular homology groups and homotopy groups of finite topological spaces.)
Comment: That's correct.
Comment: Thanks!

I have a related query. Let $S$ be a simplicial complex.

We get a topology from either the Alexandrov topology of its order complex, $A(P(S))$, or its geometric realisation $\mid S \mid$. Are these w.h.e.?

By taking $X = A(P(S))$, your statement says $A(P(S))$ and $|\Delta(W(A(P(S))))|$ are w.h.e., where $W$ is the specialisation preorder.
Wikipedia says $W \circ A$ [is the identity](https://en.wikipedia.org/wiki/Alexandrov_topology)
And Wach's book says (p.7) $|S|$ and $|\Delta(P(S))|$ are even homeomorphic.
So we have $|S| = |\Delta(P(S))| \sim A(P(S))$.
Is this right?


What's the current, "correct" way to bundle gems for a Rails app with system-wide RVM-installed Ruby?

Question: I got ruby installed system-wide by doing:
\curl -sSL https://get.rvm.io | sudo bash -s stable

and then:
sudo /usr/local/rvm/bin/rvm install 2.0.0

I'm still not positive that was actually correct, but it seems to have worked. It created an rvm group. I've added my user account to it, and re-logged in. Now I need to bundle install the gems for my Rails app. This is as close as I can get:
david@excelsior:/data/webapps/accountability$ sudo /usr/local/rvm/gems/ruby-2.0.0-p481@global/bin/bundle
/usr/bin/env: ruby_executable_hooks: No such file or directory

In the past, I've just done all of this stuff as root, but the rvm website spends a lot of time telling me that this (and rvmsudo) is "wrong" for system-wide operations. So I want to try doing it "right" this time, but I can't find where they've indicated how I should be doing it. It would seem that this simple operation would be front-and-center. Maybe I'm just blind?
Comment: My goal here is to deploy multiple Rails apps in, say, /data/webapps, all with their own versions of Ruby and various gems, and serve those apps with a standard Apache/Passenger install.
Answer: you do not need to use sudo, it should be enough to be in rvm group, just make sure you are in it with id.
as for the bundle command, I assume you do not rvm use 2.0.0-p481 before running the bundle, so instead of the bin/bundle you should be running wrapper which takes care of loading proper ruby environment for you:
/usr/local/rvm/wrappers/ruby-2.0.0-p481/bundle


Are there different kinds of Mini SAS to 4x SATA reverse breakout cables?

Question: I have an RPC-4224 case that has 24 bays with 6 Mini SAS ports. I needed a cable to break out one of them into 4 SATA ports, so I went down to my local Fry's Electronics and bought one. The cable came with a "sideband" cable that says optional on it.
I installed it in the box and my hard drives aren't showing up in the EFI/BIOS setup. I see other cables online, specifically one from Norco (the case manufacturer) that doesn't have that "sideband" cable.
My question is, are there different types of Mini SAS to 4x SATA cables? And if so, how do I tell the difference?
Answer: There is an excellent answer to this question in a post by barrygordon over on the unRAID Server Community:

To make it simple, if the host-controller side is a SAS connector (SFF-8470) and the target side is SATA drives then you must always use a SAS to SATA Forward Breakout Cable.  If The Motherboard/host-Controller side are SATA connectors and the backplane is a SAS connector then you must always use a SAS to SATA Reverse Breakout Cable.  For SATA to SATA you just use a "SATA" cable as there is only one type, although they do come in different lengths. For SAS to SAS connections there is also just a single cable type.

See also this excellent answer to How exactly does a SAS SFF-8087 breakout cable work? + RAID/connection questions.
Also, as Alex, said in comments:

Some confusion appears to stem from the fact that backplanes exist that have individual SAS/SATA ports such as the SuperMicro SAS743TQ. In this case, you do need to use forward breakout (e.g. 1x 8087 -> 4x SATA/SAS) - despite the fact that you are connecting those forward facing cables to the backplane.

So, to summarise:
<code>Cable needed           SATA drives/backplane  SAS backplane
---------------------  ---------------------  ----------------
SAS host/motherboard   Forward breakout       Mini SAS cable
SATA host/motherboard  SATA cables            Reverse breakout
</code>
Comment: Thanks @Alex, I've updated my answer to make this more clear.
Comment: Some confusion appears to stem from the fact that backplanes exist that have individual SAS/SATA ports such as the SuperMicro `SAS743TQ`. In this case, you do need to use forward breakout (e.g. 1x 8087 -> 4x SATA/SAS) - despite the fact that you are connecting those forward facing cables to the backplane.
Answer: There are multiple types of SAS connectors. Generally mini-SAS will be SFF-8086 or SFF-8087; according the the product page your case uses 8087.
Answer: Actually using the wrong cable prevents controller from detecting drive.
In the case of SFF 8470 cable it is easy to convert a host type into the other one and the other way round, I did it and it works, looking to the pin layout you can understand why it works.
Just un-screw the connector of the SFF8470 cable, flip over the cable inside (to swap transmitter and receiver pins), box it up again, plug it in, that's all.


Any one knows any book template for IOS App

Question: I need a template like cover flow for viewing books in IOS App. Anybody knows any template which can show books.
Please find attached images. I need something like shown in figure.
Sorry but I do not know these question should be ask on stack overflow or other stack overflow options!
Comment: Probably it is a Customized version of Cover flow. Also you can use [UIPageViewController](http://developer.apple.com/library/ios/documentation/uikit/reference/UIPageViewControllerClassReferenceClassRef/UIPageViewControllerClassReference.html)
Answer: Well to achieve this we have a number of controls. Please go through these
Pepper UI
Flip View Control
Leaves Control
Page Curl
You would have to tweak all of them to get your desired animation though iCarousel does offer many such animations. Dont forget to go through its library. Hope this helps.
Answer: Use iCarousel which is open source well-known library for such formats. You need to tweak the in-built types a little to make it look like a book.
Set the type to iCarouselTypeCoverFlow2 and implement delegate method itemTransformForOffset to provide your custom transform for book-like display.


M / M7+ / M7 / M6 or m / m7+ / m7 / m6. How do you call these kind of progressions, what is it?

Question: Several songs have this kind of progression: M, M7+, M7, M6 or m, m7+, m7, m6, for instance:

First verse of Sinatra's "My way":

And n[D]ow the end is n[D7M]ear and so I f[D7]ace the final c[B7]urtain

This verse of Beatle's "Michelle"

I will sa[Fm]y the [Fm7+]only w[Fm7]ords I kn[Fm6]ow that y[C#]ou'll underst[C]and
As those notes are not all diatonic, I'd like to know what it is, is there a name for this kind of progression, is there any theory behind it?
Thank you!
Comment: And it sounds just wonderful, doesn't it? A few weeks ago, I came across this as well while playing along to "Telephone Line" from ELO. In the first line of each verse, there's a descending A Amaj7 A7 progression. At least it's noted down like that when I looked it up. And I immediately asked myself if it shouldn't be written as A Amaj7/G# A7/G instead.
Comment: @Campfire Right; although the Beatles don't, you could of course put the chromatic line in the bass for extra impact.
Comment: @helil For the B7 on "curtain" in the Sinatra, should that be a Bm7?
Comment: @Richard I've found this chords online and I guess not; it prepares to an Em7. It's not part of the sequence in question, though.
Answer: I'm not sure if there's a name for it, but these reflect chromatic descending lines. E.g., for "My Way," as you move from chord to chord, you can find the individual notes D - C# - C natural - B, and for "Michelle," F - E - Eb - D.
Comment: Also "My Funny Valentine".
Comment: @Aaron Topical! I had reason to be humming that just a moment ago. Or, if we don't care that all the chromatic steps be equal in duration, Dido's Lament slithers all the way from ^1 down to ^5 (for an unrequited anti-Valentine's theme).
Comment: Yeah, pretty sure Dido is not a big V-day fan.
Answer: It's a line cliché. You see it a lot for a reason, it is very pretty.
Comment: Welcome to Music.SE! Could you add any more to this answer, perhaps by defining "line cliché" and other examples of it?
Answer: That's a tough one to phrase a Google search, but here's what I found:
As @Campfire and @Andy Bonner mentioned, it is a "disguised" descending chromatic bass line and it "arrives" at the subsequent chord. It could be played as such, from the examples above:
And n[D]ow the end is n[D/D#]ear and so I f[D/C]ace the final c[B7]urtain
I will sa[Fm]y the [Fm/E]only w[Fm/D#]ords I kn[Fm/D]ow that y[Fm/C#]ou'll underst[C]and
This is a fine page with a lot of examples "from the past four centuries":
https://musictheory.pugetsound.edu/mt21c/DescendingChromaticBassLines.html
So, I thought it would have a "explanation" from a theory point of view, but I guess it's just something you do, a common pattern.


CollectionView layerMask "jitter" when applied while scrolling

Question: I'm working on a view controller prototype consisting of a collectionView with the following requirements:

There is a single background image visible
Sections can "collapse" similar to an accordion view
The first view (called "main header" from now on) in the list "sticks" to the top of the screen so the button on the bottom remains visible while scrolling
Section headers "stick" below the main header and push each other out of the way when the next section header docks in the top. This is just like the default behavior of section headers in tableView.
The main header, section headers, and cells all have transparent backgrounds

I've decided to use UICollectionView for my solution. I could have tried to work around UITableView, but I wanted more control over the animation during collapsing and expansion of sections. It also allows me finer-grained control over the positioning of views on screen by subclassing UICollectionViewFlowLayout.
There's an issue due to the transparency requirement. Because all views have clear backgrounds, when overlap occurs (due to sticky main and section headers) we can see all cells at once when ideally the cells should go "underneath" their section headers. My solution here was to find the frame difference between overlapping views and use a layer mask to "hide" the part of the overlapping view that would normally be hidden if the background was opaque.
For some reason, while scrolling it looks like the frame of the layer mask is not being updated at the same time as the scrollView's contentOffset resulting in a slight, but noticeable "delay." I've tried the following approaches to fix the issue (all of which exhibited the same behavior):

Use CADisplayLink and update the layer masks every frame. To determine when view frames intersected, I tried both UIView.frame as well as UIView.layer.presentation().frame.
Use UICollectionViewLayoutAttributes on my UICollectionViewFlowLayout subclass for calculating layer mask frames instead of the views themselves.
Build a custom UICollectionViewLayout subclass and use its layout attributes for calculating layer mask frames (eliminating possibility it was something due to UICollectionViewFlowLayout subclass).

I have a few theories for this behavior. Maybe there's a sync issue due to collectionView updating the view positions in a separate pass of the run loop from when contentOffset changes, the layer mask's frame change is due to some implicit animation, or layer masks don't render properly when placed on half-points. Wrapping in an actions-disabled CATransaction ruled out the implicit animation issue and I would have though the displayLink while reading layer.presentation() for mask frame calculations would have ruled out the sync issue.
Other interesting item of note, this behavior does not occur when using UITableView which is why I was thinking it could be related to the run loop.
Below is a link to a sample project on my github page illustrating the behavior discussed above. The cells in this sample have a background color set by default to better illustrate the issue (it's hard to see when they're transparent).
https://github.com/irtemed88/ScrollJitterTest-iOS
Any help or pointers as to why this behavior occurs would be greatly appreciated!
Answer: Figured it out. The solution was similar to an approach I had tried during testing.
The issue appears to be related to the run loop (or at least when the scrollView's content offset gets updated). Instead of calculating the layer mask frame based off of the views in the collection view, I'm using a custom UICollectionViewLayout and corresponding UICollectionViewLayoutAttributes for each item to calculate the mask frames. It appears the layout attributes are updated in sync with the repositioning of the views on screen. Keying off those values when setting the mask fixes the problem.


Google Play services activity recognition disconnects without any error

Question: I am writing a background service (started by an activity) that records Screen on/off events and user's activity.
For activity, I am using google api client. The app works correctly on Moto G phones i.e. records both activity and screen but activity recognition stops on HTC one phone.
I have done few updates to code but still there is an issue that activity recognition stops after few minutes. As suggested by another member, I also exported both the android-support-v4.jar and android-support-v7-appcompat.jar files but still the issue is there.
The phone's location is on and it is not on power saving mode. Also, I updated my SDK as well as google play services on phone to the latest one, but still my api client disconnects after few minutes. Below are the code files that I used.
Please help me to correct this. I am using eclipse.
MyActiviy:
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private PendingIntent pIntent;
    GoogleApiClient mGoogleApiClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        mGoogleApiClient.connect();
        IntentFilter filter = new IntentFilter();
        filter.addAction("ACTIVITY_RECOGNITION");//For filtering
      }

    @Override

    public void onConnected(Bundle arg0) {
        Intent intent = new Intent(this, ActivityRecognitionService.class);
        pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 0, pIntent);//0
    }
    //@Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub
        mGoogleApiClient.connect(); //I found this recently, but still app doesn't works
    }
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub

    }
}

ActivityRecognitionService
public class ActivityRecognitionService extends IntentService {

    private String TAG = "appLogs...";
    private long fName;

    public ActivityRecognitionService() {
        super("My Activity Recognition Service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(ActivityRecognitionResult.hasResult(intent)){
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
            Log.i(TAG, getType(result.getMostProbableActivity().getType()) + "t" + result.getMostProbableActivity().getConfidence());
        }
    }

    private String getType(int type){
        if(type == DetectedActivity.UNKNOWN)
            return "Unknown";
        else if(type == DetectedActivity.IN_VEHICLE)
            return "In Vehicle";
        else if(type == DetectedActivity.ON_BICYCLE)
            return "On Bicycle";
        else if(type == DetectedActivity.ON_FOOT)
            return "On Foot";
        else if(type == DetectedActivity.STILL)
            return "Still";
        else if(type == DetectedActivity.TILTING)
            return "Tilting";
        else if(type == DetectedActivity.RUNNING)
            return "Running";
        else if(type == DetectedActivity.WALKING)
            return "Walking";
        else
            return "";
    }

Comment: Please compare your code with [this](https://github.com/udacity/google-play-services/tree/master/LocationLessons_Final/activityrecognition) repo which was written by googler.
Comment: thanks! I am comparing it.
Comment: How about the result?
Comment: code was correct, the issue is with the phone. Like if the phone is idle for some time, there would be no activity record (which makes sense). but on my other test phones, even if they are idle the activity still be sensed after regular time intervals (like after 10 mins)
Comment: Which test phones? On L or M?
Comment: So M has a doze mode which u need to care about
Comment: yup, sure i will. Thanks!
Comment: I have quite similar problem with HTC M8 Android 5.0.1 http://stackoverflow.com/questions/33363274/activity-recognition-does-not-work-after-phone-goes-asleep?noredirect=1#comment54586283_33363274.
Comment: from your post it seems that its not possible to solve, is this correct?
Answer: As I have just answered here, it seems that there is no way around. Activity reporting will stop after phone is "still" for some time.
If you want to record even if the phone is "still", I see two ways:
1) rely entirely on the ActivityRecognition API and record "still" until a SIGNIFICANT_MOTION will be detected by Google Services and ActivityRecognition start send you new updates;
2) to write your own simple StillActivityRecognitionService, which starts when there is no updates from "official" API. This Service should listen to the accelerometer sensors, interpret sensor events (deviation from the mean, peak values etc.) and send it's decision "still"/"not still".
Comment: yup that's what i found from my research too :)
Comment: but i just found another phone LG that has this same issue, i mean user is using the phone but still activity sensing stopped after some time, do you have any suggestions?
Comment: if sensing stops it is ok, because it is a feature of this ActivityRecognition API.

the problem would be if it will never start sensing again. I guess after you walk for a while ActivityRecognition wakes up and start sensing again.

so as I've written in my answer - two ways: trust this Service or write your own auxiliary, which will may wake up the phone using AlarmManager with the required delays, sense accelerometers for 1-5 seconds, calculate deviation from the mean and send it's decision "still" or "unknown" to a broadcast receiver and so on
Comment: but it works perfect on my other test phones..it makes sense to me that sensing stops when a user is still for a long period of time, but once user is active again then there should be a log of activity. This is what i observed on HTC. Any suggestions? BTW my app is blank activity that starts many services like location sensing etc. every thing else except for activity is working fine
Comment: maybe add some logs so you will be able if it enters 'onConnectionFailed'.
also I would add 'mGoogleApiClient.disconnect()' in it
Comment: you mean:
public void onConnectionFailed(ConnectionResult result) {
       mGoogleApiClient.disconnect();

    }

Also, if I disconnects, re connection will be automatic?
Comment: Try to add two methods to your mGoogleApiClient :

`mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();`
Comment: i am doing it already i guess, see above. or am i missing any thing?
Comment: no more ideas, but if it help I will correct my answer.

add two calls in `onCreate` in `MyActivity` to `mGoogleApiClient` as I wrote above


Is it safe to plug guitar directly to portable (battery powered rechargeable) speaker

Question: This is more of a technical questions but it relates to music practice, still, feel free to comment if you think it doesn't belong here.
I bought a 6.3mm female 3.5mm male jack adapter and did the most naive/simple setup. Electro acoustic guitar->cable->adapter->portable speaker (jbl charge 3)
And it works fine, my only concern is will this damage the speaker?

Thanks in advance
Comment: And how do they have to be relative to each other? The output impedance has to be lower or higher than the input impedance?
Comment: Check the rated output impedance of your guitar against the rated input impedance of your speaker.  'nuff said.
Comment: Is the adapter a Tip Ring Sleeve or Tip Ring plug?  It may not matter, but I would like to try the same thing. The way to tell TRS is look for three sections on the prong of the plug separated by black insulators.
Answer: No, it won't harm the speaker at all.  The worst that could happen is weak and/or distorted sound, but even that doesn't mean you're damaging the speaker.
I'm surprised you said it works fine, unless the guitar has some sort of pre-amp built in to get the signal up to line level.  (My basses have passive pickups which are microphone level.) If that's the case then you could just as easily plug it into your computer's line in jack and have that work too.


IP address of network computer

Question: The program I'm coding connects to another program via a network-API, and I believe it's called a socket connection. I specify the IP: 127.0.0.1, and the Port, which must match what I set in that program.  Now, this works fine. But what if I want to have the program running on another computer on a network?
I have set up a wireless home network, and file sharing works between the two computers. I thought I could just run cmd>ipconfig to get the IP of the other computer, but for some reason the ipconfig will not run on it. Just gives an error.   How do I now determine the correct IP to use for this type of network connection?
PS: I'm running XP Pro.
Comment: I am sure you mean `IP`, and not `API`.
Comment: "some other reason" ? Does it throw an error? You can just look in the network adapter/network connection properties in the taskbar to find the3 IP.
Comment: Can you post error content? Make sure you use ipconfig on remote computer, it can only get ip of local machine's NICs
Comment: This doesn't sound like a programming problem or are you trying to find/guess the remote IP with your code? **=> should go to superuser.com**
Comment: I did mean API.. I connect (the program I code) to another program through an API connection.    And cmd>ipconfig doesn't work. I can't either seem to find this by right-clicking "wireless network connection"  in Network Connections..
Comment: Well it's not programming "code" question. It's just to know the IP so I can specify it in my program. If that's not ok to ask, then sorry.
Answer: You could use the computer name instead of the IP (but, this depends what you're working on). To see what the computer name is right click My Computer / Properties.
Or, you can see it's IP simply by pinging it:
ping MyPCName

In the response you'll get the resolved IP address, the way computer you ran it on sees it.
Answer: Open network connections (Start -> Settings -> Control Panel -> Network Connections) and find there your wireless connection. Left click and select Properties. Then follow the Advanced tab and there you propapbly will find your IP.
Comment: This also may be done with "ipconfig /a" command. BTW, as far as I understand the question, program way to obtain IP address is required.
Comment: well, it doesn't seem to show. I can click on TCP/IP in the general tab, but it only shows that IP is set to automatic, and not showing the actual IPs.
Comment: thing is: when i try to run cmd > ipconfig (from run) .. It doesnt run like normal. it says:  "An internal error occured" A unit connected to the system does not work..  (Or something similar; it is not English XP)    So I can't get it from there.
Answer: ipconfig shows you the address of your computer. You can use ipconfig on the other computer to check its IP address. Then instead of 127.0.0.1 use that address. There is ipconfig /all that show much more information, usable if you have more network cards, want to check MAC address etc, but this is information about computer this command work on.
Comment: Then get it to work, there should be a root cause for the issue. Simplest way is usually to backup data, wipe and reload the Windows installation, it's likely faulty and/or has driver conflicts and that could take an infinite time to resolve if you're not familiar with the system.
Comment: Thanks, but I think simplest way is just to ignore it. I have better things to spend my time on.  :)

IP address of network computer


Am new but i need help in pod install my pod file also attached

Question: [!] CocoaPods could not find compatible versions for pod "Firebase/core":
In Podfile:
Firebase/core
None of your spec sources contain a spec satisfying the dependency: Firebase/core.
You have either:

out-of-date source repos which you can update with pod repo update or with pod install --repo-update.

mistyped the name or version.

not added the source repo that hosts the Podspec to your Podfile.

[!] Automatically assigning platform iOS with version 14.3 on target Spacechat because no platform was specified. Please specify a platform for this target in your Podfile. See https://guides.cocoapods.org/syntax/podfile.html#platform.
Please help as I need to finish this task fast.
My podfile:
#platform :ios, '9.0'
target 'Spacechat' do
use_frameworks!
pod 'Appirater'
#Firebase
pod 'Firebase/core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Analytics'
pod 'Firebase/Crashlytics'
end
Comment: Hi Tami! Welcome to SO! Please don't include phrases like 'need fast answer'. It almost always has the opposite effect of what it intends. Also, please consider thinking about what's really important to solve the question and then format it accordingly (including a concise title), see here: https://stackoverflow.com/help/minimal-reproducible-example .
Answer: From https://github.com/CocoaPods/CocoaPods/issues/10449:
Pod spec/subspec names are case-sensitive. It should be Firebase/Core.
Also, not required, but recommended:
Firebase/Core is no longer recommended usage. Instead, directly specify the needed Firebase libraries. See https://firebase.google.com/docs/ios/setup#available-pods.
So an even better solution is to delete the line since it is redundant with Firebase/Analytics


Many-to-many or many-to-one LSTM when predicting a value derived from a sequence of features

Question: Let's say I have a time series data set consisting of features that may correlate to whether or not the price of a stock will go up or down. Say these data points are at 5 minute intervals. I build an LSTM that takes in two hours of these sequential data points (24 time steps) and then attempts to predict if the price will have increased/decreased an hour after the last data point fed into the network.
As the training data is historic data, I have labels for every data point - whether or not the price increased/decreased an hour after this data point. In practice, I would be inputting a sequence of 24 data points, but will only base my prediction off of the final output. As the LSTM produces an output at each time step, should I be calculating the loss from all 24 of these outputs, or just the last one?.
The temporal nature of these data points is important for determining this up/down trend. Thus the output at the first time step will be a value derived from a single data point (with no previous sequence). I think that this would have a negative effect on the loss.
Or, do you think that because of the nature of an LSTM, and because it has learned on previous training sequences, it will actually make an accurate prediction on this single, first time step alone?
So can I include it, and every other time step's output, in the loss calculation?
Answer: The output of an LSTM block is not immediately interpretable as probability of an event happening as the activation function is tanh. To mitigate this, putting a Dense layer that takes the concatenated outputs from the LSTM would seem more sensible to me. So like this
$$ \sigma(W x + b)$$
where $ x = \begin{pmatrix} h_0 \\ h_1 \\ \vdots \\ h_{t-1}\end{pmatrix}$ is a vertically concatenated vector of outputs. $W\in \mathbb{R}^{24\times dim(h_i)\cdot t}$, $b\in\mathbb{R}^{24}$. Now you can use something like categorical crossentropy as your loss function.
As for your first data point problem, can you shift the starting point to be the 25-th datapoint?
Comment: I am still unsure - With the notion of "unrolling" an RNN into the number of time steps in the inputs sequence (24 in my case), wouldn't each of these 24 time steps have a dense layer from the last LSTM layer to the output neurons? Say my last layer at each time step has a size of 64 LSTM cells and my network has two outputs at each time step (price is either higher/lower 1 hour from this time step), the weights corresponding to this dense layer would have a shape of $ 100 \times 2 $. I use a softmax cross entropy on these two outputs - thus my LSTM produces a prediction at all 24 time steps.
Comment: I do not understand what you mean by "can you shift the starting point to be the 25th datapoint"? If you would like, and are familiar with TensorFlow, I could share my model with you and explain the structure of my data set so that you could make suggestions on my implementation?