SwiftUI ScrollView is not able to disable vertical bounce?

Question: There was a property in the initializer with ScrollView(alwaysBounceVertical: false) but I cant't seem to find it anymore.
Does anyone know how I can disable the vertical bounce / overscroll on a SwiftUI ScrollView?
Answer: Yes, it has been removed from the initializer of ScrollView, now you have to update the appearance of the UIScrollView in order to restrict the scrolling.
 UIScrollView.appearance().bounces = false

This line will restrict the scrolling, you can apply this in the AppDelegate(didFinishLaunching) or the init() method of your View.
Comment: @NabeelNazir I have gone through the UIScrollView documentation, and all the properties mentioned in the base class can be applied on the  appearance(). I have implemented the same thing in my app, and it works fine for me. But if you want to disable it on a particular screen and then you would have to enable it in the view onDisappear.
Comment: Can we use
UIScrollView().alwaysBounceVertical = false ??
Comment: @NabeelNazir I guess this won't work, the way you are suggesting is basically for an instance of the UIScrollView , so for that, you must have an instance,  and that won't be possible with SwiftUI. So applying it on the appearance of it will eventually update or override the underlying appearance of the UIScrollView class, so it will be applicable throughout the application.

I have explained it in detail with this answer:-https://stackoverflow.com/a/59897811/6445871 , have a look at it.
Comment: I've read from somewhere that appearance() doesn't have bounces property anymore, is it true ? If yes, then what will be the other way to disable the bounce of scrollview.
Comment: The problem I have with this solution is that without bouncing I can't have large navigation titles. But with the bouncing there is a lot of flickering.
Answer: Yes, it changed in Beta 4:
ScrollView(.vertical, showsIndicators: false) { ... }

The new initializer is:
public init(_ axes: Axis.Set = .vertical, showIndicators: Bool = true, content: () -> Content)

Comment: Sadly, thats only for the axis direction of the ScrollView. I need to disable the bounce when a user scroll fast. In UIKit there is a scrollView.bounce = false, and in previous beta there was a alwaysBounceVertical. But the sdk changed and I can't seem to disable it anymore
Comment: I'm afraid ScrollView is very limited at the moment. Lots of things you cannot do with it.
Comment: Aah what a bummer! I do think so too! At least thanks for your time!
Answer: The only way I managed to make the bounce disappear...
func setup()->Bool{
    UIScrollView.appearance().bounces = false
    return false
}

@main
struct myApp: App {
    private var useless:Bool = setup()

    var body: some Scene { [...]


Angular JS multiple select unable to get the value selected

Question: I am trying to populate a multiple select option using Angular JS . This is my List
 var depositoryList =[
{
  "depos":"Any",
  "deposName":"Any"
},
{
  "depos":"DUB",
  "deposName":"DUBAI"
},
{
  "depos":"MUM",
  "deposName":"MUMBAI"
},
{
  "depos":"SNG",
  "deposName":"SINGAPORE"
}],
// didnt Work
 $scope.depositoryId = {value:{depos:'Any'}}

This is how i populate it in HTML
 <select multiple
ng-model="depositoryId.value"
data-ng-options="obj.depos + ' - ' + obj.deposName for obj in depositoryList track by obj.depos">
</select>

1)I tried to set default value to Any and i am not able set them .
2) I tried to get the selected value and did alert($scope.depositoryId.value.depos) . Its giving me an undefined alert message
where am i going wrong
Answer: Final Edit:
Show Any- Any without any break and get selected values in ng-model

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope) {
  $scope.depositoryId = ['Any'];
   $scope.depositoryList =[
{
  "depos":"Any",
  "deposName":"Any"
},
{
  "depos":"DUB",
  "deposName":"DUBAI"
},
{
  "depos":"MUM",
  "deposName":"MUMBAI"
},
{
  "depos":"SNG",
  "deposName":"SINGAPORE"
}];
});

<!DOCTYPE html>

    <select multiple="true" ng-model="depositoryId" ng-options="obj.depos as (obj.depos + ' - ' +obj.deposName) for obj in depositoryList">
</select>

{{depositoryId}}

