Simple explanation of counterpoint?

Question: Wikipedia defines counterpoint like this:

In music, counterpoint is the relationship between voices that are interdependent harmonically (polyphony) yet independent in rhythm and contour.

What does it mean to be interdependent harmonically yet independent in rhythm & countour? Is there a simpler explanation of counterpoint? (or a simpler way of saying this?)
Comment: I would like to clarify that if you define harmony as chords, that the above definition is misleading.  Historically counterpoint has been based on the relationships between 2 or more voices and how to have them move to allow each line to operate independently but work together.  As such, the resulting harmony (if defined as chords) is a consequence of the linear motion of each voice and the rules of voice leading.  The chords are not the guiding force but are a result of functional counterpoint.  Chord theory evolved out of counterpoint and led the way to homophony.
Comment: I found good examples about this on YouTube. For example this one: https://youtu.be/4O6lc_ym12U
Comment: cf. https://music.stackexchange.com/q/14801/26407
Answer: Independent in rhythm & contour means that the voices may have different rhythms and contour, respectively.
For example, if a voice goes up and another goes down, the voices would be moving in opposing motion. Moreover, one voice may be going up, and then down while the other remains going down only. All this means that the voices are independent in contour.
Independent in rhythm is analogous; the rhythm of one voice doesn't affect the rhythm of the other voice.
On the other side is harmony. Unlike rhythm or contour, each note being played at a time has a role on the harmony. Then, the harmony is dependent on each voice.
Counterpoint, in simple terms, is a technique for creating "good" harmony with independent voices (independent on contour & rhythm). Another way of looking at it is: Counterpoint is a technique for composing various simultaneous independent voices without messing up the harmony.
Answer: Yes. It means you can distinguish 2 or more different melodies that sound pretty together.
This is not the same as melody and accompaniment; in that case there's one melody and one more voices that form a rather static backdrop.
That said Independence is to some extent subjective; a counter melody will be perceived as more independent if it has different rhythm, if the melodically movement seems not in any way connected to the other melody etc.
Answer: All it means is that is that both voices add up to some kind of harmony (think of chords although they don't have to be), while the the musical lines themselves don't sound or feel alike. These voices can also typically each be perceived as a different melody.
There is a much simpler way to say what counterpoint is, which is "The study of how to make two voices independent within the context of harmony."
The reason why rhythm and contour are singled out is they play a very big role in determining whether two voices sound or feel alike. If two voices are moving in the opposite direction you can hear it and if two voices have different rhythms you can hear it. If the rhythm and the contour was the same the voices would sound very dependent, so making one different helps make the two voices independent.
If you want good examples of how counterpoint can be used, listen to some fugues and inventions.
Answer: I believe it is easier to see it than to read about it, so here you have the maximum expression of counterpoint, a fugue. You can see how every melodic line has its own rithm and melody, they "don't care" about each other, yet it all sounds great, mostly because the composer is a freaking genius! :D
An Easy-to-see Bach fugue, click and in 3 minutes you will have understood it ;)
Answer: "Creating the effect of harmony from multiple melodies". That's pretty much it! (Of course, it is quite complex...)

Simple explanation of counterpoint?


Cannot Login, error msg shows "To log in to this site, your browser must accept cookies from the domain"

Question: On my dev environment hosted on the cloud which has SSL, I added this to the settings.php
$secure = true; // if you only want to receive the cookie over HTTPS
$httponly = true; // prevent JavaScript access to session cookie
$samesite = 'none';

if(PHP_VERSION_ID < 70300) {
  session_set_cookie_params($maxlifetime, '/; samesite='.$samesite, $_SERVER['HTTP_HOST'], $secure, $httponly);
} else {
  session_set_cookie_params([
    'lifetime' => $maxlifetime,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => $secure,
    'httponly' => $httponly,
    'samesite' => $samesite
  ]);
}

My goal was to set SESSION cookie to samesite = 'NONE'.
Login was working when I did this on Drupal 8, but now on Drupal Core 9.3.0,
when I login I get error message
"To log in to this site, your browser must accept cookies from the domain [domain_name]"
Comment: My first take would be to search this string. Then you know the place in core where it comes from, and when. Then you can compare the code at this place to Drupal 8 on https://git.drupalcode.org.
Comment: Does this help? https://www.drupal.org/project/drupal/issues/2946 It's the issue where that error message has been introduced.
Comment: Are cookies disabled in your browser by any chance?
Comment: @berliner  thanks, but haven't found out anything useful from the issue. Also cookies are enabled in my browser.
Comment: Yes, same issue in Drupal 9.4.5
Comment: Did you find any solution ? My Drupal version is 9.5.9, dev & live website which are running on server, there I am able to login, but I am facing this issue on my local setup, I can login in Firefox incognito mode, but apart from that in all browser I am facing this issue, even in incognito mode.
Answer: You get this error message when Drupal expects there to be a session, communicated by the check_logged_in, but none can be found.
I've found myself in this situation myself when a miss-configured web server stripped the cookies from the request.
The leads to Drupal setting up the session, and adding the query parameters, but the cookie not being present in subsequent requests. Drupal then displays the

your browser must accept cookies

message.
Likely the cookie settings you are adding cause the cookie to become invalidated somehow, so double check that the browser actually sends the cookies, and that they reach Drupal.


How look up JSON object in Handlebar expressions