Comment: I am able to display the list , i want the first value [Any] to be selected by default . I am also trying to retrieve the value back in controller
Comment: tried this first itself , also tried now. It didnt work :(
Comment: did you changed ng-options as i did and what you got the ng-model once you selected, `{{depositoryId.value}}` put this somewhere in your html code it will print the value as you select
Comment: If i change ng-options as you did , my dropdown is fully added with values sucha as Nan . I want my dropdown to be displaying like this Any-Any
Comment: I am trying to do multiple select dropdown . I have already implemented single select dropdown
Comment: **Updated** for `multiple select options`, notice you must hold `ctrl` and click to select multiple options to see in action
Comment: I have tried this too , but when i try to display multiple select items as Any- Any (key value pair)it breaks automatically
Comment: @Praveen i updated the code for final time, its already more than 100 time edited for little thing, look if its indeed what you want
Comment: Thanks for your help ! simple things take the most time :P !!
Answer: For a more elegant solution without hardcoding the initial value, since you have the string needed in your array, you could do:
<select multiple='true' ng-init="depositoryInitialValue = depositoryList[0].deposName"
                        ng-model="depositoryInitialValue"
                        ng-options="obj.depos as (obj.depos + ' - ' + obj.deposName) for obj  in depositoryList">

</select>

See plunkr here
hope it helps.

var app = angular.module('ngApp', []);

app.controller('MainCtrl', ['$scope', function($scope) {
  'use strict';

  $scope.depositoryList = [{
    "depos": "Any",
    "deposName": "Any"
  }, {
    "depos": "DUB",
    "deposName": "DUBAI"
  }, {
    "depos": "MUM",
    "deposName": "MUMBAI"
  }, {
    "depos": "SNG",
    "deposName": "SINGAPORE"
  }]

}]);
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>maxisam's ngApp</title>
  <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css" rel="stylesheet">
  <link rel="stylesheet" href="style.css">

  <select multiple='true' ng-init="depositoryInitialValue = depositoryList[0].deposName" ng-model="depositoryInitialValue" ng-options="obj.depos as (obj.depos + ' - ' + obj.deposName) for obj  in depositoryList">
  </select>

 {{depositoryInitialValue}}

Comment: I am trying to implement a multiple select dropdown
Comment: My bad, missed that requirement, that is fixed in the [plunkr](http://plnkr.co/edit/P65CP6H4Hu5MZkc1vRwZ?p=preview) now
Comment: When i try to display it as key- value pair it breaks automatically eg : Any-Any, MUM-MUMBAI
Comment: I don't get what you say, also displaying k-v pairs is part of the requirement in your post?
Comment: yes , please have a look `obj.depos + ' - ' + obj.deposName` . This will display in k-v  (Any - Any)
Comment: check update [plunkr](http://plnkr.co/edit/P65CP6H4Hu5MZkc1vRwZ?p=preview), is that what you want?


Find combined max value

Question: I have the following DataFrame:
{'date': '2019-10-21', 'hour': 3, 'id': '1'},
{'date': '2019-10-21', 'hour': 4, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '1'},
{'date': '2019-10-20', 'hour': 1, 'id': '1'},
{'date': '2019-10-21', 'hour': 0, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '1'},
{'date': '2019-10-19', 'hour': 5, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '2'},
{'date': '2019-10-20', 'hour': 0, 'id': '3'}

I need to find for each id the latest date and hour so for instance for id=1 I want 2019-10-21 and 4 while I am getting the correct date but hour=5
Answer: Use DataFrame.sort_values by all 3 columns and remove duplicates by DataFrame.drop_duplicates by column id:
L = [{'date': '2019-10-21', 'hour': 3, 'id': '1'},
{'date': '2019-10-21', 'hour': 4, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '1'},
{'date': '2019-10-20', 'hour': 1, 'id': '1'},
{'date': '2019-10-21', 'hour': 0, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '1'},
{'date': '2019-10-19', 'hour': 5, 'id': '1'},
{'date': '2019-10-20', 'hour': 0, 'id': '2'},
{'date': '2019-10-20', 'hour': 0, 'id': '3'}]

df = pd.DataFrame(L)
df['date'] = pd.to_datetime(df['date'])

df = df.sort_values(['id','date','hour'], ascending=[True, False, False]).drop_duplicates('id')
print (df)
        date  hour id
1 2019-10-21     4  1
7 2019-10-20     0  2
8 2019-10-20     0  3

Find combined max value


Social sharing meta tags display by SPA Angular hosted on IIS

Question: I have SPA AngularJS app hosted on IIS. The problem is displaying meta tag generated by ngMeta (https://github.com/vinaygopinath/ngMeta). I don't have any server side app (only ASP.NET web API which provides data). Is any possibility to make my site 'Social Friendly' without any server-side prerendering?
Now it look likes as here
Answer: You can set fallback, static HTML meta tags that are removed when Angular is available (using ng-if).
<title ng-bind="ngMeta.title">Fallback title</title>
<meta name="description" content="Fallback description" ng-if="false" />
<meta name="description" content="{{ ngMeta.description }}" />

Social media crawlers generally don't execute Javascript, so they would see Fallback description, while Google's Javascript-enabled crawler would pick up the description set by ngMeta.description.
Note that the above code provides a site-wide title, description and other meta tags. If you'd like to customize the meta tag values according to the route, you can do something like this

Identify user-agent of request to server
If user-agent matches a known social media crawler's user agent string, redirect to a script instead of serving the file.
Check the requested route (for example, /blog) and return or generate an HTML page with the meta tags relevant to the blog page.


When and how to use weights for sequence analysis in social science?

Question: Weighting in sequence analysis
So far, I have scarcely found papers that address the issue of weighting for sequence analysis (using for example the optimal matching algorithm). Sequence analysis normally involves several steps:

setting or calculation of substitution and insertion/deletion costs,
computation of distance matrices and
following cluster analyses or discrepancy analyses[1].

At least, the R-package TraMineR (see Gabadinho et al. 2010 and Gabadinho et al. 2011, p. 11) and the Stata-ado SEQCOMP by Laurent Lesnard makes it possible to include weights at step 1 and 3.
Furthermore, Lesnard explicitly recommends the usage of sample weights for steps 1 and 3:

"Sample weights should only be used to calculate transition matrices, and consequently
  substitution costs. Instead of counting the number of transitions, it is simply
  the weighted number of transitions that should be taken into account. The
  matching procedure in itself, namely, the comparison of pair of sequences, does
  not require any weights; it is by definition a one to one procedure. However, sample
  weights should be turned on to interpret results, for instance, if cluster analysis
  is used, the size of the clusters obtained must be weighted."
  Lesnard (2010: 415, endnote 12)

Open questions
Nonetheless, there does not seem to be a consensus in the literature when and which weights are needed or useful.

What do you think is the best rationale for applying weights in sequence analysis?
When should sequences be weighted?
Do you use cross-sectional sampling weights or longitudinal weights accounting for sampling probabilities as well as panel attrition?
How do you apply weights if you have unbalanced panel data?
The usage of weights in TraMineR is well documented; but do you have examples for the usage of weights with a Stata-ado?

References

Gabadinho, Alexis, Gilbert Ritschard, Matthias Studer and Nicolas S. Müller (2010): Mining sequence data in R with the TraMineR package: A user's guide,
University of Geneva.
Gabadinho, Alexis, Gilbert Ritschard, Nicolas S. Müller and Matthias Studer(2011): Analyzing and visualizing state sequences in R with TraMineR, in: Journal of Statistical Software, Vol. 40, No. 4, pp. 1-37.
Lesnard, Laurent (2010): Setting Cost in Optimal Matching to Uncover Contemporaneous Socio-Temporal Patterns, in: Sociological Methods and Research, Vol. 38, No. 3, pp. 389-419.
Studer, Matthias, Gilbert Ritschard, Alexis Gabadinho and Nicolas S. Müller (2011): Discrepancy Analysis of State Sequences, in: Sociological Methods and Research. Vol. 40, No. 3, pp. 471-510.

[1] See Studer et al. (2011) for a presentation of discrepancy analysis that is an ANOVA like approach for distance matrices.
Comment: Just an observation: Since the non-weighted scenario is equivalent to setting all weights to 1, it is clear that by allowing different weights you will be working with a more complex model. This means that the model will be able to capture phenomena not captured by the original model. This will come at the cost of requiring more data to properly generalize or an increased chance of over-fitting. So, without knowing anything specific about the domain, I would suggest using a weighted version only if the unweighted one doesn't work for you.
Answer: I assume that you are using sampling weights to correct for representativity bias. Please note that some "data providers" require you to use the weights in your publications.
In my opinion, you should always use weights for descriptive analysis in order to get unbiased results. I think that there are more consensus for this kind of analysis. Descriptive analysis includes cluster analysis, sequences visualization, computation of transitions rates (and hence substitution costs based on them), for instance. For weighted cluster analysis, you can have a look at the WeightedCluster library and manual.
Regarding the weights to use, I would recommend to use longitudinal weights, since the sequences are defined for the whole period, but it depends on the exact weight definition. For a more general answer, you need to answer the following questions:

What sample do I have (at what time, and so on)?
to which population do I want to generalize?

In some panels, longitudinal weights use the sample defined by wave t and generalize it to the population at wave one. This is what you want if you want to follow the evolution at wave one.
Comment: Which kind of weight would you use? Cross-sectional sampling weights from date/wave 1 or longitudinal weights for the whole observed period of time?
Comment: I have added the weight discussion to the answer.


How do I use the IComparable interface?

Question: I need a basic example of how to use the IComparable interface so that I can sort in ascending or descending order and by different fields of the object type I'm sorting.
Answer: Well, since you are using List<T> it would be a lot simpler to just use a Comparison<T>, for example:
List<Foo> data = ...
// sort by name descending
data.Sort((x,y) => -x.Name.CompareTo(y.Name));

Of course, with LINQ you could just use:
var ordered = data.OrderByDescending(x=>x.Name);

But you can re-introduce this in List<T> (for in-place re-ordering) quite easily; Here's an example that allows Sort on List<T> with lambda syntax:
using System;
using System.Collections.Generic;

class Foo { // formatted for vertical space
    public string Bar{get;set;}
}
static class Program {
    static void Main() {
        List<Foo> data = new List<Foo> {
            new Foo {Bar = "abc"}, new Foo {Bar = "jkl"},
            new Foo {Bar = "def"}, new Foo {Bar = "ghi"}
        };
        data.SortDescending(x => x.Bar);
        foreach (var row in data) {
            Console.WriteLine(row.Bar);
        }
    }

    static void Sort<TSource, TValue>(this List<TSource> source,
            Func<TSource, TValue> selector) {
        var comparer = Comparer<TValue>.Default;
        source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
    }
    static void SortDescending<TSource, TValue>(this List<TSource> source,
            Func<TSource, TValue> selector) {
        var comparer = Comparer<TValue>.Default;
        source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
    }
}

Comment: Your answer starts a bit confusing, it assumes that I've already read information that isn't in the question but in an answer posted by the OP.
Answer: Here's a simple example:
public class SortableItem : IComparable<SortableItem>
{
    public int someNumber;

    #region IComparable<SortableItem> Members

    public int CompareTo(SortableItem other)
    {
        int ret = -1;
        if (someNumber < other.someNumber)
            ret = -1;
        else if (someNumber > other.someNumber)
            ret = 1;
        else if (someNumber == other.someNumber)
            ret = 0;
        return ret;
    }

    #endregion
}

"That's great, but what if I want to be able to control the sort order, or sort by another field?"
Simple. All we need to do is add few more fields to the object. First we'll add a string for a different sort type and then we'll add a boolean to denote whether we're sorting in descending or ascending order and then add a field which determines which field we want to search by.
public class SortableItem : IComparable<SortableItem>
{
    public enum SortFieldType { SortNumber, SortString }

    public int someNumber = -1;
    public string someString = "";
    public bool descending = true;
    public SortFieldType sortField = SortableItem.SortFieldType.SortNumber;

    #region IComparable<SortableItem> Members

    public int CompareTo(SortableItem other)
    {
        int ret = -1;
        if(sortField == SortableItem.SortFieldType.SortString)
        {
            // A lot of other objects implement IComparable as well.
            // Take advantage of this.
            ret = someString.CompareTo(other.someString);
        }
        else
        {
            if (someNumber < other.someNumber)
                ret = -1;
            else if (someNumber > other.someNumber)
                ret = 1;
            else if (someNumber == other.someNumber)
                ret = 0;
        }
        // A quick way to switch sort order:
        // -1 becomes 1, 1 becomes -1, 0 stays the same.
        if(!descending) ret = ret * -1;

        return ret;
    }

    #endregion

    public override string ToString()
    {
       if(sortField == SortableItem.SortFieldType.SortString)
          return someString;
       else
          return someNumber.ToString();
    }
}

"Show me how!"
Well since you asked so nicely.
static class Program
{
    static void Main()
    {

        List<SortableItem> items = new List<SortableItem>();
        SortableItem temp = new SortableItem();
        temp.someString = "Hello";
        temp.someNumber = 1;
        items.Add(temp);
        temp = new SortableItem();
        temp.someString = "World";
        temp.someNumber = 2;
        items.Add(temp);
        SortByString(items);
        Output(items);
        SortAscending(items);
        Output(items);
        SortByNumber(items);
        Output(items);
        SortDescending(items);
        Output(items);
        Console.ReadKey();
    }

    public static void SortDescending(List<SortableItem> items)
    {
        foreach (SortableItem item in items)
            item.descending = true;
    }
    public static void SortAscending(List<SortableItem> items)
    {
        foreach (SortableItem item in items)
            item.descending = false;
    }
    public static void SortByNumber(List<SortableItem> items)
    {
        foreach (SortableItem item in items)
            item.sortField = SortableItem.SortFieldType.SortNumber;
    }
    public static void SortByString(List<SortableItem> items)
    {
        foreach (SortableItem item in items)
            item.sortField = SortableItem.SortFieldType.SortString;
    }
    public static void Output(List<SortableItem> items)
    {
        items.Sort();
        for (int i = 0; i < items.Count; i++)
            Console.WriteLine("Item " + i + ": " + items[i].ToString());
    }
}

Comment: There isn't anything that says you can't answer the question too if you have a better idea.
Comment: That is actually pretty yeucky, sorry to say it. There are much better approaches, especially using LINQ or a LINQ-inspired approach...
Comment: I have - I was just writing it ;-p
Answer: If you want dynamic sort, you can use LINQ
var itemsOrderedByNumber = ( from item in GetClasses() orderby item.Number select item ).ToList();
var itemsOrderedByText = ( from item in GetClasses() orderby item.Text select item ).ToList();
var itemsOrderedByDate = ( from item in GetClasses() orderby item.Date select item ).ToList();

or "Sort" method of List class:
List<Class1> itemsOrderedByNumber2 = new List<Class1>( GetClasses() );
itemsOrderedByNumber2.Sort( ( a, b ) => Comparer<int>.Default.Compare( a.Number, b.Number ) );

List<Class1> itemsOrderedByText2 = new List<Class1>( GetClasses() );
itemsOrderedByText2.Sort( ( a, b ) => Comparer<string>.Default.Compare( a.Text, b.Text ) );

List<Class1> itemsOrderedByDate2 = new List<Class1>( GetClasses() );
itemsOrderedByDate2.Sort( ( a, b ) => Comparer<DateTime>.Default.Compare( a.Date, b.Date ) );

Answer: You can use this for sorting list
namespace GenaricClass
{
    class Employee :IComparable<Employee>
    {
        public string Name { get; set; }
        public double Salary { get; set; }

        public int CompareTo(Employee other)
        {
            if (this.Salary < other.Salary) return 1;
            else if (this.Salary > other.Salary) return -1;
            else return 0;
        }

        public static void Main()
        {
            List<Employee> empList = new List<Employee>()
            {
                new Employee{Name="a",Salary=140000},
                new Employee{Name="b",Salary=120000},
                new Employee{Name="c",Salary=160000},
                new Employee{Name="d",Salary=10000}
            };
            empList.Sort();
            foreach (Employee emp in empList)
            {
                System.Console.Write(emp.Salary +",");
            }
            System.Console.ReadKey();
        }
    }
}

Answer: This might not be in relation to sorting order, but it is still - I think - an interesting use of IComparable:
public static void MustBeInRange<T>(this T x, T minimum, T maximum, string paramName)
where T : IComparable<T>
{
    bool underMinimum = (x.CompareTo(minimum) < 0);
    bool overMaximum = (x.CompareTo(maximum) > 0);
    if (underMinimum || overMaximum)
    {
        string message = string.Format(
            System.Globalization.CultureInfo.InvariantCulture,
            "Value outside of [{0},{1}] not allowed/expected",
            minimum, maximum
        );
        if (string.IsNullOrEmpty(paramName))
        {
            Exception noInner = null;
            throw new ArgumentOutOfRangeException(message, noInner);
        }
        else
        {
            throw new ArgumentOutOfRangeException(paramName, x, message);
        }
    }
}

public static void MustBeInRange<T>(this T x, T minimum, T maximum)
where T : IComparable<T> { x.MustBeInRange(minimum, maximum, null); }

These simple extension methods allow you to do parameter range checking for any type that implements IComparable like this:
public void SomeMethod(int percentage, string file) {
    percentage.MustBeInRange(0, 100, "percentage");
    file.MustBeInRange("file000", "file999", "file");
    // do something with percentage and file
    // (caller will have gotten ArgumentOutOfRangeExceptions when applicable)
}

Comment: To be honest, you're unlikely to use it on a type that isn't `IComparable` or `IComparable`, so I'd drop the constraint and use Comparer.Default. This is, for example, how LINQ-to-Objects does Min/Max.
Comment: Hadn't though of that. Thanks for the tip. However, wouldn't that show the extension method everything (=on types I'd be "unlikely to use it on") while with the type constraint it'll only show on types that actually are IComparable?
Answer: using System;
using System.Collections.Generic;
using System.Text;

namespace Sorting_ComplexTypes
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer {
                ID = 101,
                Name = "Mark",
                Salary = 2400,
                Type = "Retail Customers"
            };
            Customer customer2 = new Customer
            {
                ID = 102,
                Name = "Brian",
                Salary = 5000,
                Type = "Retail Customers"
            };
            Customer customer3 = new Customer
            {
                ID = 103,
                Name = "Steve",
                Salary = 3400,
                Type = "Retail Customers"
            };

            List<Customer> customer = new List<Customer>();
            customer.Add(customer1);
            customer.Add(customer2);
            customer.Add(customer3);

            Console.WriteLine("Before Sorting");
            foreach(Customer c in customer)
            {
                Console.WriteLine(c.Name);
            }

            customer.Sort();
            Console.WriteLine("After Sorting");
            foreach(Customer c in customer)
            {
                Console.WriteLine(c.Name);
            }

            customer.Reverse();
            Console.WriteLine("Reverse Sorting");
            foreach (Customer c in customer)
            {
                Console.WriteLine(c.Name);
            }
            }
        }
    }
    public class Customer : IComparable<Customer>
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Type { get; set; }

        public int CompareTo(Customer other)
        {
            return this.Name.CompareTo(other.Name);
        }
    }

How do I use the IComparable interface?


Attacking the G above staff on tenor trombone

Question: On tenor trombone, I have an issue playing the G above staff (concert pitch bass clef). My attack is really ugly, crackling. I more than often miss it, playing either on 2+ position or 4th position.
It's really annoying because I can reach a rather clean G-flat (on 3+ or 5) but also A-flat (on 3), and even A and B-flat (not perfect but way better and more consistent than my G). I've been practicing this note a lot recently, trying to solve the issue, by doing the following :

I reinforced my A-flat and G-flat with various standard exercises.
Always using a tuner, I try to get used to the G by sliding from A-flat or G-flat.
During the day, whenever I can, I even listened to G being played by a tuner.
And of course I'm playing various "high range" exercises on G. The "Broken Intervals" by Jason Sulliman worked well for me on other notes.

At this point I think my issue might be at least in part just in my mind. Did anybody ever have a similar issue ? Would you have some advices ?
Comment: In UK Brass Bands, Tenor Trombones play treble clef Bb transposing parts. Written middle C (first ledger line below the treble clef stave) is performed in first position and _sounds_ concert Bb second line up bass clef stave. Somewhat illogically, Brass Band Bass Trombone is still notated concert pitch and bass clef…
Comment: Do you mean concert pitch bass clef or Bb transposing treble clef? It makes a difference to what "G above the stave" actually means.
Comment: @BrianTHOMAS I meant concert pitch bass clef. No judging here from my part I'm truly just curious : with tenor trombone being a non-transposing instrument, i.e. I read G, I play G, it 'sounds' G in concert pitch (as far as I understand), why would a tenor trombone speak in "Bb transposing treble clef", is this something usual ?
Comment: @BrianTHOMAS thanks for the info, I had no idea!
Answer: Is this a quality instrument?  No leaks? (check the water key.)  A brass instrument CAN have a 'bad note', though it's more common on valved instruments which have to be designed to be in tune.  No such restriction on trombone where we have the choice of choosing the optimum slide position - different for every note if necessary!
Is it the same using another mouthpiece, another instrument (though it might be difficult to borrow these to try in these times of the virus)?
In the days when Denis Wick (he of the mutes) was London's prime dealer in second-hand trombones as well as principal trombone in the LSO, I remember a student complaining that an instrument he'd just bought had no high C.  Denis picked it up and blew a succession of that note, loud, soft and everything in-between.   'It has now!' he said.   It was difficult to argue the point.
Play that high G loud. Several times.  LOUD. You might find it falls into place.
Also - you say your high A and B♭ are 'not perfect'.  So work up to the C and D!  When B♭ stops feeling like a big deal you might find the G a lot easier.
Comment: Thanks for the advices, I will try that. The trombone has no leaks and is a quality one (I think), A.Courtois symphony 400, I've had it for 15 years or so now, and it was second hand, but it's still in a very good shape. He does need a revision, but I don't think the issue is with the trombone ^^


Pickling a list consisting of 'n' 2-tuple values

Question: I want to pickle a list as it takes a long time for me to create the list. The list consists of "n" 2-tuple values where the first tuple value is a large dictionary(1k to 10k keys) and the second value is a string. N can be as large as 100s to 1000s. I would like to save such a data structure so that I may load it on convenience. If the list is human-readable it would be great, but not at the cost of performance.
I have knowledge about Shelve, PyYaml, cPickle and JSON. I am just unsure as to what to use given my data. Initial reading on various other threads on this website and internet says that cPickle may be the best choice. Any thoughts from the gurus here?
Comment: Have you considered using a database?
Comment: cPickle is OK if you are staying with Python. Just be sure to use the `dump` method with the `protocol=-1` parameter. This will speed the things up.
Comment: Eumiro, I am staying with Python hence the decision.
Comment: Ignacio, I haven't. Is there any particular reason I should?
Answer: I would use cPickle, this works fine,
# Dummy data
from random import randint as r

a,b = 97,123

d = [(dict([(chr(r(a,b)),j) for j in range(1000)]),
       ''.join([chr(r(a,b)) for i in range(5)]))
                            for j in range(100)]

# Pickle it
import cPickle as pickle

f = open('store.dat','w')
pickle.dump(d,f)
f.close()

I would also consider using something like dumbdbm.
Added later
Following on from the example above, you can do something like this,
import dumbdbm as dbm

g = dbm.open('store.db')
g.update([(str(i),pickle.dumps(j)) for i,j in enumerate(d)])
g.close()

Comment: @Denzil: If you use something like dumbdbm, it's possible to access your records by key. It could make, for example, searching easier.
Comment: Lafrasu, Thanks for the reply. Isn't dumbdbm just for a dictionary? Can I store my data structure?
Comment: @Denzil: See the addition to the answer.
Comment: Lafrasu, Works well Thanks! Is there any particular reason dbdm is better than cPickle? I tried both and didn't make such a difference in performance atleast.
Comment: Lafrasu, Thanks. I wouldn't want to have any search parameters as of now. I will keep dumbdbm in mind when such a requirements comes up. Thanks!


Right align a specific column separated by spaces

Question: Example:
Monte Bianco 4.807 France/Italy
Monte Rosa 4.634 Italy/Switzerland
Dom 4.545 Switzerland/Italy
Weisshorn 4.505 Switzerland
Cervino (Matterhorn) 4.478 Italy/Switzerland
Suphan Dagi 4.434 Turkey

I'm trying to create 2 new menu options (in menu.vim):

Align right 1st column
Align right last column

I can't find out how to align right only the first, only the last column or a specific column in the middle of my table.
Monte Bianco 4.807              France/Italy
Monte Rosa 4.634           Italy/Switzerland
Dom 4.545                  Switzerland/Italy
Weisshorn 4.505                  Switzerland
Cervino (Matterhorn) 4.478 Italy/Switzerland
Suphan Dagi 4.434                     Turkey

I know I can use this to align right the latest column
Tabular /^\(.\{-}\s\{1,}\)\{1,}/l0l0r0

but what I want to find out is how to find the latest align parameter before the end of line
(p.e. in above example "Spaces") and align right all text after this (without counting the number of columns).
Is this possible?
And I have no idea at all how to align right only the first column or a specific column.
Comment: How do you define a column? If they are space-separated then does "Monte Bianco" span over 2 columns?
Comment: @Benoit, monte bianco must be 2 different columns "monte" and "bianco" My idea is to add spcaces where I need the columns and then do above.
Answer: In order to right align the first whitespace-separated column leaving the rest
of them aligned to the left, use the following :Tabular command,
:Tab/^\S*\s\+\zs/r1l0l0

Similarly, to right align the last column, run
:Tab/\s\@<!\ze\s\+\S*$/l1l0r0

If column separators must have, say, at least two space characters, modify the
commands as follows.
:Tab/\(\s\{2,}.*\)\@<!\s\{2,}\zs/r1l0l0

and
:Tab/\s\@<!\ze\s\{2,}\(.*\s\{2,}\)\@!/l1l0r0

Comment: Thank you very much ib. What would be the formulas if I want not to do the right align at the first whitespace separator but at the first 2 whitespaces seperators? (jumping over separators with only 1 whitespace)
Comment: @Remonn:  I added the commands corresponding to that case.  To change the minimum number of spaces that column separators must have, substitute `2` with an appropriate number.


Ler ficheiro txt para Select

Question: Quero utilizar um select, com os dados que estão dentro de um ficheiro .txt, criado por mim. Utilizar uma função em PHP. Dentro do ficheiro (select.txt) tenho:
teste1
teste2
teste3

E o select
<select name=select >
    <option value=""></option>
    <option value=""></option>
    <option value=""></option>
</select>

Comment: Tente explicar um bocadinho melhor a pergunta para que fique mais percetível para ajudar outros utilizadores.
Answer: Para poucos registros pode usar a função file(), ela carrega todo o arquivo e converter as linhas do em array.
<?php $linhas = file('teste.txt'); ?>
<select name=select >
    <?php foreach($linhas as $item){ ?>
           <option value=""><?php echo $item; ?></option>
    <?php } ?>
</select>

Outra forma de ler um arquivo é combinando as funções fopen() para abrir o arquivo e fgets() extrai o conteudo o segundo argumento da função opcional informa a quantia de bytes que devem ser lidos.
<?php $arquivo = fopen('teste.txt', 'r'); ?>
<select name=select >
    <?php while($linha = fgets($arquivo)){ ?>
           <option value=""><?php echo $linha; ?></option>
    <?php }
      fclose($arquivo);
     ?>
</select>

Comment: Esta resposta salvou a pergunta +1
Answer: A forma mais fácil de se fazer é utilizando a função file(), ela lê o arquivo e retorna um array contendo para cada posição, uma linha do arquivo lido.
Dessa forma você conseguirá ler cada linha do arquivo e imprimir as options dentro do select.
<select name='select'>
  <?php
    $arquivo = file("arquivo.txt");
    for($i = 0; $i < count($arquivo); $i++) {
      print "<option value=''>". $arquivo[$i] ."</option>";
    }
  ?>
</select>

Para selecionar uma única linha do arquivo use:
(Lembrando que em arrays a primeira posição é 0)
print $arquivo[1]."
";

Retirado desse link
Answer: Use o fopen para poder ler o arquivo txt linha por linha em um array aqui temos um tutorial. O ideal acredito que você tenha que jogar em um array ou algo do tipo para poder ler separadamente, mais para deixar o código bonito, como está aqui.
Depois você pode pegar essa variável e realizar um foreach dentro do seu select:
foreach($variavel as $linhas)
{
 $select = "<option value=''>".$linhas."</option>";
}

Ler ficheiro txt para Select


Salvar uma valor de um data frame sem que ele seja perdido quando seja atualizado

Question: Estou tentando salvar o primeiro valor desse dataframe em uma variável que o valor não será perdido quando a tabela que gera o dado for atualizada.
Answer: use o método .copy para copiar um DataFrame/Series do pandas. A partir desse momento, os dados original e copiado podem ser modificados de forma independente.
Exemplo:
import pandas as pd

df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [10, 20, 30],
})