Question: I'm using Handlebars and am trying to use a post's userId to find the user's username and pic; for now I'm using the userId as a placeholder for the correct expression. I've also tried several ways to get the data from JSON files instead of having it inline, but I haven't gotten that right.
{{#posts}}

        {{userId}}
        {{content}}

        {{#comments}}

            {{userId}}
            {{content}}

        {{/comments}}
        <input type="text" name="comment" placeholder="post a comment"/>

{{/posts}}

var source = $("#postTemplate").html();
var template = Handlebars.compile(source);
var data = {
posts: [
{
  "id": 1,
  "userId": 1,
  "content":"Love wine? Love food?",
  "comments": [
    {
      "id": 13,
      "postId": 1,
      "userId": 2,
      "content": "Would you happen to know were Capone is? "
    }
  ]
},
{
  "id": 2,
  "userId": 2,
  "content":"Day 2 of house sitting...awww my firends really do Trust me!",
  "comments": []
}
],
users: [
{
  "id": 1,
  "username": "James Bond",
  "pic": "images/profile/Sean-Connery-as-James-Bond.jpg",
},
{
  "id": 2,
  "username": "William Forrester",
  "pic": "images/profile/2001_finding_forrester_008.png",
}
]
};
$('.feed').append(template(data));

Comment: Your code seems to be working - Have you added all of the libraries? Example: http://jsbin.com/waqusowelo/1/edit
Comment: @limelights He needs the users `pic` as the image source and `username` as the text inside hyperlink, not `userId`
Answer: If you convert your users array into an object whose keys are the userId's like:
users: {
      "1": {
              "username": "James Bond",
              "pic": "http://i49.tinypic.com/28vepvr.jpg",
           },
     "2": {
            "username": "William Forrester",
            "pic": "http://i46.tinypic.com/2epim8j.jpg",
      }
}

then you can create two custom helpers as shown below:

var data = {
  posts: [{
    "id": 1,
    "userId": 1,
    "content": "Love wine? Love food?",
    "comments": [{
      "id": 13,
      "postId": 1,
      "userId": 2,
      "content": "Would you happen to know were Capone is? "
    }]
  }, {
    "id": 2,
    "userId": 2,
    "content": "Day 2 of house sitting...awww my firends really do Trust me!",
    "comments": []
  }],
  users: {
    "1": {
      "username": "James Bond",
      "pic": "http://i49.tinypic.com/28vepvr.jpg",
    },
    "2": {
      "username": "William Forrester",
      "pic": "http://i46.tinypic.com/2epim8j.jpg",
    }
  }
}
Handlebars.registerHelper('username', function(options) {
  var userInfo = options.data.root.users[this.userId];
  return userInfo ? userInfo.username : "";
});
Handlebars.registerHelper('avatar', function(options) {
  var userInfo = options.data.root.users[this.userId];
  return userInfo ? userInfo.pic : "";
});
var source = $("#postTemplate").html();
var template = Handlebars.compile(source);
$('.feed').append(template(data));
.post{
  margin:5px;
}
.post-comments{
  padding-left:20px;
}
img {
  width: 50px;
}

or you can keep the array and iterate over it the until you find a match inside the helpers, which is much costly:

var data = {
  posts: [{
    "id": 1,
    "userId": 1,
    "content": "Love wine? Love food?",
    "comments": [{
      "id": 13,
      "postId": 1,
      "userId": 2,
      "content": "Would you happen to know were Capone is? "
    }]
  }, {
    "id": 2,
    "userId": 2,
    "content": "Day 2 of house sitting...awww my firends really do Trust me!",
    "comments": []
  }],
  users: [{
    "id": 1,
    "username": "James Bond",
    "pic": "http://i50.tinypic.com/f0ud01.jpg",
  }, {
    "id": 2,
    "username": "William Forrester",
    "pic": "http://i49.tinypic.com/28vepvr.jpg",
  }]
};
Handlebars.registerHelper('username', function(options) {
  var id = this.userId,
    userInfo = $.grep(options.data.root.users, function(userInfo) {
      return userInfo.id == id;
    })[0];
  return userInfo ? userInfo.username : "";
});
Handlebars.registerHelper('avatar', function(options) {
  var id = this.userId,
    userInfo = $.grep(options.data.root.users, function(userInfo) {
      return userInfo.id == id;
    })[0];
  return userInfo ? userInfo.pic : "";
});
var source = $("#postTemplate").html();
var template = Handlebars.compile(source);
$('.feed').append(template(data));
.post {
  margin: 5px;
}
.post-comments {
  padding-left: 20px;
}
img {
  width: 50px;
}

P.S: My first handlebars encounter (I've been reading this for the past few hours) so there might be a better way


Copy instances of derived class based on properties with attributes

Question: Suppose I have an abstract base class in which I want a CreateCopy method:
public abstract class BaseClass
{
    ///base stuff

    public BaseClass CreateCopy() //or public object, if necessary
    {
        //?????
    }
}

Assume that all derived classes have a parameterless constructor and property fields (that can be) marked with some kind of attribute:
public class DerivedClass : BaseClass
{
    [CopiableProperty]
    public string Property1 {get; private set;}

    [CopiableProperty]
    public int Property2 {get; private set;}

    //no need to copy
    public int Property3 {get; private set;}

    //parameterless constructor
    public DerivedClass() { }
}

Is it possible with this structure to write the body of CreateCopy() in a way that I can create new instances of the derived objects with the correct CopiableProperty fields?

Naturally I could make a public abstract BaseClass CreateCopy() and force each derived class to care for its own copy, but due to the size and amount of the derived classes, this would bring too much extra effort.
Comment: Perhaps you could use a Json serializer. You can decorate the properties with JsonIgnore. Then your base CreateCopy could return a serialized payload of the derived class. You can then take that payload and de-serailize into a copy of the class? I think :)
Comment: Have you considered using serialization? You can use attributes to control which properties should be serialized or not. See https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonIgnoreAttribute and also  https://stackoverflow.com/a/15788750/558486
Comment: have you thought about using an intermediate class between the base and the derived class?
Comment: Yes it is possible, iterate through the properties, filter for your attribute and copy the values of the properties left.
Answer: A fairly simple approach could be using generics and reflection:
public abstract class BaseClass
{
    // restrict to children of BaseClass
    public T CreateCopy<T>() where T: BaseClass, new()
    {
        var copy = new T();

        // get properties that you actually care about
        var properties = typeof(T).GetProperties()
            .Where(x => x.GetCustomAttribute<CopiablePropertyAttribute>() != null);

        foreach (var property in properties)
        {
            // set the value to the copy from the instance that called this method
            property.SetValue(copy, property.GetValue(this));
        }

        return copy;
    }
}

public class DerivedClass : BaseClass
{
    [CopiableProperty]
    public string Property1 { get; set; }

    [CopiableProperty]
    public int Property2 { get; set; }

    public int Property3 { get; set; }

    public override string ToString()
    {
        return $"{Property1} - {Property2} - {Property3}";
    }
}

static void Main(string[] args)
{
    var original = new DerivedClass
    {
        Property1 = "Hello",
        Property2 = 123,
        Property3 = 500
    };

    var copy = original.CreateCopy<DerivedClass>();

    Console.WriteLine(original);
    Console.WriteLine(copy);

    Console.ReadLine();
}

This would print:
Hello - 123 - 500
Hello - 123 - 0

Another approach would be to take advantage of a serialization library, if you don't mind the dependency:
public abstract class BaseClass
{
    public BaseClass CreateCopy()
    {
        string serialized = JsonConvert.SerializeObject(this);

        var actualType = GetType();

        return JsonConvert.DeserializeObject(serialized, actualType) as BaseClass;
    }
}

public class DerivedClass : BaseClass
{
    public string Property1 { get; set; }

    public int Property2 { get; set; }

    [JsonIgnore]
    public int Property3 { get; set; }

    //parameterless constructor
    public DerivedClass() { }

    public override string ToString()
    {
        return $"{Property1} - {Property2} - {Property3}";
    }
}

Comment: Great thing with Generics. Thanks for the very complete answer. --- A "bug" that is easy worked around: if the target property belongs to the base class, it throws an exception when setting. (It would be complex if I had more than one level of inheritance, but here I just use the base class property without reflection).
Comment: @DanielMöller Huh, I knew I had to test this a little more. Glad you found it useful though!
Comment: Maybe using `BindingFlags.DeclaredOnly` should solve it, but then I'd have to go through each type in the hierarchy up to the base type.
Answer: My solution uses serialization/deserialization, using JSON.NET nuget package.
No need for a method in the base class, you can use an extension method instead (adapted from this answer):
using Newtonsoft.Json;

public static class ObjectExtensions
{
    public static T Clone<T>(this T source)
    {
        var serialized = JsonConvert.SerializeObject(source);
        var clone = JsonConvert.DeserializeObject<T>(serialized);

        return clone;
    }
}

And then use attributes to control which properties should be copied or not - example:
using Newtonsoft.Json;

public class DerivedClass : BaseClass
{
    public string Property1 { get; set; }

    public int Property2 { get; set; }

    [JsonIgnore]
    public int Property3 { get; set; }
}

Using the code:
var obj1 = new DerivedClass
{
    Property1 = "Abc",
    Property2 = 999,
    Property3 = 123
};

DerivedClass clone = obj1.Clone();

Result - as you can see, Property3 has the default value in the cloned object:
Answer: Iterate through all properties in type and check your attribute with GetCustomAttributes. See code:
public BaseClass CreateCopy()
{
    var type = GetType();
    var result = Activator.CreateInstance(type);

    foreach (var propertyInfo in type.GetProperties())
    {
        var skipThisProperty = !propertyInfo.GetCustomAttributes(
                typeof(CopiablePropertyAttribute), false)
            .Any();

        if (skipThisProperty)
            continue;

        var value = propertyInfo.GetValue(this, null);
        propertyInfo.SetValue(result, value, null);
    }

    return (BaseClass) result;
}

Please pay attention to null parameter in GetValue and SetValue. If your property is indexer, you need to pass a correct value as last argument


Remove shortlink link and meta tag generator

Question: I try to remove shortlink and generator link from my site.
<meta name="generator" content="Drupal 7 (http://drupal.org)">
<link rel="shortlink" href="http://landberg.at/nl/node/109">

I used below code in template.php but when i look in my source code its still there?
function landberg_html_head_alter(&$head_elements) {
    unset($head_elements['system_meta_generator']);
    foreach ($head_elements as $key => $element) {
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
          unset($head_elements[$key]);
        }
        if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'shortlink') {
          unset($head_elements[$key]);
        }
    }
}

What is best way to remove this?
Comment: Your code is correct. Make sure that you cleared the cache.
Comment: @Aram Boyajyan i already cleared cash but the code is still showing up?
Comment: Strange; I checked the code and it works fine. Is the name of your theme exactly `landberg`? Add there a watchdog entry (e.g. `watchdog('debug', 'hook_html_head_alter() called from the theme');`) to make sure it is executed.
Comment: it was because it was overwritten by Meta tag module... Thanks
Comment: Good catch - glad you managed to resolve it!
Answer: Above code is good but it didn't work because it was overwritten by Meta tag module. I adjust some settings in Configuration » Search and metadata and now generator tag and shortlink is gone.
Comment: That is a proper solution. Sadly it needs to be done on all Metatag elements.
Comment: You could also simply add `unset($head_elements['metatag_shortlink']);` to your above snippet. Although I don't like how this then invalidates the admin UI. As no matter what anyone will put in these fields on the Metatag settings form, the values will be overwritten by that line.


Save jQuery selector and function to variable

Question: I have a Save/Edit button. I would like it to do different things depending on whether it's currently a Save button or an Edit button. For clarity, I want to save the jQuery selector and function to a variable name, then call it:
<code>    $('div#' + id + ' .edit').click(function(){

        var i = this;
        var state = function(st){
            if( typeof st !== 'undefined')
                $(i).html(st);
            else
                return $(i).html();
        };

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });
</code>
My question: is there a faster way to do this? Something like the following:
<code>    $('div#' + id + ' .edit').click(function(){

        var state = $(this).html;

        if( state() == 'Edit' ) {
            controller.edit(id);
            state('Save');
        } else {
            controller.save();
            state('Edit');
        }

    });
</code>
...but this does not work.
This example is just an example; I know there are many ways to do what it's trying to do without saving the selector and the function to a variable. Nonetheless, the question still stands: is it possible to do this faster?
Answer: Why not just
<code>$('#' + id + ' .edit').on('click', function(){
    $(this).text(function(_, txt) {
        if (txt == 'Edit') {
            controller.edit(id);
            return 'Save';
        } else if (txt == 'Save') {
            controller.save();
            return 'Edit';
        }
    });
});
</code>
Comment: Your particular example doesn't change the text of the button after it's been clicked. And as I'd mentioned, I know there are different ways of doing it without saving the selector and function. I want to know whether saving selector and function is at all possible.
Comment: @sg.cc - It's not really clear what you're trying to do, as the code you've posted doesn't really make any sense, but I edited  the answer to change the button text as well ?
Comment: `$(this).text(_, txt) {` doesn't make sense. I assume you meant to write `$(this).text(function (_, txt) {`
Answer: jQuery elements are objects so why not store directly into your Object element the desired state:
DEMO
<code>$('div#' + id + ' .edit').click(function(){
  var es = this.es ^= 1;           // Toggle/Store state
  $(this).text(es?'Save':'Edit');
  return controller[es?'edit':'save'](id);
});
</code>


NSDictionary writetofile is not working

Question: I'm trying to save some user settings using NSDictionary writetofile but it is not working.
I have already checked out similar questions but I could not find out what the problem is.
here's my code:
NSDictionary *settings;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *settingsPath = [NSString stringWithFormat:@"%@/UserSettings.plist", [paths objectAtIndex:0]];
BOOL settingsExist = [[NSFileManager defaultManager] fileExistsAtPath:settingsPath];
if(settingsExist){
    NSLog(@"file found!");
    settings = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
}else{
    NSLog(@"file not found!");
    settings = [[NSDictionary alloc] initWithObjectsAndKeys:@"iPhone",@"device", nil];
    [[NSFileManager defaultManager] createFileAtPath:settingsPath contents:nil attributes:nil];
    if([settings writeToFile:settingsPath atomically:YES]){
        NSLog(@"success!");
    }else{
        NSLog(@"fail!");
    }
}

It keeps returning 'fail!'.
Could you help me with this please?
Comment: I'm sure you meant `NSDocumentDirectory` instead of `NSDocumentationDirectory`. Also, you ***must not*** use format strings for constructing file paths. Use `stringByAppendingPathComponent:` for that purpose.
Answer: You need to specify NSDocumentDirectory rather than NSDocumentationDirectory.
Comment: @marccenedella Yep, I've been burned by that one myself; it's very easy to miss.
Comment: Thanks! I was making such a rookie mistake :D
Comment: XCode autocomplete offers the 'incorrect' one first. From what I can see, it might also be used far less, i.e., the list of references to 'NSDocumentationDirectory' on stackoverflow are overwhelming to this same problem: http://stackoverflow.com/search?q=nsdocumentationdirectory

Small but painful bug.

NSDictionary writetofile is not working


How to get values which changed during node edit in node api?

Question: I have a node with user entity reference field. Now I want to get newly added users id's to this node via this field in hook_node_update
What is the best way?
Answer: The $node argument to hook_node_update contains a $node->original object. With that you can identify the newly added user IDs by comparing $node->your_user_ref_field to $node->original->your_user_ref_field.


Chaos theory, equation-free modeling and non-parametric statistics

Question: Being interested in complex systems and trying to get a beginner's understanding of the field, today I ran across this interesting article in Quanta Magazine on chaos theory and equation-free modeling. I realize that non-parametric statistics implies lack of certainty in data distributions' parameters (please correct me, if I'm wrong). I'm not sure about chaos theory, but but it seems to me that, at least, equation-free modeling is a term, closely related to non-parametric statistics.
Question: what are relations, if any, between the emphasized topics and non-parametric statistics (I am not interested in details, but rather sources and nature of relations; references are welcome)?
Comment: A lot of statisticians will argue exactly what the phrase *non-parametric statistics* means exactly (I know the definition that applies to my field...), but "lack of certainty in data distributions's parameters" can be easily misinterpreted as parametric statistical inference ("I have uncertainty about $\mu$ and $\sigma$ that define my normal distribution").
Comment: @AleksandrBlekh, for me a good characterization of *nonparametric* is *lack of distributional assumptions* (as you wrote above). Suppose we have variables $y$ and $x$. In a *parameteric* case, we assume the shape of the conditional distribution of $y|x$ to be known but the specific parameters unknown (e.g. Normal with unknown mean, unknown variance); we then go after estimating the unknown parameters. In a *nonparametric* case we do not assume to know the shape.
Comment: I'm going to get flack for this, I can see it, but...the definition of non-parametric estimator that I prefer is "an estimator whose solution cannot be characterized by a finite number of parameters".  For example, the simplest NP estimator is the empirical distribution function, which places probability mass $1/n$ at each observed time point. All possible monotonic step functions cannot be described by a finite set up of parameters, unlike, say all possible normal distributions.
Comment: Note that the tag `stochastic-processes` does not describe [chaotic dynamics](https://en.wikipedia.org/wiki/Chaos_theory), which are deterministic. If you examine the evolution in time from two nearby points in state space, the difference between the two trajectories will be random for a stochastic system, but the trajectories will diverge exponentially in time for a chaotic system.
Comment: @CliffAB: Thank you for pointing that out. My wording indeed could be more precise. As you can guess, the implied meaning is not the uncertainty about, but the lack of any distributional assumptions (if I can use these terms; please correct me, as I am not a statistician).
Comment: Non-parametric approaches are not equation free. Think of fitting a curve where you have a function form of a curve, such as $sin(x)$, vs. where you don't have it, but specify that the curve must have minimum length. In the latter case you still have a variational *equation* despite not having the functional form of the curve.
Comment: ...but while I consider that a valid definition, it doesn't quite reveal the motivation of non-parametric estimators: to be "infinitely flexible". However, it doesn't take much exposure to NP estimation to see that this is the *goal* of NP estimators, but it is not necessarily achieved. Sorry to go off on a side tangent from your original question...
Comment: @AleksandrBlekh, every time I write "always" Glen_B shows up with a counter example :) So, I'll say only that "non-parametric" doesn't imply there is no equation. Like in my example there could be a variational equation or some kind of min/max condition to be satisfied. So, parametric approaches define a solution on a narrowly defined class of functions such as $\sin(k x)$, while non-parametric approaches tend to be less specific like "shortest line with continuous second derivative"
Comment: Also, there's no chaos theory per se, in my opinion.
Comment: @Aksakal: Thank you for clarification. If I understood you correctly, non-parametric approaches always (?) imply the existence of some _equations_, representing forms, other than a core _function_, such as a set of _constraints_ (as in your example).
Comment: @CliffAB: Thank you for expanding on the topic. I think it is a bit clearer to me now, but I still need some time to digest the info properly (unfortunately, lack of my formal math/stats background is showing; hopefully, eventually, I will overcome this problem).
Comment: @Aksakal maybe we should all team up and write a paper defining exactly what non-parametric actually means.
Comment: @CliffAB, aren't there already papers on the subj?
Comment: @Aksakal: perhaps? I've seen the definitions in books but I can't say I've ever read it in an article. And I've seen plenty of disagreement in different subfields about what it actually means.
Comment: @EdM: Thank you for your comment. IMHO, the exponential divergence might be naively explained by the presence of constantly increasing entropy along the time dimension. Looking at the Wikipedia article you've referenced, I'm curious whether chaotic dynamic systems can contain entropy component at all and, if so, how does it fit into such systems being deterministic.
Comment: @RichardHardy: I appreciate your explanation, which is very clear. Returning to the core of my question, would you agree with Aksakal's comment above that _non-parametric_ approaches do not imply being _equation-free_?
Comment: @AleksandrBlekh, I do not have enough experience to say anything authoritative on that question. I have not dealt with it much at all.
Comment: @RichardHardy: I see. Thank you for your feedback.
Answer: In the limit, this becomes a question of whether you consider time-series analysis to be non-parametric statistics.
The approach of the PNAS paper by Ye at al., cited in the Quanta Magazine article, might be considered a generalization of standard time-series analysis. As stated in the Supporting Information Appendix to the article: "reconstructions of a dynamic system can be made using successive lags of a single time series...if enough lags are taken, this form of reconstruction...preserves essential mathematical properties of the original system." This Appendix has (for me, at least) the clearest explanation of the approach.
What this approach adds is a weighting procedure that can deal better with the problems posed by underlying non-linear dynamics. (I will leave aside the question of whether there really is a chaos theory, as raised in comments above.) A "tuning parameter," $\theta$, is added to the model, which gives nearby points "stronger weighting, allowing the model to be adaptive to local influences and therefore, nonlinear."
For $\theta=0$, "the model reduces to an autoregressive model"; hence the first sentence of this answer. Forecast skill is then assessed as a function of $\theta$. In the data analyzed in that paper, "forecast skill peaks when $\theta$ is ~ 2, which is evidence for nonlinearity in the aggregate time series." Information from multiple time series is then used to try "to identify informative environmental variables and elucidate potential mechanisms."
I suppose that one could find an analogy between this approach and non-parametric tests that make no assumptions about underlying distributions, in that the approach of Ye et al. makes no assumptions about the form of the equations of the underlying dynamic model. But I think that drawing the analogy would be a disservice both to "non-parametric statistics," whatever that means, and to the work presented by Ye et al.
Comment: +1. But I had a brief look at the PNAS paper (as well as at the popular article that @AleksandrBlekh linked to), and somehow it looks like a fairly simple exercise in time series analysis, but filled with buzzwords, complemented with appropriate strawmen and unbelievably oversold and over-hyped. That's to put it *politely*. I don't understand what it does in PNAS, but then it's not the first time I have this feeling about PNAS. Not surprising that people get confused about how all these fancy terms are related.
Comment: To EdM's point in the quote he cites, distributed lags of a univariate time series amount to a Koyck model in econometrics and is nothing new. Where I think EDM models do diverge significantly from traditional time series analysis is in leveraging a non-reductionistic, non-mechanistic approach to model building. This is a definite rejection of the "Occam's Razor" assumptions underlying nearly all traditional analysis.
Comment: Thank you so much for taking time to answer my question. I appreciate your detailed answer (+1). It will take some time for me to process the information, considering that I'm an aspiring complex systems enthusiast.


Is there a more efficient way to have this C program print different things based on results of addition?

Question: I'm trying to write a C program which reads three integers, where if any two of those integers equal the remaining integer, it will print all integers within 1 and 10. If not, it will ask for three more integers and print the number of integers that are divisible by 6.
This is my program, but it looks long-winded. Is there a cleaner way to do it? Thanks.
#include<stdio.h>

int main(){
    int x,y,z;

    printf("Enter three integers.\n");
    scanf("%d %d %d", &x, &y, &z);

    if(x + y == z){
        printf("1, 2, 3, 4, 5, 6, 7, 8, 9");
    }
    else if(x+z == y){
        printf("1, 2, 3, 4, 5, 6, 7, 8, 9");
    }
    else if(y+z == x){
        printf("1, 2, 3, 4, 5, 6, 7, 8, 9");
    }
    else {
        int a, b, c, count;
        count = 0;
        printf("Type in three more integers.\n");
        scanf("%d %d %d", &a, &b, &c);
        if(a%6 == 0){
            count++;
        }
        if(b%6 == 0){
            count++;
        }
        if(c%6 == 0){
            count++;
        }
        printf("%d integers are divisible by 6.", count);
    }
}

Comment: If your code works, but you're looking to improve it, it's best to try the [Code Review SE](https://codereview.stackexchange.com).
Comment: You can use functions to avoid duplicating code.
Comment: `if (x + y == z || x + z == y || y + z == x) { …print 1..9… } else { … }` —— and `printf("%d integers are divisible by 6\n", (c % 6 == 0) + (b % 6 == 0) + (a % 6 == 0));` — and do away with `count` and the conditionals.  You should check that the inputs were successful before using the results.  You should end printing with newlines.  It's not immediately obvious why you don't print `10` too, given the (loose) specification of "integers within 1 and 10".
Comment: You can use arrays and loop instead of repeating the same code on individual variables.
Comment: Combine the first three if conditions with '||', also with the sub if conditions
Answer:
Can put three if conditions on one using || operator. This tutorial can help. link
If only wish to check divisible for 3 integers (c % 6 == 0) + (b % 6 == 0) + (a % 6 == 0) can help to get the count.
And reusing the same variables will help in optimizing memory.

Solution code :
#include <stdio.h>

int main()
{
    int x, y, z;
    printf("Enter three integers.\n");
    scanf("%d %d %d", &x, &y, &z);
    if(x + y == z || x+z == y || y+z == x)
    {
        printf("1, 2, 3, 4, 5, 6, 7, 8, 9\n");
    }
    else
    {
        printf("Type in three more integers.\n");
        scanf("%d %d %d", &x, &y, &z);
        printf("%d integers are divisible by 6\n", (x % 6 == 0) + (y % 6 == 0) + (z % 6 == 0));
    }
}

Comment: Suggestion: the return value of `scanf` is not checked. If i didn't successfully read all three ints, the variables are uninitialized and then you're dealing with undefined behavior.
Comment: Yes @not_castillo
Comment: So for point 2, (c % 6 == 0) will return a 1 if true and 0 if false?
Answer: "Is there a cleaner way to do it?"
Yes! Write less code and reuse code and variables...
EDIT: removed bad code example and effected light "touch-ups"
void get3ints( char *prmpt, int *x, int *y, int *z ) {
    printf( "Enter three %sintegers.", prmpt );
    scanf( "%d %d %d", x, y, z ); // != 3 /* omitting check */
}

int main() {
    int x, y, z;

    get3ints( "", &x, &y, &z );
    if( (+x+y-z) * (+x-y+z) * (-x+y+z) ) {
        get3ints( "more ", &x, &y, &z );
        printf( "%d integers are divisible by 6.\n", !(x%6) + !(y%6) + !(z%6) );
    } else
        printf( "1, 2, 3, 4, 5, 6, 7, 8, 9\n" );

    return 0;
}

Without clarification of the objective, words like "efficient" (in the title) or "cleaner" (in the OP body) are subject to interpretation.
Below is code that fulfills the objective, built up of several discrete functions. One could argue that this is "cleaner" because each function cares little how its subordinate functions do their job; just that the job is done properly and the result returned is what is wanted.
Many ways to skin a cat
int t1( int x, int y, int z ) { return x+y==z || x==y+z || y==x+z; }
int t2( int x, int y, int z ) { return !(x%6) + !(y%6) + !(z%6); }

int get3ints( char *prmpt, int(*f)(int, int, int) ) {
    int x, y, z;
    printf( "Enter three %sintegers.", prmpt );
    scanf( "%d %d %d", &x, &y, &z ); // != 3 /* omitting check */
    return f(x,y,z);
}

bool phase2() {
    printf( "%d integers are divisible by 6.\n", get3ints( "more ", t2 ) );
    return true;
}

bool phase1() {
    int rval;
    printf( &"\0 1, 2, 3, 4, 5, 6, 7, 8, 9\n"[rval = get3ints( "", t1 )] );
    return rval;
}

int main() {
    phase1() || phase2();
    return 0;
}

Comment: Neat to rewrite the sum.
Comment: In the second rewrite, the order of evaluation in the second `printf()` is not defined, so it is not clear that `help()` will be called before the comparison/addition is done.
Comment: Using one comma operator instead of two braces would work correctly, but isn't a particularly great idea otherwise.  What you've written (in the revised answer) is essentially what I'd write — give or take the placement of the open braces.  (To a first approximation, I use [Allman](https://en.wikipedia.org/wiki/Indentation_style) style; you're using 1TBS.)
Comment: @AllanWind Just a little bit bored... `:-)` Cheers! `:-)`
Comment: @JonathanLeffler Thank you. I've removed that code example (that came from a "bad day.") I was unaware the "order is not defined". My experience had always been 'R-to-L' for pushing parameters on the stack. Thank you for the correction. `:-)` (How would you feel if I ditched the braces, though, and exploited the comma to have the help() ahead of the printf() ... JK... JK!!!)
Comment: Unlike the conditionals the two multiplications might overflow.  I am much less worried with the additions.
Comment: @AllanWind You are right about o'flow. Then again, the user could enter INT_MAX-1 twice and INT_MIN+1 as the 3rd, and then the addition results are out of range... "To infinty and beyond!!!" `:-)`
Answer: Here is version that uses:

Function input() to reduce duplicate code of the prompt and reading data from user.
scanf() error handling
Early return for less branched code
Macro SUM to make variable part stand out, and derive the index of the right hand side to reduce chance of error.
Macro MOD6 to make the variable part stand out.
Reuse array variable a just to make it a line shorter.  This is usually bad practice.

#include <stdio.h>

int input(const char *prompt, int *a) {
    printf("%s", prompt);
    if(scanf("%d %d %d", a, a + 1, a + 2) != 3) {
        printf("failed\n");
        return 1;
    }
    return 0;
}

int main() {
    int a[3];

    if(input("Enter three integers.\n", a))
        return 1;
    #define SUM(i, j) a[(i)] + a[(j)] == a[3 - (i) - (j)]
    if(SUM(0, 1) || SUM(0, 2) || SUM(1, 2)) {
        printf("1, 2, 3, 4, 5, 6, 7, 8, 9");
        return 0;
    }
    #undef SUM

    if(input("Type in three more integers.\n", a))
        return 1;
    #define MOD6(i) !(a[(i)] % 6)
    printf("%d integers are divisible by 6.\n",
        MOD6(0) + MOD6(1) + MOD6(2)
    );
    #undef MOD6
}

Comment: To me, having `input` return `1` for failure and `0` for success, while it mirrors `main`, reads wrong. It feels like this is saying: "if input succeeds, error and quit."
Comment: That's too inflexible. It doesn't provide the option to handle an input failure by prompting again.
Comment: @Fe2OS3 I welcome any and all input.
Comment: @Chris It's a fair comment.  There is one happy path (0) and many failures (!0). Reading it as "if input returns an error" and with enough of these it becomes the norm.  Reverting the logic in main seemed more ugly.  I did consider assign it to a variable with a goto done and return said variable.  goto usually earns me downvotes.
Comment: My two cents? (Who asked?) `input()` currently only fails when `scanf()` fails, and then it's a quick march out the door... "Out the **door**??" Hey! why not just go straight to the `exit(1)` (with , naturally) `input()` is then `void input()` **Do or die!!** `:-)`


Is it ok to get a massage BEFORE a competition?

Question: I recently went for a professional medical massage, and felt incredibly relaxed afterwards. He only did my torso and back, but the breathing feeling was so free I felt incredible. I sit all day in front of a computer, so my shoulders are usually quite tight - I felt like in heaven.
I could imagine, that the relaxed feeling would allow me much better control over my movement during a run, as well as breathing ability.
About 24h after though, I had quite some sores along the primary massaged muscle groups. Two days later I'm feeling fine again, but my upper body is as tense as always. So I'm wondering if a massage is a stress on the body that would interfere with the stress of a competition.
Is there any drawback to getting a massage before a competition? (I run, swim and bike, but I assume this could apply to any sports discipline).
Answer: I am a massage therapist. I specialize in deep tissue and sports massage. A Swedish massage is NOT a deep tissue massage. True deep tissue is concentrated on specific areas of the body. To do a full body deep tissue it would take HOURS to complete. Deep tissue is NOT recommended before any athletic event. It would be too invasive and change the body too much. A sports massage is recommended before any sporting event. This includes friction, tapotement, range of motion of the joints to increase or decrease stiffness and gentle stretching.
Post event massage is what we call the cool down massage... this is where you would receive a Swedish or circulatory massage to help flush the built-up lactic acid, decrease muscle soreness and aches.
Comment: I don't know why this was downvoted. This seems like a perfectly valid answer from someone with experience in the field.
Comment: Possibly the inclusion of personal details implying an invitation to engage with said field-experienced likely-professional looked a lot more like spam and/or copy-pasta?
Answer: I am not a massage therapist, but I have received many different types of massages and treatments over the years, so I can share my experience.
If you get a deep tissue massage - sometimes called a "swedish" massage - the muscle areas that were massaged are going to feel a little sore afterwards and the muscles themselves are going to be dehydrated somewhat. This is why after getting a deep tissue massage you are encouraged to drink plenty of water to help re-hydrate your muscles. I would definitely not recommend getting a massage like that before a competition. It will hurt your performance, not help.
If you get a relaxation massage where they use light pressure then I would say go ahead and do that before a competition if you feel it helps your movement during a run and with breathing.
Having said all of that, what I would think to be the best kind of treatment to receive before a run or any kind of competition would be some assisted stretching after you perform a light warm-up routine. Spend 10-20 minutes doing light exercise (just enough to where your heart beat is slightly elevated) then get on a table where someone can help you go through some stretching routines. That has helped me the most before any kind of competition and gets me the most loosened up.


How to avoid Input a String in an Integer value using Try Catch (C++)

Question: I just want the user to avoid Input a String in an Integer value using Try Catch because using a while loop does not work at all. I know how to use Try Catch in Java but I do not in C++. I have been trying something like this:
#include <iostream>

using namespace std;

main(){
   int opc;
   bool aux=true;
   do{
   try{
       cout<<"PLEASE INSERT VALUE:"<<endl;
       cin>>opc;
       aux=true;
   }
   catch(int e){
             aux=false;
             throw e;
             cout<<"PLEASE INSERT A VALID OPTION."<<endl;
           }
           }while(aux==false);
       system("PAUSE");
         }//main

Answer: There are easier and better ways to do it, but if you really want exceptions, you could enable them and catch std::ios_base::failure. Something like this:
int main() {
    int opc;
    bool aux = true;
    cin.exceptions(std::istream::failbit);
    do {
        try {
            cout << "PLEASE INSERT VALUE:" << endl;
            cin >> opc;
            aux = true;
        }
        catch (std::ios_base::failure &fail) {
            aux = false;
            cout << "PLEASE INSERT A VALID OPTION." << endl;
            cin.clear();
            std::string tmp;
            getline(cin, tmp);
        }
    } while (aux == false);
    system("PAUSE");
}

Answer: Under normal circumstances the std::cin as all istreams does not throw an exception when the data provided does not fit. The stream changes its internal state to false. So you may simply do something like:
int n;
std::cin >>n;
if(!std::cin) {
 // last read failed either due to I/O error
 // EOF. Or the last stream of chars wasn't
 // a valid number
 std::cout << "This wasn't a number" << std::endl;
}

Answer: int opc;
cin >> opc;

The bad bit of the stream will be set when you try to read a non-numeric value. You can check if the stream is in a good state or not. If not, reset the state flags and try the reading again if you want. Note that when the bad bit is set, any following read is ignored. So what you should do before another trial is to first clear the bad bit of the input stream and ignore the rest of the bad input.
// If the input stream is in good state
if (cin >> opc)
{
   cout << opc << endl;
}
else
{
   // Clear the bad state
   cin.clear();

   // Ignore the rest of the line
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

// Now if the user enters an integer, it'll be read
cin >> opc;
cout << opc << endl;


finding the complex eigenvalues from complex eigenvector

Question: The question:
A system of differential equations can be created for two masses connected by springs between one another, and connected to opposing walls. The dependent variables form a 4 × 1 vector y consisting of the displacement and velocity of each of the two masses. For the system y′  =  Ay, the matrix A is given by:
\begin{bmatrix}0&0&1&0\\0&0&0&1\\-37&3&-4&0\\3&-37&0&-4\end{bmatrix}
Because the system oscillates, there will be complex eigenvalues. Find the eigenvalue associated with the following eigenvector.
\begin{bmatrix}-4i\\4i\\24+8i\\-24-8i\end{bmatrix}
I thought about this question, and it would be easy if the matrix was in 2x2 form and i could use the quadratic formula to find the complex eigenvalues. But with a 4x4 matrix I am not sure how to proceed. So just to give it a try I found the determinant by reducing the matrix into upper triangular form:
\begin{bmatrix}-37&3&-4&0\\3&-37&0&-4\\0&0&1&0\\0&0&0&1\end{bmatrix}
Thus eigenvalues = $\lambda-37$ and $\lambda= 1$
If I have started correctly, how do I proceed?
Answer: Your method is wrong.  To find eigenvalues you need to equate $\det(A-\lambda I)$ to zero then solve.  That is, you have to subtract $\lambda I$ then find the determinant - you seem to have (partially) found the determinant then subtracted $\lambda I$.
However, the problem is actually much easier than this.  To say that a non-zero vector $v$ is an eigenvector of $A$ with eigenvalue $\lambda$ means
$$Av=\lambda v\ ;$$
since you have been given $A$ and $v$, it is easy to use this equation to find $\lambda$.
Answer:
Each eigenvector should corresponds to only one eigenvalue.
By definition, an eigenvector satisfies $Av = \lambda v$.
From $Av=\lambda v$, the first row gives us the constraint that $$24+8i = \lambda (-4i).$$
We just have to solve for $\lambda$.
Comment: So $\lambda = 8i$?
Comment: can't be. if the answer is $8i$, the RHS would be negative but the LHS is not a real number. $\lambda = \frac{24+8i}{-4i}=\frac{6+2i}{-i}=2 \cdot \frac{3+i}{-i}$. Can you simplify it by multiplying both the numerator and denominator by $i$?
Comment: you are right, thanks.
Comment: ahh sorry, it would be $2-6i$ but this returned as incorrect answer in my assignment.
Comment: I get $-2+6i$, can you check if you made a sign error mistake?
Comment: argh, seems the 10 hours of math i have been doing today has taken its toll. Yes you are right. it is $-2+6i$ thank you
Comment: Why are you specifically choosing $λ=\frac{24+8i}{−4i}$
Comment: The first row has lots of $0$ and a single $1$, so I just pick the first row of the equation $Av=\lambda v$ to obtain an equation. You can pick the other rows as well. Second row would be simple too.
Answer: We have to get
 $$Av=\lambda v$$
$$\begin{bmatrix}0&0&1&0\\0&0&0&1\\-37&3&-4&0\\3&-37&0&-4\end{bmatrix}\begin{bmatrix}-4i\\4i\\24+8i\\-24-8i\end{bmatrix} = \begin{bmatrix}24+8i\\-24-8i\\-96+128i\\96-128i\end{bmatrix} =(-2+6i)\begin{bmatrix}-4i\\4 i\\24+8i\\-24-8i\end{bmatrix}   $$
Thus the eigenvalue is $-2+6i$
Comment: I appreciate your response, but I do not see the logic (also your answer was wrong as per my assignment)
Comment: @TheoBendit  Oh, yes. Thanks for the comment. I edited my answer.
Comment: @Forextrader The logic is $Av=\lambda v$ sure you see the logic. The typo is fixed now.
Comment: Sorry, but how were you able to find $(-2+6i)?
Comment: @Forextrader  $ (24+8i)/(-4i) = -2+6i$


How many 0,1 bit strings of length 10 are there which do not contain a string of 1001001?

Question: I've never been asked a question involving how many do not contain a specific string and I'm not quite sure how to go about answering this question.
Comment: How many _do_ contain the string $1001001$?  What the amount is, subtract it from the total number of bitstrings of length $10$.
Comment: How do I get started on that path I'm very new to discrete math.  Would I do 11 c 7 for that?
Comment: My answer had a minor problem, and since I posted it, there are many other answers now that should provide details on how to go about this process.
Answer: Hint, following on JavaMan's comment:  You probably know there are $2^{10}$ total 10-bit strings.  Now to contain $1001001$ you can have a string of the form $xxx1001001$ (where the $x$'s are either $1$ or $0$)  or a few similar choices, so subtract them.  The challenge comes in whether you have subtracted a string twice-so think about the various patterns and see if the same string can satisfy more than one.
Comment: All the possible patterns are:
1001001xxx
x1001001xx
xx1001001x
xxx1001001
Is this correct?
Comment: @Anthony:  that is correct.
Answer: This problem is actually just a little tricky. JavaMan's suggestion in the comments is the way to go, but there's a little sting in the tail.
In a ten-bit string the seven-bit string $1001001$ can start at the first, second, third, or fourth bit. Each of those starting positions leaves $3$ bits that can be anything. Thus, there are $2^3=8$ ten-bit words of the form $1001001xxx$, $8$ more of the form $x1001001xx$, and so on, for a total of $4\cdot8=32$ ten-bit strings containing $1001001$.
BUT there might be some ten-bit strings that have $1001001$ starting in more than one of the four possible starting positions, and if so, we've counted those strings twice. A little thought reveals that there is exactly one such string, $1001001001$; we counted it once for $\color{red}{1001001}001$ and once for $100\color{red}{1001001}$. Thus, the number of strings containing the substring $1001001$ is really only $32-1=31$.
Finally, there are $2^{10}=1024$ ten-bit strings, so there are $1024-31=993$ that do not contain the substring $1001001$.
Comment: Thank you very much for your help, I believe I understand the question and the answer now.
Comment: @Anthony: You're most welcome.


Can I learn an instrument just by practicing songs?

Question: I am a working individual with tons of responsibility at work giving me little to no time to practice in the conventional way. I can't consistently keep practicing scales and stuff. I just picked up the bass as something to de-stress and play for like 30 minutes every 2 days. I was wondering if it is a good strategy for me to learn bass solely by learning songs.
The way I see it:
Pros:

I'll stay motivated. I love playing basslines.
I won't dread the 30 minutes.

Cons:

I won't have "formal" training.
??

I have read How can I move beyond learning songs? but I can develop Ear Training and whatever else along the way. I know that if I sit and start learning scales and chords, I am never going to pick up the bass.
Any comments?
(I don't intend to make this skill marketable or make money off it. I merely want it to have something to calm myself at the end of a rough day. Musical Meditation if you may.)
Comment: There is a famous drum quote which is attributed to many famous drummers that goes _If you can practice 1 hour each day, a full year, with full dedication and efficiency, you would be a great player in the end_. It sounds much easier then it actually is but even if you can keep up your current pace consistently, just listening to songs won't be able to satisfy your hunger soon and you'll switch to the dark side of technical issues :) You don't have to be proficient in the technical lingo but still it doesn't hurt to know the overall concepts, harmony basics etc.
Comment: There's a lot of pearl clutching going on in this thread, but the short answer to "Can I?" is "YES absolutely." Most of the answers focus on why you might not want to and why it might take longer, but in light of your stated goals there is no reason why you need lessons.
Comment: I'm not a teacher, nor have I tried this method, so I don't feel qualified to answer the question, but at least one bass teacher seems to think it's possible: [How To Play Bass In 50 Songs](https://how-to-play-bass.com/play-bass-in-50-songs)
Answer: I think motivation is absolutely essential. If you're not enjoying what you're doing, then why are you doing it?!
But you can probably handle one scale, right? Once or twice through, as a warm-up? And then after a few days or weeks, switch to a different one.
You can also make your own exercises. Any difficult part from a song you want to play, isolate it and repeat until it's under your fingers. If you can see immediate results (or maybe after a few days), you may come to better appreciate what scales and exercises can do for you.

One big difficulty you may encounter with an entirely empirical approach (ie. no theory) is that you won't be able to talk about what you're doing with other musicians.
Answer: These methods should be fine if you intend to just be a 'loungeroom' musician, doing it for fun and yourself. Scales/chords though are a necessary evil, when learning violin as a kid/teen I dreaded all that, but years later am so glad I persisted.
Answer: Yes, but only to a certain extent. Really though, do what you want to do. As long as it's fun, keep doing. Realistically, however, it doesn't matter what you practice if you're only doing it for 30 minutes every two days. There's only so much you can actually do in that little time frame.
Anyone who is in -- or has been in -- a serious practice regimen will likely tell you that they spend 30 minutes or more just warming up, let alone actually practicing anything. With a string instrument, most of your playing will be straight muscle memory. Repetition will make you better and faster. It takes a lot of time and patience, not to mention playing a lot of the same exercises over and over again, to build up the kind of muscle memory required for anyone to ever consider you to be a more technical musician.
Since you're practicing bass I'm going to go ahead and assume it's an electric bass. Slap technique is almost all muscle memory. It's such a repetitive motion that it's basically impossible to learn without putting a lot of time into repetitive exercises. Practicing an easy slap song might help you get the idea down but when you're ready to move on to more complicated techniques you'll find that you just can't do them.
The above mentioned doesn't even get into theory. It's one thing to recognize a pattern on your bass and go: "that's A major." It's another thing to recognize that pattern all the way up and down your fret board. And further more, just knowing where and how to play A major is great, but when and why you're playing it is another field of consideration. Going through a chord chart is nice, but again, it's one thing to go: "this chord means this, which means I can play this;" it's another thing to do this at 140+ bpm.
Finally, the best way to learn still is -- and probably always will be -- to get a teacher. They help focus you. They can look at your technique and find faults that you might not notice. They can help you overcome learning plateaus. If you're having trouble with a certain song or idea they can help smooth over the details in a much shorter amount of time. Etc. etc.
All this aside, you can learn an instrument by just playing songs. But the level of skill that you will obtain will be much less than you might hope for. You will eventually find that song that you just have to play; but unless you really practice, the sad truth of it is you might not ever actually be able to. But as I said originally, if you're having fun just keep having fun and don't worry too much about it.
Comment: "unpleasant" but helpful, in fact.
Answer: at least learn enough theory so that you can correctly identify and be mindful of the key and rhythmic signature you're playing in
maybe look up the suzuki method?
Answer: I personally don't believe in scales and other "purely technical exercises". [This is from a classical pianist point of view; other instruments and styles may be different.] There are lots of good exercises in the pieces themselves, namely the difficult places. They are both well-motivated and well-targeted, i.e. you know why you practice them and where you are going to need them. The most difficult thing is probably going to be that you need to stop and really practice them instead of just playing through the whole piece every time.
You'll find some of the difficult places when you practice. To find the others, play through the piece and record it. During recording you'll find new difficult places (because you'll be a little bit more stressed). Then listen to the recording and be surprised: some of the places you thought went quite well don't actually sound that good. :-) So, now you have some exercises.
Another difficulty is that you need to know when you're doing things properly. For this you probably need either a teacher or some good books, videos and lots of reflection. One important thing which can be difficult to learn just on your own is to identify and release unnecessary tension, while still having the necessary tension to be able to play. Now, playing "properly" might not be a priority for you but it will be much more enjoyable (and relaxing!) that way. Note that those purely technical exercises won't help here because you can do those wrong, too!
You can also learn theory this way. You have to identify what you don't know (this can be quite difficult, too!) and then go figure it out. If you do this by getting answers to the whys in addition to the hows, and going as deep as you can, you should be able to get a good grasp of the theory you need.
So does this actually work? I did exactly this for the first 3-4 years. I did have a teacher and that certainly helped in the beginning. Later my teachers rarely taught any technique; I got that from books, experimenting etc. At some point I also started to study theory "formally" but it came quite easily since I already had lots of working knowledge.
The only instrument exercises I have ever done were the scales which I had to learn to pass an exam. I haven't touched or needed them since (in the form scales are learned; of course scales appear in music but there's usually something different, like different fingering, skipping some notes, ...). I never studied the standard piano exercises like Hanon or Czerny. Using this method I got through university and nobody ever complained that my technique is faulty, quite the opposite in fact. I like to think that this is because I never wasted time and energy on useless exercises ;-) Had my teachers forced me to do exercises I would probably have quit quite early.
So, my final answer is this: I do believe it's possible, and even a good way if you have good self-discipline, but having a teacher for some time will be very useful.
Answer: Playing the instrument is a great way to learn the instrument - to a certain extent. By playing rote patterns (which is what I think you mean by "playing songs") you will develop proficiency in executing passages, and you will train your ear and your time. As you learn more of these rote patterns, you will give your brain a lot of useful context, and you'll probably find yourself changing the patterns around, developing your own ideas, and building your own idea of how music works.
If this is what you enjoy, and it gives you pleasure, you will learn from it. However, if your goal is to become a more proficient musician, perhaps to be able to improvise a bass part from chord changes or by ear from another person's playing, or to write your own songs, you might or might not get there as fast as you want to by playing rote passages for half an hour a day. If that's what you want and you think you're not getting there, the next step would be to learn some theory - which, given the amount of musical material you've already put into your head, will likely be relatively easy for you.
Answer: One of my favourite de-stressing pasttimes is to sit on the sofa, with the TV on, not listening to it noodling away on my guitar (6 string or bass) playing songs or just twiddling about playing nothing in particular. So relaxing for me. I utterly get where you're comeing from !
Although this keeps the dexterity up etc and often results in learning a ew lick or something, I wouldn't call it practice: It's just a funthing to do like watching a film or going for a walk. Just happens to be quite productive :-)
Sometimes I concentrate a bit and learn a song- play it on CD etc, play along, find it on the guitar as I go. That's closer to practice, but still just for fun usually.
I've done this for 35 years and for me it worked a treat. I now play lead guitar in 3 rock bands (one has been going for 30 years) and am loving music- but my motivation is just that I like to play. There's absolutely nothing wrong with what you're doing, and if your motivation is just to relax, then you don't need formal training. It's about what you like to hear yourself playing :-)


Re-indexing an array by matching value

Question: I'm trying to manipulate the sorting order of an array. I would like to get the matching fruit - in this case the apple - as the third index on the array.
$array_fruit[] = array('fruit' => 'apple', 'color' => 'red');
$array_fruit[] = array('fruit' => 'banana', 'color' => 'yellow');
$array_fruit[] = array('fruit' => 'kiwi', 'color' => 'green');
$array_fruit[] = array('fruit' => 'orange', 'color' => 'orange');
$array_fruit[] = array('fruit' => 'strawberry', 'color' => 'red');
$array_fruit[] = array('fruit' => 'lemon', 'color' => 'yellow');

$i = 0;

$array_inStock = array();

foreach($array_fruit as $fruit)
{
    if($fruit['fruit'] == 'apple')
    {
        $array_inStock['3'] = array('fruit' => $fruit['fruit'], 'color' => $fruit['color']);
    }
    else
    {
        $array_inStock[$i] = array('fruit' => $fruit['fruit'], 'color' => $fruit['color']);
    }
    $i++;
}

asort($array_inStock);

print_r($array_inStock);

I don't understand what is going wrong here. Anybody an idea? Big regards.
Comment: So what is the result of current code?
Comment: Array
(
    [1] => Array
        (
            [fruit] => banana
            [color] => yellow
        )

    [2] => Array
        (
            [fruit] => kiwi
            [color] => green
        )

    [3] => Array
        (
            [fruit] => orange
            [color] => orange
        )

)
Answer: try this
although this is a lengthy way, but works perefect no matter where apple is currently
$array_stock =array();$i=0;
foreach($array_fruit as $k=>$v)
{
if($v['fruit'] =='apple')
    {
        $array_stock[3]=$v;
        if($k>3)
            array_push($array_stock,$array_fruit[3]);
        continue;
    }
if(array_key_exists($i,$array_stock))
{
    array_push($array_stock,$v);
}
else
{
    $array_stock[$i]=$v;
    $i++;
}
}