print(df)
# output:
#    a   b
# 0  1  10
# 1  2  20
# 2  3  30

df_copia = df.copy()  # cópia independente
df['a'] = ['outros', 'valores', 'aqui']

print(df)  # valores modificados
# output:
#          a   b
# 0   outros  10
# 1  valores  20
# 2     aqui  30

print(df_copia)  # valores originais
# output:
#    a   b
# 0  1  10
# 1  2  20
# 2  3  30

No seu caso, imagino que você queira fazer algo do tipo:
Lastdate = T_Newbloqueio.iloc[0]['databloqueio'].copy()


Extending the trendline of a stock chart to the right

Question: I want to extend this trendline that I have drawn to the right.
Following is the code:
import matplotlib.pyplot as plt
import yfinance as yf

df = yf.download('aapl', '2020-01-01', '2021-01-01')

df1 = df[df.index > '2020-06-01']
df2 = df[df.index < '2020-06-02']
lowest2 = df1[df1.Close == df1.Close.min()]
lowest1 = df2[df2.Close == df2.Close.min()]

fig, ax = plt.subplots(figsize= (10, 6))
ax.plot(df.index, df.Close)
ax.plot([lowest1.index[0], lowest2.index[0]], [lowest1.Low[0], lowest2.Low[0]])
ax.set_xlim(df.index[0], df.index[-1])
plt.show()

And heres the output image:
Answer: This is really simple maths combined with the use of Timestamps:
import matplotlib.pyplot as plt
import yfinance as yf

df = yf.download('aapl', '2020-01-01', '2021-01-01')

df1 = df[df.index > '2020-06-01']
df2 = df[df.index < '2020-06-02']
lowest2 = df1[df1.Close == df1.Close.min()]
lowest1 = df2[df2.Close == df2.Close.min()]

fig, ax = plt.subplots(figsize= (10, 6))
ax.plot(df.index, df.Close)

## calculating slope
x1, x2, y1, y2 = lowest1.index[0], lowest2.index[0], lowest1.Low[0], lowest2.Low[0]
slope = (y2-y1)/(x2-x1).total_seconds()

## extending line
x3 = pd.Timestamp('2020-10-01')
y3 = y1+(x3-x1).total_seconds()*slope

## plotting lines
ax.plot([x1, x2], [y1, y2])
ax.plot([x1, x3], [y1, y3], ls=':')

ax.set_xlim(df.index[0], df.index[-1])

output:
Comment: Thanks @mozway. Why did you convert the slope into seconds?
Comment: To have numbers for the slope division you can't divide number with TimeDelta
Comment: NB. it isn't the slope that is converted to seconds, but the delta of time


Why do the database functions return all fields as strings?

Question: db_select('my_table', 'a')
   ->fields('a')
   ->condition('a.campaign_id', $entity->campaign_id)
   ->execute()
   ->fetchObject();

my_table has some columns that are integers, but the query above returns strings.
Why does this happen? It seems strange to me that the query ignores the column types.
Answer: The DatabaseStatementBase::fetchObject() method is inherited from PHP's PDOStatement::fetchObject() which returns the object columns as strings. Given that not all RDBMS's have the same set of types & PHP isn't a strongly typed language, it was probably decided to return everything as strings since it's a base datatype that can be relied on.


Problem 1.K.(e) of Kelley

Question: I am working on problem K from the first chapter of Kelley and I can not solve part (e) of this problem. I know that every open subspace of a separable space is separable, but this is not enough. Maybe we can use (d) to solve it, I guess. Could you please help me?
Edit: Now I have got an idea. We shall find a dense subset of $A$. Fix a $N\in\mathbb{N}$, then we are able to divide $\mathbb{R}$ into countably some parts, namely
$$ \mathbb{R}=\bigcup _{k=-\infty}^\infty\left[\frac{k}{N},\frac{k+1}{N}\right).$$
For every $k$, if $\left[\frac{k}{N},\frac{k+1}{N}\right)\cap A\neq\varnothing$, then pick an element from it, and put $A_N$ as the set of such elements. Now since $A_N$ is countable, $\cup_{N=1}^\infty A_N=A_0$ is also countable. By (d), we know that $A$ only has got countably some accumulation points in itself. Denote the derived set of $A$ by $A'$, we shall prove that $A_0\cup \left(A\setminus A'\right)$ is dense in $A$. For an accumulation point $a\in A$, if $a\in A_0$, then there is nothing to prove; if not, then since $a$ is an accumulation point of $A$, for any neighbourhood $\left[a,b\right)$ of $a$, there are always some $c\in \left(a,b\right)\cap A$. Choose $N$ large enough such that $\frac{1}{N}<\min \left(c-a,b-c\right)$, then there will be some $k_N\in\mathbb{Z}$ such that $c\in\left[\frac{k_N}{N},\frac{k_N+1}{N}\right)$, then since $\left[\frac{k_N}{N},\frac{k_N+1}{N}\right)\cap A\neq \varnothing$ and $\left[\frac{k_N}{N},\frac{k_N+1}{N}\right)\subset \left[a,b\right)$, there must be some points in $\left[\frac{k_N}{N},\frac{k_N+1}{N}\right)\cap A_0$, hence in $\left[a,b\right)\cap A_0$.
Answer: The closure of your set $A_0$ contains all point that are accumulation points of $A$ from the right; add the points from 1(d) to that and there is your countable dense set.

Problem 1.K.(e) of Kelley


Scale of variables and the consequences on the solution

Question: Let us say I have data set of distinct $x_i$. A Gaussian is fitted to it with maximum likelihood, obtaining some $\mu$ and some $\sigma^2$. I will also obtain a likelihood $\mathcal{L}$.
Now, I copy the data set where I set $\tilde{x}_i = 2 x_i$. I estimate another Gaussian, obtaining $\tilde{\mu}, \tilde{\sigma}^2, \tilde{L}$.
Since I am using ML I will get $2 \mu = \tilde{\mu}$, $4 \sigma^2 = \tilde{\sigma^2}$. Contrary to my intuition, $\mathcal{L} \neq \tilde{\mathcal{L}}$.
This is maybe not so bad for a univariate Gaussian. But what if I perform model selection for factor analysis, Gaussian mixture models or more complicated models? Will the order of models ranked by their respective likelihoods be the same?
Answer: What dilemma?
While the actual value of the likelihood at the maximum will change, the point where it is maximized will be the same.
E.g. let's take factor analysis:
First, from the help for factanal in R:
# A little demonstration, v2 is just v1 with noise,
# and same for v4 vs. v3 and v6 vs. v5
# Last four cases are there to add noise
# and introduce a positive manifold (g factor)
v1 <- c(1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,5,6)
v2 <- c(1,2,1,1,1,1,2,1,2,1,3,4,3,3,3,4,6,5)
v3 <- c(3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,5,4,6)
v4 <- c(3,3,4,3,3,1,1,2,1,1,1,1,2,1,1,5,6,4)
v5 <- c(1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,6,4,5)
v6 <- c(1,1,1,2,1,3,3,3,4,3,1,1,1,2,1,6,5,4)
m1 <- cbind(v1,v2,v3,v4,v5,v6)
cor(m1)
factanal(m1, factors = 3) # varimax is the default

Now, double all the variables and re-run
v1 <- 2*v1
v2 <- 2*v2
v3 <- 2*v3
v4 <- 2*v4
v5 <- 2*v5
v6 <- 2*v6

m2 <- cbind(v1,v2,v3,v4,v5,v6)

factanal(m2, factors = 3) # varimax is the default

The results are identical.  The actual value of the likelihood isn't relevant, only the place where it occurs.


What should the width of the border be?

Question: You have made a rectangular stained glass window that is
$2$ feet by $4$ feet. You have 7 square feet of clear glass to create
a border of uniform width around the window. What should
the width of the border be?

Comment: Here is solved page 3 and with a better wording: http://www.classzone.com/eservices/home/pdf/teacher/LA205BAD.pdf edited according with the pdf (which makes sense with the picture you uploaded)
Comment: Question is not clear. $2$ feet of stained glass seems to be missing a dimension. And you've got $7$ square feet of clear glass, but with no form? No given form would allow adopting to any width $x$ that might be needed; there is no such thing as $7$ square feet of _liquid_ glass.
Comment: *You have a rectangular stained glass window that is
$2$ feet by $4$ feet. You have to create totally 7 square feet of clear glass including a border of uniform width around the window. What should the width of the border be?*... I would edit it so had I seen it earlier.
Answer: The total area of the window, including the border and the stained glass, is the product of the height and width: $h \cdot w = (4 + 2x)(2 + 2x) = 4x^2 + 12x + 8\ \text{ft}^2$. The area of the stained glass is $2 \cdot 4 = 8\ \text{ft}^2$, so the area of the border is
$4x^2 + 12x + 8 - 8\ \text{ft}^2$, which is given to be $7\ \text{ft}^2$. Thus
$$4x^2 + 12x - 7 = 0 \\
\implies 4x^2 -2x + 14x - 7 = 0 \\
\implies 2x(2x - 1) + 7(2x - 1) = 0 \\
\implies (2x - 1)(2x + 7) = 0 \\
\implies x = \frac{1}{2}, \frac{-7}{2}
$$
Obviously, the width of the border can't be negative, so $x = \frac{1}{2}\ \text{ft}^2$.

What should the width of the border be?


Como pegar a posição da barra de rolagem com JavaScript?

Question: Eu tenho a seguinte página:

<navbar>
    Link 1
    Link 2
    Link 3
</navbar>

Dependendo da seção que o scroll da página estiver, eu gostaria de trocar a cor da barra de navegação, como eu poderia fazer isso de maneira simples com JavaScript?
Comment: @AugustoVasques coloquei.
Comment: Poderia nos fornecer um [mcve] demostrando o esta tentando fazer.
Comment: Teste no console do seu navegador o comando `this.scrollY`
Comment: @BrennoSegolim mas o this deve referenciar qual elemento?
Comment: Referencia ao elemento `window`, tanto que se você digitar `window.scrollY` seria a mesma coisa. Até melhor usar `window.scrollY`, pois se você utilizar `this` dentro do contexto de uma classe, ela que será referida.
Answer: O algorítimo é simples no evento window.scroll ele faz um conjunto de verificações para saber sobre qual elemento o <navbar> está:

verifica se <navbar> esta sobre #sec-1 se estiver muda a cor do <navbar> para vermelho e abandona o evento.
verifica se <navbar> esta sobre #sec-2 se estiver muda a cor do <navbar> para verde e abandona o evento.
verifica se <navbar> esta sobre #sec-3 se estiver muda a cor do <navbar> para azule abandona o evento.
caso não esteja sobre nenhum <navbar> muda a cor para preto.