ksort($array_stock);
echo "
";
print_r($array_stock);
echo "
";

DEMO
Comment: awesome, this solved the puzzle. Big thanks to all of you who have helped
Comment: @ian if `apple`s come always on top `[0]` or before [3]`` then u can remove `if($k>3)` condition
Answer: Am I misreading this or do your lines
$array_fruit[] = array('fruit' => 'apple', 'color' => 'red');
$array_fruit[] = array('fruit' => 'banana', 'color' => 'yellow');
etc.

rewrite the contents of the array each time? Instead you want
$array_fruit[0] = array('fruit' => 'apple', 'color' => 'red');
$array_fruit[1] = array('fruit' => 'banana', 'color' => 'yellow');
etc.

Comment: No, the indexing adds up as your second example automatically
Comment: not necessary to assign index...it will automatically placed. read this : http://php.net/manual/en/language.types.array.php
Answer: I suppose that going through the foreach loop has this events:

$i = 0, array('fruit' => 'apple', 'color' => 'red') is processed and $array_inStock['3'] = array('fruit' => 'apple', 'color' => 'red') is created
$i = 1, array('fruit' => 'banana', 'color' => 'yellow') is processed and $array_inStock['1'] = array('fruit' => 'banana', 'color' => 'yellow') is created
$i = 2, array('fruit' => 'kiwi', 'color' => 'green') is processed and $array_inStock['2'] = array('fruit' => 'kiwi', 'color' => 'green') is created
$i = 3 !!!, array('fruit' => 'orange', 'color' => 'orange') is processed and $array_inStock['3'] = array('fruit' => 'orange', 'color' => 'orange') is created that OVERWRITES the first processed array('fruit' => 'apple', 'color' => 'red')...