Primeiro são calculados os valores iniciais de topo e base para cada
 e <navbar> utilizando para isso princípios básicos de geometria(topo mais a altura do elemento é igual a posição da base).
Já dentro do evento window.scroll os valores de topo e base são recalculados com relação a rolagem da tela e esses valores são comparados apenas com a base do  pois podemos saber sobre qual
 ele está.

//Calcula os valores estáticos de topo e base para os elementos

let sec1Top = $("#sec-1").offset().top
let sec1Botton = sec1Top + $("#sec-1").outerHeight()
let sec2Top = $("#sec-2").offset().top
let sec2Botton = sec2Top + $("#sec-2").outerHeight()
let sec3Top = $("#sec-3").offset().top
let sec3Botton = sec3Top + $("#sec-3").outerHeight()

//Calcula os valos estático de base para o elemento <navbar>({top: 0; position: fixed;})
let navHeight = $("navbar").outerHeight()

//No evento scroll da janela
$(window).scroll(function() {

  // o número de pixels rolados na janela
  let wst = $(window).scrollTop();

  // Calcula os valores dinâmicos de topo e base para os elementos
 com relação o número de pixels rolados a janela
  let s1T = sec1Top - wst
  let s1B = sec1Botton - wst
  let s2T = sec2Top - wst
  let s2B = sec2Botton - wst
  let s3T = sec3Top - wst
  let s3B = sec3Botton - wst

  //Se a base do <navbar> estiver sobre #sec1
  if (navHeight > s1T && navHeight < s1B) {
    $("navbar").css('background-color', 'red');
    return;
  }

  //Se a base do <navbar> estiver sobre #sec2
  if (navHeight > s2T && navHeight < s2B) {
    $("navbar").css('background-color', 'blue');
    return;
  }

  //Se a base do <navbar> estiver sobre #sec3
  if (navHeight > s3T && navHeight < s3B) {
    $("navbar").css('background-color', 'green');
    return;
  }

  //Se a base do <navbar> não estiver sobre nenhum

  $("navbar").css('background-color', 'black');

});

//Recalcula os valores estáticos de topo e base para os elementos
 e <navbar> caso a janela do navegador seja redimensionada
$(window).resize(function() {
  sec1Top = $("#sec-1").offset().top
  sec1Botton = sec1Top + $("#sec-1").outerHeight()
  sec2Top = $("#sec-2").offset().top
  sec2Botton = sec2Top + $("#sec-2").outerHeight()
  sec3Top = $("#sec-3").offset().top
  sec3Botton = sec3Top + $("#sec-3").outerHeight()
})
navbar {
  color: #FFF;
  position: fixed;
  top: 0;
  width: 100%;
  height: 60px;
  background-color: #000;
}

section {
  width: 100%;
  height: 100vh;
}

#sec-1 {
  background-color: red;
  /* Inseri uma margem para melhorar a visualização do resultado do algorítimo*/
  margin-top: 61px;
}

#sec-2 {
  background-color: blue;
}

#sec-3 {
  background-color: green;
}

<navbar>
  Link 1
  Link 2
  Link 3
</navbar>


Monogame: Creating Draw Function In Class

Question: I am wanting to make a tile class that contains it's own drawing function. Below is what I have so far. The error that is showing when I run the coder is. "System.InvalidOperationException: 'Begin cannot be called again until End has been successfully called." This error message shows up on the spirteBatch.Begin() inside the class.
namespace TileGame.v3

{
    class Tile
    {
    public Texture2D texture { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
    public int sourceX { get; set; }
    public int sourceY { get; set; }
    public int width { get; set; }
    public int height { get; set; }

    public void Draw(GameTime gameTime, SpriteBatch spriteBatch)

    {

        spriteBatch.Begin();

        spriteBatch.Draw(texture, new Vector2(X, Y), new Rectangle(sourceX, sourceY, width, height), Color.White);

        spriteBatch.End();

        Draw(gameTime, spriteBatch);
    }

}

}
namespace TileGame.v3

{
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D mark;
    Texture2D peep1;
    Texture2D ocean;

    int x1 = 100;
    int y1 = 100;
    int x2 = 400;
    int y2 = 400;
    int tempx;
    int tempy;

    bool win = false;

    Tile a = new Tile();

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);

        mark = Content.Load<Texture2D>("mark");
        peep1 = Content.Load<Texture2D>("peep1");
        ocean = Content.Load<Texture2D>("ocean");

        a.texture = ocean;

    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
        {
            tempx = x1;
            x1 = x2;
            x2 = tempx;

            tempy = y1;
            y1 = y2;
            y2 = tempy;

            win = true;
        }

        a.X = 100;
        a.Y = 100;
        a.sourceX = 300;
        a.sourceY = 300;
        a.width = 100;
        a.height = 100;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {

        spriteBatch.Begin();

        a.Draw(gameTime, spriteBatch);

        spriteBatch.End();

        base.Draw(gameTime);
    }
}

}
The texture is 1920x1080 and I have tested drawing and cutting it and it has worked fine.
Comment: im not familiar with monogame, but im familiar with unity, shouldnt your Tile class inherit from the game class? and what does the Update() do, because as far as I can tell is a recursive statement that must be eating all your cpu
Comment: Are you actually calling `a.Draw()` anywhere?
Comment: if you are using visual studio 2017 you can enable `Common Runtime Exceptions` and rerun your code. You can enable this option in the `Exception Settings`. (Shortkey to the settings: `Crtl+Alt+E`). Maybe then there will be an error.
Comment: are you actually loading the texture and calling that draw-function anywhere?
Comment: You are never calling Draw(a.Texture...) anywhere, are you?
Comment: I have run it with a.Draw in the main update and the main draw function on separate  occasions but it didn't work either time.
Answer: First of all, your code is probably incomplete, but you are never calling the draw method anywhere.
Let say you are calling it, are you sure your texture is bigger than 300x300? And what does that texture contains for (x,y = 300,300 to x,y = 400,400)? Does it have any color data in those positions?
If you answer yes to all of this, we will need more code to be able to help you with that.
Side node: Since this is a tile, you probably are going to render many of them. You don't need to call .Begin() and .End() for all of them. Simply call Begin() before the first tile and End() after the last one and you're good to go. This will make rendering much faster.


Code comments in TPL file that wont be rendered in HTML?

Question: Can I add code comments to my template files that won't be publicly shown in the HTML?
Comment: @Close-voters...I get why you're voting to close as off-topic (this is pretty much a generic PHP question), but I think there's some value in putting this in the context of a Drupal template file. I know there's no technical difference, but I think this has the potential to help newbies understand a Drupal template file is just a standard PHP file mixed with HTML.
Comment: I also didnt know if there was a specific Drupal way. Its not inconceivable that Drupal would provide its own way of doing comments as Ive seen it with other CMS.
Answer: You can use PHP comments, those will be ignored by the template engine and not rendered to HTML:

  <?php /* This won't be visible in the source. */ ?>

Comment: @jdln - There is some overhead for switching from html to php mode and back. Little one, but it's there. That's one of the reasons caching opcode (see APC for example) is so effective. If you need to open php block anyway, comments are pretty much free. Of course they make file bigger and bigger file is slower to load, but I don't believe it's measurable difference.
Comment: Is there any performance impact to having to use php tags? Thanks
Comment: Wow, never been asked that before :) It's really a question for the PHP forums, it would need to be benchmarked properly. My gut instinct is that the PHP processor would be significantly optimised so the impact of parsing a comment would be negligible, if anything at all. Put it this way, if there _is_ a performance impact then the same impact will exist in pretty much every PHP site ever built


SQL Server- Trigger. Update a column on one table with a count of columns from another table

Question: Trying to learn triggers and can't seem to wrap my head around whether this is the best way to go about this. There is a total of 'tickets' that I would like to count and put into a column for an 'order'.
CREATE TRIGGER DAILYTICKETTOTALS
ON db.ORDER
AFTER UPDATE
AS
BEGIN
INSERT INTO db.ORDER (
    --Finding the order they made for the day:
    SELECT * FROM db.ORDER
    WHERE DESCRIPTION = 'specific description' AND
          CAST(CAST(CAST(GETDATE()AS float) AS int) AS datetime) =
          CAST(CAST(CAST(db.ORDER.STARTDATE AS float) AS int) AS datetime)
          AND db.ORDER.CREATEDBY = 'Last, First'
)
SET db.ORDER.COLUMNTOTALS VALUES(
    --Finding the total of tickets input for the day
    SELECT COUNT(*)
    FROM db.ticket
    WHERE CAST(CAST(CAST(db.ticket.DATE AS float) AS int) AS datetime) =
          CAST(CAST(CAST(GETDATE()AS float) AS int) AS datetime)
          AND db.ticket.INPUTBY = 'Last, First');

Thanks for any help, and I appreciate you reviewing this.
Comment: Your `INSERT` statement / syntax is all wrong - it should be `INSERT INTO db.Order (list-of-columns) SELECT ...... FROM ....` - there's no `SET` in an `INSERT` statement anywhere.... (that's for `UPDATE`)
Comment: something like this?
CREATE TRIGGER DAILYTICKETTOTALS
ON db.ORDER
AFTER UPDATE
AS
BEGIN
INSERT INTO db.ORDER (db.ORDER.COLUMNTOTALS)
    --Finding the order they made for the day:
    SELECT * FROM db.ORDER
    WHERE DESCRIPTION = 'specific description' AND
          CAST(CAST(CAST(GETDATE()AS float) AS int) AS datetime) =
          CAST(CAST(CAST(db.ORDER.STARTDATE AS float) AS int) AS datetime)
          AND db.ORDER.CREATEDBY = 'Last, First'
Comment: Side note: Make sure to wrap your table name in square brackets. You've used `ORDER` for some reason (ill-advised) which is a reserved key word (for obvious reasons).
Comment: There also doesnt appear to be any reference to the actual rows that have been updated, via the inbuilt INSERTED table.
Comment: @ZLK Yeah, I could have chosen a better table name for this example, but it's just a name for the example.
Comment: @ TomC The row/table I am trying to update with the count would be the first Selection where I find the order created by someone, and for that day. Again, I don't know if there's a better way to structure this.
Answer: Do some research on the "Special" tables available inside a trigger, such as "INSERTED" as that will give you the details of the rows that have been updated, and you can join that to anything else (including the actual table being updated) that you need to. Remember that you should not assume there is only 1 row updated, as the trigger will fire once per batch, not once per row.
This is a version of your stored proc that assumes that each order has a unique ID named OrderID, and that both the ticket and order table have a personID rather than looking for them by name. If not, they should, and if you cant change it then use your existing messy joins.
CREATE TRIGGER DAILYTICKETTOTALS
ON db.ORDER
AFTER UPDATE
AS
BEGIN
    update o
    set columntotals=TicketNum
    from inserted
    join db.[order] o on o.orderid=inserted.orderid
    join (
        select convert(date,ticket,[date]) as ticketdate, PersonID, count(*) as TicketNum
        from db.ticket
        group by convert(date,ticket,[date]) as ticketdate, PersonID
        ) t on t.PersonID=o.PersonID and t.ticketdate=convert(date,getdate())

Answer: This solved my problem, in case any of you were curious. I don't know if its ideal, but it works.
CREATE TRIGGER DAILYTICKETTOTALS
ON db.ORDER

AFTER INSERT, UPDATE
AS
BEGIN
DECLARE @INS NVARCHAR(50)
SELECT @INS = NAMECOLUMN FROM INSERTED
WHERE DESCRIPTION = 'specific description' AND
CAST(CAST(CAST(STARTDATE AS float) AS int) AS datetime)=
CAST(CAST(CAST(GETDATE() AS float) AS int) AS datetime)
END
IF @INS = 'Last, First'

BEGIN

UPDATE db.ORDER
SET COLUMNTOTALS  =  EXAMPLENAME.CT

FROM (SELECT COUNT(*) AS CT FROM ticket WHERE INPUTBY = 'Last, First') EXAMPLENAME
WHERE DESCRIPTION = 'specific description' AND INPUTBY = 'Last, First'
END
BEGIN

Comment: This will fail! The problem is that you are assuming that there is only one row in Inserted. While that may have been the case in testing, as soon as someone does any sort of update that updates more than one row then your method wont work. You should always assume that there will be more than one row updated otherwise you will cause yorself or someone else grief in the future.
Comment: With the where clause attached to filter on the inserted I should only ever get 1. The UI being used would only allow one entry at a time anyway. And actually if for some reason they could add more inserted rows that fit that where clause, I would want the same thing to be done.
Comment: Up to you, but sooner or later someone will do a bulk fix on the table that affects a whole bunch of rows. Its never good practice to set a single variable inside a trigger like this, specially when you can do exactly the same thing by joining between INSERTED and your table, using whatever crieria you need, as per the other answer you got.  Part of SO is for education purposes. You are welcome to ignore it if you wish.


Javascript Module pattern - how to reveal all methods?

Question: I have module pattern done like this:
var A = (function(x) {
   var methodA = function() { ... }
   var methodB = function() { ... }
   var methodC = function() { ... }
   ...
   ...
   return {
      methA: methodA,
      methB: methodB
   }
})(window)

This code let's me call only methA and methB() on A which is what I want and what I like. Now the problem I have - I want to unit test it with no pain ot at least with minimal efforts.

First I though I can simply return this but I was wrong. It returns window object.(can someone explain why?).
Second - I found solution somewhere online - to include this method inside my return block:
__exec: function() {
    var re = /(\(\))$/,
        args = [].slice.call(arguments),
        name = args.shift(),
        is_method = re.test(name),
        name = name.replace(re, ''),
        target = eval(name);
    return is_method ? target.apply(this, args) : target;
}

This method let's me call the methods like this: A.__exec('methA', arguments);
It is almost what I want, but quite ugly. I would prefer A.test.methA() where test would never be used in production code - just for revealing private methods.

EDIT
I see people telling me to test the big thing instead of the small parts. Let me explain. In my opinion API should reveal only the needed methods not a bunch of internal functions. The internals because of their small size and limited functionality are much easier to test then test the whole thing and guess which part gone wrong.
While I may be wrong, I would still like to see how I could return references to all the methods from the object itself :).
Comment: you dont unit test private methods or you dont make them private. that's simple.
Comment: This is not good idea. Private methods are privite, you don't have to make them public. Test your public methods, they depend on private so testing public should also cover this.
Comment: @mpm private methods are code too so they need to be tested out too.
Comment: possible duplicate of [How to unit test 'private' utility funcion in nodejs](http://stackoverflow.com/questions/15322354/how-to-unit-test-private-utility-funcion-in-nodejs)
Comment: @lukas.pukenis then make it public , what's so complicated about it ? you want to access something, make it public. You dont want then make it private. You can use composition to make something public private inside another object. I fail to understand what is the problem here. You just cant have it both ways, that's all. And as stated in the other question (upper) , TDD is about testing contracts. TDD doesnt care about private.
Comment: @mpm, the problem is that I inherited very big codebase and simply want to minimize my efforts :) I find no problem to reveal the functions as public, but that would involve a lot of manual work.
Answer: Answer to your first question(you return this, but it returns window, not the object you wanted): in javascript this inside the function returns global object unless this function is a method of the object.
Consider next examples:
1) this points to the global object ():
function(){
   return this;
}

2) this points to the object:
var obj = {
    value: "foo",
    getThisObject: function(){
        return this;
    }
}

Your case is example #1, because you have a function, that returns an object. This function is not a method of any object.
The best answer to your second question is to test only public methods, but if
that is so important for you, I can propose next:
create your modules dynamically on server side.
How it works:

create separate scripts for functionality you want;
create tests for these separate scripts;
create method that will combine scripts into one however you want;
to load script, reference to the combining scripts method.

Hopefully, it can solve your problem. Good luck!
Answer: Why not use namespaces to add your modules and public methods to js engine.  Like this:
window['MyApp']['MODULE1'] = { "METHOD1" : {}, "METHOD2" : {}};

I write modules like this Sample module in JavaScript.
And test it like this: Simple unit testing in JavaScript
The use of eval() is generally not good idea.
Comment: You might be right of eval() but I don't see a problem with it. It's a language construct which helps in certain cases.


Derivation of the standard error for Pearson's correlation coefficient