What You should do instead:
foreach($array_fruit as $fruit) {
    if($fruit['fruit'] == 'apple') {
        $array_inStock[3] = $fruit;
    } else if($i != 3) {
        $array_inStock[$i] = $fruit;
        $i++;
    }
}

This will end up with apple being the index 3...
Comment: When there are more fruits the result ends up being this: Array
(
    [0] => Array
        (
            [fruit] => banana
            [color] => yellow
        )

    [1] => Array
        (
            [fruit] => kiwi
            [color] => green
        )

    [4] => Array
        (
            [fruit] => lemon
            [color] => yellow
        )

    [2] => Array
        (
            [fruit] => orange
            [color] => orange
        )

    [3] => Array
        (
            [fruit] => strawberry
            [color] => red
        )

)
Comment: so there will be no apple in the result
Comment: This is great, but now apple has an index of 4 instead of 3 (I have added a few more fruit to the first array in my post)
Comment: Hmm, OK, so apple shouldn't be last, but has an index 3? Why do You need this?
Comment: The matching fruit will be echoed to the screen as the 3rd result in the first row, so when I change the matching word to look for it will always end op the 3rd result and all the other results will go down (second row)
Comment: This works as a charm although it is now not matching towards apples but towards $i. So when I change apple to banana I will have another problem. Hope you'll understand
Comment: Hmm, not sure, but if You need to have some element at concrete index that cannot be done by sorting or ordering, this has to be hardcoded... I don't see any logic here that could be implemented as an algorithm... But OK, I changed the code once again slightly...check it...
Comment: This was how I ended up before creating the provided sample code. The problem now is that the code stopped running when it reaches the index 3. Array
(
    [3] => Array
        (
            [fruit] => apple
            [color] => red
        )

    [0] => Array
        (
            [fruit] => banana
            [color] => yellow
        )

    [1] => Array
        (
            [fruit] => kiwi
            [color] => green
        )

    [2] => Array
        (
            [fruit] => orange
            [color] => orange
        )

)
Comment: And isn't this just because You have only 4 items in $fruit array? If so, the last index is 3. Try adding other items and the result array should be bigger... aaaaaaaahh, now I see it...put the $i++ after the end of `else if() {}`... This will evoke the first index to be 1 (not 0) but this shouldn't be a problem - should it? Or You can set `$i = -1;`
Comment: There are 6 items in the fruit array. When I put the $i++ on the right spot, the array index [5] is then missing. Look at the answer from diEcho. That solved the puzzle. Big thanks for you help.
Comment: Yes, I gave him 1+. And I'm giving up :-)
Answer: Try this :::

$array_fruit = array();
$array_fruit[] = array('fruit' => 'apple', 'color' => 'red');
$array_fruit[] = array('fruit' => 'banana', 'color' => 'yellow');
$array_fruit[] = array('fruit' => 'kiwi', 'color' => 'green');
$array_fruit[] = array('fruit' => 'orange', 'color' => 'orange');

print_r($array_fruit);

$i = 0;

$array_inStock = array();

foreach($array_fruit as $fruit)
{
    if($fruit['fruit'] == 'apple')
    {
        $array_inStock['3'] = $fruit;
    }
    else
    {
        $array_inStock[$i] = $fruit;
        $i++;
    }
}

asort($array_inStock);
print_r($array_inStock);

Comment: the result is: Array
(
    [0] => Array
        (
            [fruit] => banana
            [color] => yellow
        )

    [1] => Array
        (
            [fruit] => kiwi
            [color] => green
        )

    [4] => Array
        (
            [fruit] => lemon
            [color] => yellow
        )

    [2] => Array
        (
            [fruit] => orange
            [color] => orange
        )

    [3] => Array
        (
            [fruit] => strawberry
            [color] => red
        )

)  so there are no apples left

Re-indexing an array by matching value


Proof that the largest eigenvalue of a stochastic matrix is $1$