Question: I am wondering how to derive the formula for the standard error of Pearson's correlation coefficient which is given in Zar for example as
$$
\newcommand{\cov}{{\rm Cov}}
\newcommand{\var}{{\rm Var}}
\newcommand{\sd}{{\rm SD}}
SE_r =\sqrt{\frac{1-r^2}{n-2}}$$
I tried to get it from estimating the variance of r when
$$r =\frac{\cov(x,y)}{\sd(x)\sd(y)}$$
and $V(X) = E(X^2) - E(X)^2$ so we get $Var(r) = E\bigg(\frac{\cov(x,y)^2}{\var(x)\var(y)}\bigg) - r^2$. But from here I don't know how to continue since $E\bigg(\frac{\cov(x,y)^2}{\var(x)\var(y)}\bigg)$ would have to be $\frac{1-(n-3)r^2}{n-2}$ to get finally to
$$\var(r) =\frac{1-r^2}{n-2}$$
Any suggestions or references where I could look this up?
Comment: From all the references above and below, it seems that the formula you want to recover is wrong, anyway...
Comment: One more reference: http://www.tandfonline.com/doi/abs/10.1080/00220973.1956.11010555?journalCode=vjxe20
Comment: That's a really good question. Contrary to many textbooks,, that is not the standard error of r. For starters, the standard error of a statistic cannot be defined in terms of a statistic. It should be defined in terms of parameters. I believe you use rho in the formula and divide by sqrt(N-1) rather than 2 but I don't have a reference handy.
Comment: Maybe that  helps http://en.youscribe.com/catalogue/tous/knowledge/formal-sciences/a-tutorial-on-standard-errors-520541
Comment: Thanks for the link but it just lists lots of formulas for SE of particular estimates but doesn't give any information of how these formulas are obtained. The fact that this cannot be found by using google somehow tells me that people just use it without knowing where it comes from which i find a bit scary...
Comment: Here is the reference: https://www.mathworks.com/matlabcentral/newsreader/view_thread/107045.html   SE[r] = (1 - rho^2)/sqrt[n - 1], approximately.
Comment: Your question is not very clearly formulated.  If the $r$ in the question is the sample Pearson correlation, how can its variance still depend on $r$ itself?  It looks like the result you presented is an asymptotic result, which is well-known: $\sqrt{n}(r - \rho) \to_d N(0, (1 - \rho^2)^2)$, where $\rho$ is theoretical correlation between $X$ and $Y$.
Comment: Plus, if the conclusion is an accurate one (i.e., non-asymptotic), then you need to specify the underlying joint distribution of $(X, Y)$.  Without it, where should the calculation begin with?
Comment: I don't have a clue what you want with your references. There is plenty of references in which the standard error of the correlation coefficient estimate has n-2 in the denominator. Having looked through plenty of the original publications by Fisher and others it is clear that the standard error depends 1. on the sample size n (pairs of x,y samples),2 if x,y are indeed normal or not, 3. if one of them is fixed or not. depending on these three conditions the denominator can be derived to be n, n-1 and n-2. The derivation of these are very elaborate so no space here to recap all of this.
Comment: @Pascal. So you say that the formula that is given in the standard text book of biostatistics is wrong, Alright. :-)
Answer: There are two equations here for computing the statistical significance of the correlation coefficient.  The first is the variance of the true correlation coefficient $\rho$ of two bivariate normal random variables:\begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n},\end{equation} and the second is a t-statistic associated with the hypothesis that in the linear regression of $Y$ on $X$, the main effect of $X$ is zero:\begin{equation}t=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}Whence the standard error of $r$ mentioned by the OP: $\text{se}\left(r\right)=\sqrt{\frac{1-r^2}{n-2}}$.
Both of these expression can derived from the principle of maximum-likelihood.  That is, if we assume a parameter $\theta$ should be distributed normally,\begin{equation}\mathcal{L}\left(\theta\right)\sim\exp{\left(-\frac{\theta^2}{2\sigma^2_{\theta}}\right)},\end{equation}then the standard error of the parameter can be estimated from the curvature of the log-likelihood $\ell=\log{\mathcal{L}}$, function via\begin{equation}\sigma^2_{\theta}=\frac{-1}{\frac{\partial^2\ell}{\partial\theta^2}\bigr|_{\theta=\hat{\theta}}},\end{equation}where $\hat{\theta}$ is the maximum-likelihood estimate of $\theta$, got from the condition\begin{equation}\frac{\partial\ell}{\partial\theta}\bigr|_{\theta=\hat{\theta}}=0.\end{equation}
Now, Pearson derived the first expression \begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}\end{equation} in VII. Mathematical contributions to the theory of evolution.-III. Regression, heredity, and panmixia and https://royalsocietypublishing.org/doi/10.1098/rspl.1897.0091 by expanding the joint distribution of $n$ pairs of bivariate normal variables about the true value of $\rho$.  We can summarize his method here.  If we let $f$ be the bivariate normal density of two zero-mean random variables, i.e.,\begin{equation}f\left(X,Y\right)=\frac{1}{2\pi\sqrt{1-\rho^2}\sigma_X\sigma_Y}\exp{\left(-\frac{X^2}{2\sigma_X^2\left(1-\rho^2\right)}+-\frac{\rho XY}{2\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{Y^2}{2\sigma_Y^2\left(1-\rho^2\right)}\right)},\end{equation}then we can get the variance $\sigma^2_{\rho}$ of the correlation coefficient by evaluating $\frac{-\partial^2\log{f}}{\partial \rho^2}\bigr|_{\rho=\hat{\rho}}$.  The first derivative of $\log{f}$ is\begin{align}\frac{\partial\log{f}}{\partial \rho}&=\frac{\rho}{1-\rho^2}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_X^2}+\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)\frac{XY}{\sigma_X\sigma_Y}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_Y^2}\nonumber\\&=\frac{\rho}{1-\rho^2}+\left(\frac{2\rho}{1-\rho^2}\right)\left(\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right)+\frac{1}{1-\rho^2}\frac{XY}{\sigma_X\sigma_Y},\end{align}where at the maximum-likelihood solution $\hat{\rho}=\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}$ the middle term becomes\begin{equation}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}=-\frac{\mathbb{E}\left(X^2\right)}{\sigma_X^2\left(1-\rho^2\right)}+\frac{\rho\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{\mathbb{E}\left(Y^2\right)}{\sigma_X^2\left(1-\rho^2\right)}=-1.\end{equation}Whence upon taking the second derivative and evaluating at $\rho=\hat{\rho}$, we get\begin{align}\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho^2}}&=\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)+\frac{2\rho}{\left(1-\rho^2\right)^2}\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}+\left(\frac{2}{1-\rho^2}+{4\rho^2}{\left(1-\rho^2\right)}\right)\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}+\frac{2\rho}{1-\rho^2}\frac{\partial}{\partial\rho}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}\nonumber\\&=\frac{1+\rho^2}{\left(1-\rho^2\right)^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}-2\left(\frac{1+\rho^2}{\left(1-\rho^2\right)^2}\right)-\frac{2\rho^2}{\left(1-\rho\right)^2},\end{align}so that\begin{equation}\sigma^2_{\rho}=\frac{-1}{\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}=\frac{\left(1-\rho^2\right)^2}{1+\rho^2}.\end{equation}Then by the central limit theorem, the sampling variance of $\rho$ is $\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}$.
For the second form of the statistic, let's drop the assumption of bivariate normality and consider the regression of $Y$ on $X$ with normally-distributed error $\varepsilon$: if\begin{equation}Y=\alpha+\beta X+\varepsilon\end{equation}and\begin{equation}\sigma^2_Y=\beta^2\sigma^2_X+\sigma^2,\end{equation} then according to the relationship $\beta=\rho\frac{\sigma_Y}{\sigma_X}$, it must be the case that error variance is $\sigma^2=\left(1-\rho^2\right)\sigma^2_Y$.   Then the distribution of $\varepsilon$ is:\begin{equation}\mathcal{L}\left(\varepsilon\right)\sim\Pi_i\exp{\left(-\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\sigma^2}\right)},\end{equation}so that the log-likelihood is\begin{equation}\ell=-\sum_i\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}The first two derivatives are\begin{equation}\frac{\partial\ell}{\partial \beta}=\sum_i\frac{\left(Y_i-\overline{Y}-\beta\left(X_i-\overline{X}\right)\right)\left(X_i-\overline{X}\right)}{\left(1-\rho^2\right)\sigma_Y^2}\end{equation}and\begin{equation}\frac{\partial^2\ell}{\partial\beta^2}=-\sum_i\frac{\left(X_i-\overline{X}\right)^2}{\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}Now, making the substitution  $\beta=\rho\frac{\sigma_Y}{\sigma_X}$ and evaluating at $\rho=\hat{\rho}=r$ gives\begin{equation}\frac{-1}{\frac{\partial^2\ell}{\partial\beta^2}\bigr|_{\beta=\hat{\beta}}}=\frac{-1}{\frac{\partial^2\ell}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}\frac{\sigma^2_Y}{\sigma^2_X}=\frac{\sigma^2_Y\left(1-r^2\right)}{\sigma^2_X\left(n-2\right)},\end{equation}whence the sampling variance of the measured correlation coefficient $\hat{\rho}=r$ is\begin{equation}\sigma^2_r=\frac{1-r^2}{n-2},\end{equation} in which we lose two degrees of freedom from the estimation of two parameters $\alpha$ and $\beta$.  Finally, we can form a t-statistic to test the hypothesis that $r=0$ using \begin{equation}t=\frac{r}{\sigma_r}=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}For an alternate derivation, see The Analysis of Physical Measurements, pp. 193-199, by Pugh and Winslow cited in A brief note on the standard error of the Pearson correlation.
A comparison of the two formulas shows\begin{equation}\frac{\sigma^2_{\rho}}{n}=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}<\frac{1-r^2}{n-2}=\sigma^2_r.\end{equation}In other words, there is less variance of the true parameter $\rho$ than in the value estimated from linear regression.  It should also be pointed out that Pearson's formula is only true for bivariate normal variables, while the standard error of $r$ is valid for any linear regression.  However, we see that the test of whether $r=0$ is equivalent to the test of whether $\beta=0$ and does not really tell us anything new.
Comment: I didn't follow everything but the derivation looks well done, at least it is in accordance with my simulations and on the fact that the OP has to square the numerator of his formula. But why did you cross out some sentences, do you think they are wrong or is it just a style that you apply?
Comment: I had a change of heart about my first derivation and decided it must be this way instead.  However, I'd still like to see how we could derive the variance directly from E(X^2Y^2) - E(X)^2E(Y)^2, because I was getting nonsensical results (that had to be crossed out) from that approach.
Answer: After looking for a long time for an answer to this same question, I found a couple interesting links:
$\bullet$ The Standard Deviation of the Correlation Coefficient, where we can only see the first page but that's where the derivation is. The "standard deviation by dr Sheppard" is given by something called the Asymptotic distribution of moments, of which you can see a bit in the following source.
$\bullet$ A History of Parametric Statistical Inference from Bernoulli to Fisher, 1713-1935.
The reason for the "n-2" instead of "n" in the root, is that your formula assumes a t-distribution with n-2 degrees of freedom, while the one in the links assumes a normal distribution.
Comment: It looks like the equal sign in the formula should be written as an approximately sign then cause it reflect asymptotic behaviour rather than a closed form solution. Further, the SE of the correlation coefficient is also then heavily dependent on the sample size as far as I read it from Pearson original papers. Conclusion is that the formula for the SE of r cannot be simply obtained as it is the case for the SE of the mean or the variance.
Comment: Although it makes sense to have n-2 in the denominator since we use r as an estimate of $\rho$ there still must be somewhere a mathematical derivation of this which I would like to see. With the variance estimated from a sample we also get n-1 in the denominator which is mathematically derived as well and not just put because we reduce the degrees of freedom by one when using the samples expected value.
Answer: I do not have the answer, but for me there is an error in the formula of the question.
It is: $$SE_r =\frac{1-r^2}{\sqrt{n-2}}$$ and
$$\newcommand{\Var}{\operatorname{Var}} \Var(r)=\frac{(1-r^2)^2}{n-2}$$
I will try to check this by simulation:
library(MASS)

N = 100000
r = 0.8
n = 100

Sigma = matrix(c(1, r, r, 1), nrow=2)
r_obs =  replicate(N, cor(mvrnorm(n, c(0,0), Sigma))[2,1])

> mean(r_obs)
[1] 0.7984783
> sd(r_obs)
[1] 0.03690896

So the standard error for r=0.8 with n=100 is approximately 0.037.
If I use the formula of the question I get:
> sqrt((1-r^2)/(n-2))
[1] 0.06060915

And with the formula I gave:
> (1-r^2)/sqrt((n-2))
[1] 0.03636549

The second formula seems to be much closer to the true value than the first.
Edit:
To try to explain why there are two different formulas for the standard error which are circulating, I found that it depends on how you compute it.
In my first simulation, I used Pearson formula to compute the correlation, but one can also use the least square regression coefficient. I can confirm that the latter method has the standard error proposed in the question:
r_obs <- replicate(N, {
    M<-mvrnorm(n, c(0,0), Sigma)
    c(pearson=cor(M, method="pearson")[2,1],
      regression=lm(M[,2]~M[,1])$coef[[2]])
    })

> apply(r_obs, 1, mean)
   pearson regression
 0.7981580  0.7998433
> apply(r_obs, 1, sd)
   pearson regression
0.03707184 0.06094964

These are two estimators of the correlation which do not have the same variance.
Edit 2:
That try to reconcile the two formulas did not work, because I forgot to normalize the regression coefficient. The formula to compute the correlation from the regression coefficient is:
$$r=\frac{SD(x)}{SD(y)}b$$ with $$E(y|x)=a+b\cdot x$$
By redoing the correct computation, I obtain in fact the same result:
r_obs <- replicate(N, {
    M<-mvrnorm(n, c(0,0), Sigma)
    c(pearson=cor(M, method="pearson")[2,1],
      regression=lm(M[,2]~M[,1])$coef[[2]]*sd(M[,1])/sd(M[,2]))
    })
> apply(r_obs, 1, sd)
   pearson regression
0.03676248 0.03676248
> apply(r_obs, 1, mean)
   pearson regression
 0.7992615  0.7992615

Which is reassuring in some way. So I maintain that the standard error formula in the question is incorrect, but maybe I explained where does the error come from.
Comment: There is no error in the original formula: see https://en.wikipedia.org/wiki/Pearson_correlation_coefficient.  You will discover your formula doesn't seem to work, either, if you set `n <- 3` instead of `100` and `r <- 0` instead of `0.8`.  There are several problems, one of which is that the formula of the question is a reasonable standard error only when $r$ is close to zero. Another is that the sampling distribution can be highly skewed, rendering any SE less than useful: that's why better analyses re-express $r$ with the Fisher transformation.
Comment: I think that `n=3` is a too special case to judge. I don't know, maybe `n-2` is not the good divisor, maybe it is `n-3`. Beyond that, the two formulae give the same result for `r=0`.
Comment: Please explain the downvotes. In addition, I would like to know where I can find the formula of the standard error of the raw correlation coefficient (not the Fisher transform) in the Wikipedia page. Logically it should be in this section: https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Inference, but I am unable to see it.
Comment: Yes checking by simulation is not a mathematical proof, but if simulations do not match a formula but match another there are reasons to think that the other formula is better. For Wikipedia it is just the other guy who suggested me to check the formula there, I just answered that I was unable to find it, I did not deduce anything more. But now the formula of the standard error has been added, and guess what, that's not the formula of the question but the one of my answer which is written there.
Comment: First of all: 'Checking' by simulation is not a mathematical proof. Second, just because it is not on wikipedia it does not mean it is not existent. It just means no one has yet copy/paste information to it.
Comment: How crazy: everyone is downvoting my answer but it is still taken as reference in the Wikipedia page. Go modify the Wikipedia page if you think my answer is not right.


Do all continuous functions have antiderivatives?