Question: The largest eigenvalue of a stochastic matrix (i.e. a matrix whose entries are positive and whose rows add up to $1$) is $1$.
Wikipedia marks this as a special case of the Perron-Frobenius theorem, but I wonder if there is a simpler (more direct) way to demonstrate this result.
Answer: Here's a really elementary proof (which is a slight modification of Fanfan's answer to a question of mine). As Calle shows, it is easy to see that the eigenvalue $1$ is obtained.  Now, suppose $Ax = \lambda x$ for some $\lambda > 1$.  Since the rows of $A$ are nonnegative and sum to $1$, each element of vector $Ax$ is a convex combination of the components of $x$, which can be no greater than $x_{max}$, the largest component of $x$.  On the other hand, at least one element of $\lambda x$ is greater than $x_{max}$, which proves that $\lambda > 1$ is impossible.
Comment: Unlike Perron-Frobenius, however, this does not show that $\lambda=1$ is a simple eigenvalue (that is, having a 1-dimensional eigenspace) in case the matrix in question is irreducible. Right?
Comment: @Bach: Right; this does not show that 1 is a simple eigenvalue.
Comment: Can the vector $x$ be complex? I think the argument still largely works for complex vectors, but requires minor adjustments.
Comment: This is (essentially) a proof of the Gershgorin circle theorem in disguise, I think.
Comment: Very nice! If you apply the same reasoning to $A^2 x = \lambda^2 x$, you can conclude that $\lambda \geq -1$ as well. (One can use the elementary fact that the rows of $A^2$ still sum to 1, or just use the above estimate twice.) And this is the best inequality possible, since permutation matrices can have eigenvalue $-1$.
Comment: Elegant and neat.
Comment: Note that the same argument can be adapter to (countably) infinite matrices by taking $x_{sup}$ instead than $x_{max}$.
Answer: Say $A$ is a $n \times n$ row stochastic matrix. Now:
$$A \begin{pmatrix} 1 \\ 1 \\ \vdots \\ 1 \end{pmatrix} =
\begin{pmatrix}
\sum_{i=1}^n a_{1i} \\ \sum_{i=1}^n a_{2i} \\ \vdots \\ \sum_{i=1}^n a_{ni}
\end{pmatrix}
=
\begin{pmatrix} 1 \\ 1 \\ \vdots \\ 1 \end{pmatrix}
$$
Thus the eigenvalue $1$ is attained.
To show that the this is the largest eigenvalue you can use the Gershgorin circle theorem. Take row $k$ in $A$. The diagonal element will be $a_{kk}$ and the radius will be $\sum_{i\neq k} |a_{ki}| = \sum_{i \neq k} a_{ki}$ since all $a_{ki} \geq 0$. This will be a circle with its center in $a_{kk} \in [0,1]$, and a radius of $\sum_{i \neq k} a_{ki} = 1-a_{kk}$. So this circle will have $1$ on its perimeter. This is true for all Gershgorin circles for this matrix (since $k$ was taken arbitrarily). Thus, since all eigenvalues lie in the union of the Gershgorin circles, all eigenvalues $\lambda_i$ satisfy $|\lambda_i| \leq 1$.
Answer: For $A$ left stochastic, we can show that $A$ doesn't increase the 1-norm, i.e.,
$$\|Ax\|_1\leq\|x\|_1$$
Then $$\|Ax\|_1=\|\lambda x\|_1=|\lambda|\|x\|_1\leq\|x\|_1$$
which is $|\lambda|\leq 1$, we are done, but how to show above inequality? For convenience, let's set stochastic matrix
$$A=\begin{pmatrix}a_{11}& a_{12}\\a_{21}& a_{22}\end{pmatrix}$$
Then
\begin{eqnarray*}\|Ax\|_1&=&|a_{11}x_1+a_{12}x_2|+|a_{21}x_1+a_{22}x_2|\\&\leq& a_{11}|x_1|+a_{12}|x_2|+a_{21}|x_1|+a_{22}|x_2|\\&=&|x_1|+|x_2|\\&=&\|x\|_1\end{eqnarray*}
For n-dimensional matrix, it can be shown in same manner.
For a right stochastic matrix, $x$ should be multiplied on the left: $\|xA\|_1\leq\|x\|_1$, where $x$ is a row-vector.
Comment: Why $a_{11} |x_1|+a_{21}|x_1|=|x_1|$? $A$ has a row sum of $1$, but not a column sum of $1$.
Answer: It is an elementary exercise to show that a matrix $A \in \textsf{M}_n (\mathbb{C})$ has row sums equal to one if and only if $Ae = e$ (here, $e$ denotes the all-ones column vector of size $n$). Thus, $1 \in \sigma(A)$ whenever $A$ is stochastic.
Now, if $(\lambda,v)$ is an eigenpair of $A$, in which $A$ is stochastic, then, without loss of generality, it may be assumed that
$$ \vert \vert v \vert \vert_\infty := \max_{1 \le k \le n} \{ \vert v_k \vert \} = 1.$$
Thus, there is a positive integer $i$, $1 \le i \le n$, such that $\vert v_i \vert = 1$. Since $Av = \lambda v$, by the mechanics of matrix multiplication and the above, we have
$$\vert \lambda \vert =
\vert \lambda \vert\cdot 1 =
\vert \lambda \vert \cdot \vert v_i \vert =
\vert \lambda v_i \vert = \left\vert \sum_{j=1}^n a_{ij} v_j \right \vert
\le \sum_{j=1}^n a_{ij} \vert v_j \vert
\le \sum_{j=1}^n a_{ij} = 1,
$$
i.e., $\vert \lambda \vert \le 1$.
Answer: Call A a $n \times n$ stochastic matrix and denote with $(\lambda,\textbf{x})$ one of its eigenpair.
Obviously $1$ is an eigenvalue for $A$, indeed follow directly from the definition of row-stochastic [column-stochastic] matrix that $\textbf e$ $=(1\dots1)^{T}$ is a right [left] eigenvector associated with $1$.
Using induced matrix norm $\parallel\parallel_{1}$ or $\parallel\parallel_{\infty}$ ,  it's easy to prove that the spectral radius $\rho(A)\leq 1$ :
$$
|\lambda|= \frac{||A x||}{||x||} \leq max_{||x||=1} ||Ax||= ||A||
$$
Now, since $||A||_{1}$  [respectively $||A||_{\infty}$ ] is the maximum absolute column [row] sum of the matrix, we have
$||A||_{1}=1$ if $A$ is a column-stochastic matrix and
$||A||_{\infty}=1$ if $A$ is a row-stochastic matrix,
and then in any case $|\lambda|\leq 1$.
Answer: If $A \in \textsf{M}_n (\mathbb{C})$, then
$$\begin{Vmatrix} A \end{Vmatrix}_\infty := \max\limits_{1\le i \le n} \sum_{j=1}^n \vert a_{ij} \vert$$
is a matrix norm and $\rho(A) \le \begin{Vmatrix} A \end{Vmatrix}$ for any matrix norm $\vert \vert \cdot \vert\vert$ (e.g., Theorem 5.6.9 in the first-edition of Horn and Johnson's Matrix Analysis). If $A$ is stochastic, then $\begin{Vmatrix} A \end{Vmatrix}_\infty = 1$ so that $\vert \lambda \vert \le \rho(A) \le 1$.
Answer: Here's a very elegant proof that utilizes the Perron–Frobenius theorem:  let $y$ be the left Perron vector normalized so that $y^\top e = 1$. By the PFT, $y^\top A = \rho(A) y^\top$ since $A^\top \ge 0$. Because $Ae = e$, we have
$$1 = y^\top e = y^\top (Ae) = (y^\top A) e = (\rho(A) y^\top) e = \rho(A) (y^\top e) = \rho(A)\cdot 1 = \rho(A).$$


How to execute the "while" statement after fetchmail do his job?

Question: I have this script inside /etc/ppp/ip-up.d/script
<code>#!/bin/sh
/usr/sbin/postqueue -c /etc/postfix -f
/usr/bin/fetchmail -v -f /etc/fetchmailrc -L /var/log/fetchmail.log
while ! postqueue -p | grep -q empty; do
  sleep 1
done
killall wvdial
</code>
in this script it disconects my modem when detects that the mail queue is empty, also i wish to check if the fetchmail process is still running or execute the part of the while just and just after the fetchmail command finish to do his job completely.
some help please?
Answer: Since you are not running fetchmail in daemon mode, the script will not start the while loop until fetchmail has exited.
I don't think you will save any time by starting your while loop before fetchmail finishes running.
Comment: Yes thats the point y was thinking at, until fetchmail exit of work it will do the while check, but in the practice i dont know why but it is procesing the while check and if the queue gets empty it disconects my modem letting to fecthmail at the half way, thats why i would like to add a command to start the while loop before fetchmail or add that besides to check if the queue is empty check if the process of fecthmail is not running
Comment: Can you please post a sanitized version of your fetchmailrc?
Comment: defaults
        proto pop3
poll pop.gmail.com
        user "userxxx"
        pass "password"
        is userxxxx
        ssl
Comment: I think something else must be ending your connection early. Put some debug echo statements in your script to tell you when things are happening.
Comment: Hmm great idea, please how can i put this?
i am not too experiencied in bash scripting
Comment: just add the echo command with distinct output between each line: http://pastebin.com/Z7VQrDJY
Comment: OK i have putted inside the echo output, now how can i see the output of the full script when it starts to excute?
Comment: Try disabling it from running automatically, then you can run it in an interactive shell to see the output. Alternatively, there may be some output in a log in /var/log.


Get human readable Windows WiFi adapter name

Question: The following code lists all WiFi adapters (see https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifi.wifiadapter.findalladaptersasync?view=winrt-22621#windows-devices-wifi-wifiadapter-findalladaptersasync):
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
foreach (var adapter in result)
{
    System.Console.WriteLine("Adapter: " + adapter.Id + ", " + adapter.Name + ", " + adapter.ToString());
}

But the adapter.Id is some cryptic string and adapter.Name returns the Windows machine name. Is there a way to get a human readable representation of the WiFi adapter name?
Regards,
Comment: The simplest wait is to use WlanEnumInterfaces (https://learn.microsoft.com/en-us/windows/win32/api/wlanapi/nf-wlanapi-wlanenuminterfaces)
Comment: The example returns the WLAN_INTERFACE_INFO_LIST structure that contains array of the WLAN_INTERFACE_INFO structures each one has strInterfaceDescription field. That is what you are looking for.
Comment: Can you point me to the part where a human readable name is produced? The linked example also seems to return only GUIDs.
Answer:     Console.WriteLine("Adapter: " + adapter.Id + ", " + adapter.Name + ", " + adapter.ToString());

Please Try Console.Writeline();?


Is the identity permutation a transposition?

Question: I've heard every permutation can be expressed as a composition of transpositions. How would this be done with the permutation $\pi:\{1\}\to\{1\}$? This only seems possible if one includes the identity as a transposition.
Comment: The identity permutation is most certainly not a transposition, but it is a product of transpositions. What do you get if you multiply a transposition by itself?
Comment: @bof But there are no transpositions on the symmetric group over a singleton.
Comment: By convention an empty product is the multiplicative identity.  Correspondingly the product of no transpositions is the identity permutation (the identity element of any symmetric group).  In any case transpositions have odd parity while the identity map is of even parity.
Answer: The identity permutation is precisely the composition of zero transpositions.
Comment: @user3865391 It has zero transpositions, but it has the identity element by **definition** of a group. Indeed it is the trivial group.
Comment: I don't understand. So the symmetric group on one element can't be generated by transpositions?
Comment: @user3865391: it is generated by the empty set of transpositions.


Campo com # não aparece no Mysql por _GET

Question: Bom pessoal, não sei onde posto a pergunta..
Desculpe-me se estiver em área errada!
Bom, eu estou quebrando a cabeça com um código na minha pagina.
O código funciona ele envia os dados para o meu banco de dados, só que não está mandando um pedaço do campo por ter esse character " # " ai só está mandando metade.
Olhem:

Está chegando o resultado só que não chega o final do código nick=Teste"#6287"
Olhem o resultado no banco de dados:

Código do Arquivo processar.php
<?php
$conexao = mysqli_connect("phpmyadmin", "user", "pass");
mysqli_select_db($conexao, "db");

     $novoemail = addslashes($_GET["novoemail"]);
     $nick = addslashes($_GET["nick"]);

       $inserir = "INSERT INTO ajuda (id, email, usuario) VALUES (NULL, '$novoemail', '$nick');";
        mysqli_query($conexao, $inserir) or die (mysqli_error($conexao));
        echo"";
    ?>

Answer: Você terá que codificar ele, porque o # direto é reconhecido pelo navegador com "URL dinamica" que é usado para principalmente interagir no front-end, com HTML, CSS e JavaScript, inclusive fiz uma resposta sobre o assunto:

https://pt.stackoverflow.com/a/235335/3635

Tendo entendido o porque isto falha agora vamos ao passo de corrigir, para que funcione você terá que codificar (trocar no caso) o # para %23, ou seja vai ficar assim:
email@example.com&nick=teste%236287

Mas fique tranquilo, quando usar $_GET['nick'] vai retornar teste#6287 perfeitamente.
Se o link for gerado pelo seu script então para facilitar pode usar urlencode(), mais ou menos assim:
<?php
$email = urlencode('email@example.com');
$nick = urlencode('teste#6287');

echo 'Link';
?>

Outra coisa, NÃO USE addslashes para escapar em mysqli, esta função pode até funcionar aparentemente, mas não tem este propósito, ainda mais dependendo de codecs (variações de utf8, latin1, etc) por ai, então dependendo do codecs talvez algum caractere poderá ocasionar erro de sintaxe, então não faça isso:
 $novoemail = addslashes($_GET["novoemail"]);
 $nick = addslashes($_GET["nick"]);

O ideal é usar a função própria para isto, mysqli_real_escape_string, assim:
 $novoemail = mysqli_real_escape_string($conexao, $_GET["novoemail"]);
 $nick = mysqli_real_escape_string($conexao, $_GET["nick"]);

Answer: O que você pode estar fazendo é separar o campo de envio :

firstname.lastname@example.com&nick=Teste&num=6287

E depois "juntar" os dois no PHP:
$nick = addslashes($_GET['nick'] . "#" . $_GET['num']);

Comment: então o jeito é manipular o texto que você quer, alterando o valor da string para envio e depois alterar novamente o valor: --JS-- var exemplo = "Teste#1234"; var resultado = exemplo.replace("#", "."); alert(resultado);  --PHP-- $nick = addslashes($_GET['nick']); $nickCorrigido = str_replace('.', '#', $nick); echo $nickCorrigido;
Comment: Mas ai eu teria que criar uma outra variável para pegar o numero?
Porque eu já tenho uma variável que pega o nome#numero junto..
Comment: sim, as âncoras não são enviadas do navegador para o servidor.
Comment: você está pegando por input essas informações?
Comment: Sim estou..
Teste#6287
Comment: var nick = document.getElementsByClassName("lien-blanc-gras")[0].textContent;
Comment: faz 2 , um para o nick e outro para o numero
Comment: A pagina não é minha da onde tou puxando os dados então não tem como eu fazer.
Comment: Consegui amigo obrigado!!


Rules content unpublish in 30 days

Question: I've followed this thread https://groups.drupal.org/node/240678#comment-782543, but that's based on a date field and it has a different scenario.
My idea is: When a new content is created, after 30 days will be automatically unpublished.
How can I achieve this without using additional date fields?
Answer: Instead use Auto Expire module, Using this module you can set the node to unpublish after 30 days.

For your case set zero in purge field, otherwise it will automatically delete from database.

This module allows site administrators to set expiration times for
  content types.
End users creating content that has auto expiry set cannot control the
  expiry time. They could be allowed to renew the content for one or
  more cycles.

Rules content unpublish in 30 days


Unable to Use Output from dorny/paths-filter@v2 in Startegy Matrix ( Github Action )

Question: I am trying to take output from dorny/paths-filter@v2 which is actually a list of files that got changed, and use it as a multiple input for Strategy matrix in Github Actions.
Although i see relevant file path that got changed, which looks something like "aws/dev/something/yo.yaml" for eg. in the plugins output, but the strategy matrix just dont like it and throws errors like
Error when evaluating 'strategy' for job 'deploy'. .github/workflows/main.yaml (Line: 59, Col: 15): Error parsing fromJson,.github/workflows/main.yaml (Line: 59, Col: 15): Unexpected character encountered while parsing value: a. Path '', line 0, position 0.,.github/workflows/main.yaml (Line: 59, Col: 15): Unexpected value ''

My Github Action file
name: Yo

on:
  push:
    branch:
    - main

jobs:
  changes:
    runs-on: ubuntu-latest
    outputs:
      files: ${{ steps.filter.outputs.aws_files }}

    steps:
    - uses: actions/checkout@v2

    - uses: dorny/paths-filter@v2
      id: filter
      with:
        base: ${{ github.ref }}
        list-files: 'escape'
        filters: |
          aws:
          - added|modified: 'aws/**'

  deploy:
    runs-on: ubuntu-latest
    needs: changes
    strategy:
      matrix:
        file: ${{fromJson(needs.changes.outputs.files)}}
      fail-fast: false

    steps:

    - name: Lets See
      env:
        file: ${{matrix.file}}
      run: |
        echo ${{env.file}}

Tried multiple option of the plugin like shell, csv but no luck
Comment: Can you use `list-files` as `json`?
Comment: Shouldnt `${{ steps.filter.outputs.aws_files }}` be instead `${{ steps.filter.outputs.aws }}`? Notice its `aws` and not `aws_files`
Comment: I get a error like this if i change that
`Error when evaluating 'strategy' for job 'deploy'. .github/workflows/main.yaml (Line: 60, Col: 15): Unexpected value 'true'`
Comment: Can you do an echo of `${{ steps.filter.outputs.aws }}` and show me its value?
Comment: sure, it gives output as "true" if i echo that
Comment: Whats the output of `${{ steps.filter.outputs.aws_files }}`?
Comment: its the actual file name with absolute path `aws/dev/myfile.txt`
Comment: Is that a string as an array serialized?
Comment: i think thats what the problem is, i think its giving a string ( not 100 % )
Comment: bingo, that did the trick, i was avoiding to put json and tried everything else,
Answer: The issue is that strategy matrix expects the response from fromJSON to be an array. That's not happening here, and hence the error.
So you need to make sure dorny/paths-filter@v2 send back the list of files formatted as a JSON array.
- uses: dorny/paths-filter@v2
  id: filter
  with:
    base: ${{ github.ref }}
    list-files: 'json'
    filters: |
      aws:
        - added|modified: 'aws/**'

Notice that list-files: 'json' instead of list-files: 'escape'.
Comment: The goal here is to get the list of files that changed and act on that data
To get the list of file i have to use `aws_files` and not `aws` as u said that only gives boolean


Generating very few samples from a probability distribution using MCMC?

Question: Since MCMC converges to target only after taking very large number of steps, what if I want to have just say 10 samples from target distribution? Do I still have to generate lots of samples, and then discard the rest?
Or like machine learning models, is there seperate training and testing part, where a model is trained to project an easy-to-sample distribution to our desired one?
Comment: MCMC is used to sample from an unknown distribution, the more observations you can get the better as it better approximates it. Why do you want to select only 10 observations? Are you trying to randomly sample 10 observations from this distribution? If so, then you would pick 10 observations at random from all the available ones, however keep in mind that the observations are likely correlated.
Comment: Yes, usually MCMC has a "warm-up" period during which you do not sample. This step is used to make sure that there are no problems at the beginning with convergence. If, however, you had strong knowledge / you knew that your MCMC would start at the right point of the distribution then you would have no need for a warm-up period. if so, you could ignore the warm-up and go straight to sampling.
Comment: please let me know if this is duplicate. I tried searching around but don't really have the stat. vocabulary to do that properly
Comment: Can you increase the number of steps?
Comment: sorry @user2974951, couldn't understand your question. Increase what steps?
Comment: I'm coming from ML. using GAN for example, you could ask for any number of samples, which will respect the distribution the data GAN was trained on. With MCMC now, we have to take that infinite walk every time we need to sample from target distribution, right? I mean is this how MCMC usually implemented in softwares? I'm sensing I'm missing something obvious here :(
Answer: MCMC stands for "Markov chain Monte Carlo". There are two aspects to how long you will run your MCMC sampler: one for the Markov chain and one for the Monte Carlo part.

Markov chain : Like user2974951 wrote in their comment, usually there is a burn-in or "warm-up" period, where you can't necessarily give your Markov chain a good starting value, so your chain takes time to get to areas of high probability. This part may be ignored and thrown away, since the samples are not representative of the distribution. However, if you have a strong knowledge of the areas of high probability, you can start your Markov chain from a point in that area, in which case a "warm-up" is not essential. In any case, this part does not factor into the sampling.
Monte Carlo: To answer your question, I would need to know more about what you're using your samples for. But generally, if you're doing MCMC, samples are used for Monte Carlo averages. That is, if your target distribution is $\pi$, and you're using MCMC to estimate $E_{\pi}g = \int g(x) \pi(dx)$, then from a Markov chain sample $X_1, \dots, X_n \sim \pi$, the Monte Carlo estimator of $E_{\pi}g$ is
$$\dfrac{1}{n} \sum_{t=1}^{n} g(X_t)\,. $$
That is a true average is estimated by a sample average. Now the question is, if you're given a distribution, and given samples from that distribution, then are 10 samples enough to estimate the mean of the distribution relatively well? The answer is almost unequivocally, no.  10 samples from the target distribution is nearly not enough, let alone the fact that MCMC gives you "corrupt" samples, since they are correlated. To understand how many samples after "burn-in" you may need, read this post and my answer there.
Comment: @ShihabShahriar Why are you generating samples if you aren't interested in population statistics? I am curious. Also, why are you interested in removing correlations by taking the Mth sample, when you aren't interested in population statistics?
Comment: My understanding is, this is what Generative Adversarial Network does. You've got dataset of 10,000 pics of cute cats to train a model, and want to build an app that generate new cat pics whenever user asks for, by sampling from the same unknown distribution that generated your dataset. I understand there are better alternatives to MCMC for this particular task, but this is an example where population params aren't really our goal.
Comment: Thank you. So if I don't really care about population statistics, but only on generating samples, I don't really need the Monte carlo part, right? Bishop's PRML mentions taking every Mth sample if we want them de-correlated, so there is no avoiding generating lots of samples anyway...
Comment: @ShihabShahriar Ah ok. That's helpful. Yeah, so then you also don't need to worry about thinning ("taking every Mth draw"). But you do need to be careful about burn-in.


Multiple dice rolls (D&D Skill challenge)

Question: In Dungeons and Dragons there is something called a skill challenge, which involves rolling some dice (no surprise there).
An example of a skill challenge:
Skill challenge DC 25 thievery. Roll a d20* and add your thievery bonus (let's say 11) and check if the result matches or goes over 25 take note and roll again (next turn).
As soon as you have five rolls under 25 you fail. As soon as you have 2 rolls over or equal to 25 you succeed in the skill challenge.
How do I calculate the odds of being successful in a skill challenge?
With the numbers I provided I need at least a 14 to match the DC 25. That means that I have $7/20$ odds of matching (or going over) the DC (and $13/20$ for the opposite).
If I only had to match the DC once the math would be easy:
$(13/20)^5$ is the probability of failing, so $1-(13/20)^5$ is the probability of succeeding.
* d20 = 20 sided die, numbered 1-20.
Comment: So in 5 rolls, you need at least 2 rolls (not necessarily consecutive) to be over 25 with the bonus?
Comment: @Jacob I can have at most 5 rolls under 25 (with the bonus). And need 2 rolls over 25. Meaning that I will roll at least 2 times and at most 6 times.
Answer: An equivalent way of phrasing this is that you roll 6d20 (because $6=5+2-1$ is the number of rolls after which you'll definitely have either succeeded or failed, and can't have done both), and succeed if at least two of those are higher than the threshold number. So your overall failure probability is
$$p^6 +6 p^5(1-p) \, ,$$
where $p=13/20$ is the probability of failing on any given roll (the first term counts the probability of failing 6 times, the second the probability of failing 5 times and succeeding once).
So, in your specific example, the probability of success is
$$1-(13/20)^6-6(13/20)^5(7/20) \approx 0.6809 \, .$$
Comment: Thank you for your answer. I feel a bit embarrassed for being so close and still not seeing it. Is it hard to generalize this method for any number of failures and successes?
Comment: I tried to generalize your answer but I'm not sure I did everything right (it's been a long time since statistics classes) maybe you can have a look?
Answer: Trying to generalize @Micah answer.
If we define:

$m$ - maximum number of misses (originally $5$)
$n$ - required number of successes (originally $2$)
$p$ - probability of failing any given roll (originally $13/20$)
$x = m + n - 1$ - number of rolls after which we'll have either succeeded or failed (originally $6$)

The overall failure probability can calculated using this:
$$
\sum_{i=0}^{n-1} \binom{x}{x-i} \times p^\left(x-i\right) \times \left(1-p\right)^i
$$

$s$ is the odds of success.
Example 1
Given $m = 5$, $n = 1$ and $p = 13/20$
we get
$$
x=5 \\
s = 1 - \left( 1 \times \left( 13/20 \right)^5 \times \left (1 - \left( 13/20 \right) \right)^0 \right)
$$
Example 2
Given $ m = 5$, $n = 2$ and $p = 13/20$
we get
$$
x=6 \\
s = 1 - \left( 1 \times \left( 13/20 \right)^6 \times \left (1 - \left( 13/20 \right) \right)^0 + 6 \times \left( 13/20 \right)^5 \times \left (1 - \left( 13/20 \right) \right)^1 \right)
$$
Example 3
Given $m = 5$, $n = 3$ and $p = 13/20$
we get
$$
x=7 \\
s = 1 - \\ \left( \\ 1 \times \left( 13/20 \right)^7 \times \left (1 - \left( 13/20 \right) \right)^0 + \\ 7 \times \left( 13/20 \right)^6 \times \left (1 - \left( 13/20 \right) \right)^1 + \\ 21 \times \left( 13/20 \right)^5 \times \left (1 - \left( 13/20 \right) \right)^2 \right)
$$
Comment: The thing you need to be careful about when generalizing is the "you'll definitely have either succeeded or failed, and can't have done both" condition. It's possible to have some very similar-sounding rules to these ones where there's no such number -- then you have to worry a lot more about order. For example, if you decided that a natural 20 counted as 2 successes and a natural 1 counted as 2 failures, then rolling 6d20 and coming up with 5 20s and a 1 could be either an overall success or failure, depending on the order you rolled them in.
Comment: This looks almost right to me, except that a lot of your $m$s should be $x$s (since that's the number of rolls you're making). Basically, you want to take the binomial expansion for $\left(p+(1-p)\right)^x$ and truncate it after $n$ terms.
Comment: Okay, now I believe you. :)
Comment: @Micah Now you got me curious of how to solve for that case, maybe I'll create a new question for that. I have also taken the liberty of adding some example values.