Question: If not all continuous functions are differentiable, so how is it that all continuous functions have anti-derivatives?
Comment: Not all natural numbers can be divided by 2, how is it that all can be multiplied by 2?
Comment: @ProfessorVector : if it were that trivial most calculus books would have proved it. It is trivial only when you are already aware of it. The fact that continuous functions are integrable is a typical example of "theorems whose proofs are beyond the scope of the introductory books" but somehow their statements are in their scope.
Comment: Let's say very it openly: continuous functions possess anti-derivatives and the whole gamut of elementary calculus textbooks has failed miserably to explain why it is so. The proof is not easy and fundamental theorem of calculus is just one part (the easier one) of the story here. The more difficult part deals with the integrability of continuous functions.
Comment: Also @ProfessorVector: both facts from number theory are almost trivial to prove. The case here is that it is difficult to show that continous functions possess anti-derivatives. I suppose your analogy is more to illustrate that such contrasts should not be hard to believe.
Comment: Because $g(x)=\int_0^x f(t)\,dt$ is differentiable and $g'(x)=f(x)$.
Comment: @Paramanand Singh That's relative, I find that proof very simple, almost trivial. And it explains very well why it works: because a continuous function doesn't change much in a small interval. So upper and lower integrals don't differ much, and the mean value you get from the difference quotient of the integral function doesn't differ much from the function value.
Answer: Let $I\subset\mathbb R$ be an interval with more than one point. If $f\colon I\longrightarrow\mathbb R$ is a continuous function, the existence of an anti-derivative of $f$ can be proved as follows: take $a\in I$ and define$$\begin{array}{rccc}F\colon&I&\longrightarrow&\mathbb R\\&x&\mapsto&\displaystyle\int_a^xf(t)\,\mathrm dt.\end{array}$$Then $F$ is a primitive of $f$, by the Fundamental Theorem of Calculus.
You seem to find it strange that every continuous has an anti-derivative while not all continuous functions are differentiable, but it's up to you to explain what's strange about it.


Jquery removeData not working for modal that is called with href inorder to pass $_GET values

Question: I'm coding a website that populates a table dynamically from the database, and each row on the table has a button that calls launches a modal to view more details of that particular row (details are also dynamically generated from the database) and makes database updates. So in order to pass the needed values to my modal.
I declared the modal on the same page

then i called the rest of my modal with an href to pass database id's
echo "

	";

My problem is I also make form updates using jquery to avoid page reloads, but because I'm calling the rest of the modal with an href I have to link my jquery libs to that particular page else it wouldn't respond, of which I do not really understand why. But when i do this it works fine. The only problem is, on the page where the modal is called from, my jquery script which helps my remove data from my modal when closed stops working and only this particular script. Here is the script.

When i remove the jquery libs from my href modal page the script above works just fine, but I wouldn't be able to make an update using jquery and avoid a page reload
here is the code for calling the modal with href (the entire page)
<?php
  include '../connection/connect.php';
  $store_key = $_GET['id3'];
  $category_key = $_GET['id2'];
  $date = date("M, l Y", strtotime('Today'));

  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Date: (<?php echo $date;?>)

      <form id="register_formProduct1">

              <select class="form-control" name="category">
        <?php
          $query = "SELECT * FROM product_category WHERE store_key = '{$store_key}' AND category_key = '{$category_key}' LIMIT 1";
        $result_set = mysql_query($query);
        while($result = mysql_fetch_array($result_set)){
            echo "<option value='{$result['category_key']}'>".  ucfirst($result['category_name'])."</option>";
          }
        ?>
               </select><button type="button">Submit</button>

        </form>

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

How can I make both scripts work for me simultaneously?
Comment: so hidden.bs.modal is calling or not
Comment: it's doesn't call when i link my jquery libs to my href modal page, but it works when i remove it, only that i need my jquery libs on my href modal page to submit a form with jquery.
Comment: Where is `#invoiceModal` ? The only modal you mentioned in your question is having id `add_branchProductModal`
Comment: sorry i posted the wrong code, but i've corrected it now.
Answer: Modal in my page:

My  tag that i used to call the modal body and send variables to it
echo "

 "

I called the function to submit my form within my modal when it opens
$('#add_branchProductModal').on('shown.bs.modal', function (e) {
  // Function that submits my form within the modal body
  $("#submit_product1").submit(function(e) {
    e.preventDefault();
      var form = e.target;
      var data = new FormData(form);
    if (string.IsNullOrWhiteSpace(Request.Form["form_name"])) {
      alert("Insertion Failed, Some Fields are Blank....!!");
    } else {
     if(data.get('pieces') < data.get('reorder')){
      alert("Re-order Level cannot be greater than pieces available!!");
     }else{
       $.post("scripts/product_update.php",{
        data:data
       }, function(data) {
           alert("Product successfully added!!!");
           $('#register_formProduct1')[0].reset(); // To reset form fields
      });
     }
   }
  });
});

clear modal on close
$('#add_branchProductModal').on('hidden.bs.modal', function () {
   $(this).removeData('bs.modal');
});


Edição na ListView

Question: Criei um xml separado para mexer melhor com o ListView.. só que não estou conseguindo relacionar o id dele no meu onCreate
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:textColor="@color/corList"
        tools:targetApi="ice_cream_sandwich"
        android:paddingRight="?android:attr/listPreferredItemPaddingRight"
        android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" />

</LinearLayout>

esse xml esta no /res/layout/resultado_modificado.xml
Java:
package com.allsport.miyonic.allsport;

import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

        import Base.DbHelper;
        import Base.Esporte;

        import static android.os.FileObserver.DELETE;

public class ResultSimples extends AppCompatActivity {

    private ListView lista;
    private Button apagar;
    public TextView txt;

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

        lista = (ListView) findViewById(R.id.ListaTimes);
        apagar = (Button) findViewById(R.id.btndeletar);
        txt = (TextView) findViewById(R.id.text1);
        apagar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DbHelper dd = new DbHelper(ResultSimples.this);
                dd.delete(); // É necessário passar o parâmetro
            }
        });
    }

    @Override
    public void onResume(){
        super.onResume();

        DbHelper dbhe = new DbHelper(this);
        List<Esporte> listaResultPartida = dbhe.selectTodosResult();

        ArrayAdapter<Esporte> adp = new ArrayAdapter<Esporte>(this, R.layout.resultado_modificado, listaResultPartida);

        lista.setAdapter(adp);
    }
}

Obrigado...
Comment: Nathan, você teria que postar o xml do item do `Adapter` que está passando para o ListView. Não tem como alterar a cor do item diretamente do `ListView`.
Comment: Então @Wakim como que funciona... tentei olhar na internet e não consegui entender... parece que o `Adapter` necessita de um `TextView` ou algo desse tipo.... como que funciona?
Comment: Então Nathan, recomendo que dê uma olhada nesse link: https://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews. Tem uma documentação bem detalhada sobre a customização do `ListView`.
Comment: @Wakim, preciso criar um xml separado com o textview e depois no java eu chamo ele como se fosse no `simple_list_item_1` é isso né?
Comment: Isso exato, como o `simple_list_item_1` é do framework, você não consegue alterar o xml. Existem duas alternativas, ou você cria um Adapter próprio e altera a cor programaticamente quando a `View` for criada, ou cria um xml semelhante e altera a cor no xml. Eu recomendo a segunda abordagem, fica mais claro e da menos trabalho.
Comment: Criei um xml, e coloquei no java na parte do `onResume` essa linha   `ArrayAdapter adp = new ArrayAdapter(this, R.layout.resultado_modificado, listaResultPartida);` e esta me apresentando esse erro no LogCat **java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView** só que no onCreate não estou conseguindo relacionar ele, chamando o `ID` - criei um private em cima `(private TextView txt;)` e dentro onCreate `txt = (TextView) findViewById(R.id.txt1);` e não está indo.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/47886/discussion-between-nathan-and-wakim).
Answer: Consegui com ajuda do @Wakim, precisei passar o id dentro do construtor do Adpter
dessa forma:
@Override
    public void onResume(){
        super.onResume();

        DbHelper dbhe = new DbHelper(this);
        List<Esporte> listaResultPartida = dbhe.selectTodosResult();
        ArrayAdapter<Esporte> adp = new ArrayAdapter<Esporte>(this, R.layout.resultado_modificado, android.R.id.text1, listaResultPartida);

        lista.setAdapter(adp);
    }
}

Edição na ListView


dimension formulas for $\mathbb{Z}$-module homomorphisms

Question: I have a general question on using dimension formulas for linear maps.
I only know the some dimension formulas for linear maps $f:V\to W$ between $k$-vector spaces $V$ and $W$, i.e. $\dim{(V)}=\dim{(\ker(f))}+\dim {(\text{Im}(f))}$
What about if $f$ is a $\mathbb{Z}$-linear map between finitely generated abelian groups $V$ and $W$, do I have a similar dimension formular as above, i.e. $\text{rank}(V)=\text{rank}(\ker(f))+\text{rank}(\text{Im}(f))$? If yes, in which situations is it allowed to apply dimension formulas?
The background of my question is the following:
I want to calculate (for example) the simplicial homology with coefficients in $\mathbb{Z}$ for the torus $X=S^1\times S^1$ (considered as a topological space) and therefore I have to calculate the kernels and images if the simplicial boundary maps $\partial_*$. It is possible to write down transformation matrices of these boundary maps with respect to the canonical bases. Afte applying Gaussian elimination to determine the kernels and ranges I tried to apply a dimension formula as above. For the torus I obtained a correct solution, but I guess if you do this for the $\mathbb{RP}^n$ instead of the torus, again homology with coefficients in $\mathbb{Z}$, you obtain a wrong solution (if I remember correctly! I'm not 100 % sure) I guess.
Regards
Comment: To compute kernels and images in the chain complex, it's usually best to put the matrices representing the differentials into [Smith normal form](https://en.wikipedia.org/wiki/Smith_normal_form).
Answer: The dimension formula for $\mathbb{Z}$-linear maps is indeed true. In fact, it can be reduced to the dimension formula for $\mathbb{R}$-linear maps by applying the tensor product over $\mathbb{R}$ (or you can work over $\mathbb{Q}$ if you prefer).
However, this is not the best way to calculate the homology of $S^1 \times S^1$ with $\mathbb{Z}$ coefficients, because it will tell you nothing about the torsion in the homology. Instead, if you have gone so far as to determine the kernels and ranges using Gaussian elimination, you should be able to go one step further and determine the quotient $\frac{\text{cycles}}{\text{boundaries}}$ precisely, not just its rank. All you are missing is a precise description of the boundaries expressed in terms of a basis for the cycles.
Comment: okay, thank you. Yes, I'm able to determine the quotient precisely (and I prefer other ways as Gaussian elimination, since I don't like Gaussian elimination)


How to fetch a video from db in codeigniter

Question: I'am trying this Code
<video width="320" height="240" controls>
<source src="<?php echo 'resource/video/';  echo $image; ?>" type="video/mp4">
 <source src="<?php echo 'resource/video/';  echo $image; ?>" type="video/ogg">    </video>

Comment: Yes and what are you trying to achieve?
Comment: https://www.codeigniter.com/userguide2/database/active_record.html if v2
Comment: https://www.codeigniter.com/user_guide/database/query_builder.html if v3
Answer: You can use base_url() like this:
<video width="320" height="240" controls>
             <source src="<?php echo base_url('resource/video/'.$image); ?>" type="video/mp4">
             <source src="<?php echo base_url('resource/video/'.$image);   ?>" type="video/ogg">