Find dominant eigenvector

Question:
Consider the $5x5$ tridiagonal matrix with entries $a_{i,i} = 2$,
$i=1,2,...,5$ and $a_{i,i+1}= a_{i+1, i} = 1$ , $i=1,...,4$. Knowing
that the initial approximation $x_0  =(0.5,0.8,1,0.8,0.5)$  is almost
aligned with the dominant eigenvector of the matrix, determine until
the fifth iteration an approximation of the dominant eigenvalue.

So, the first thing I did was to construct the matrix:
$A = \begin{bmatrix}
2 & 1 & 0 & 0 & 0\\
1 & 2 & 1 & 0 & 0\\
0 & 1 & 2 & 1 & 0\\
0 & 0 & 1 & 2 & 1\\
0 & 0 & 0 & 1 & 2\\ \end{bmatrix}$
Then I calculated $A^5x_0 = \begin{bmatrix} 348.2\\603.1\\696.4\\603.1\\348.2\end{bmatrix} = \lambda^5x_0$. But from now on I'm stuck. How can I calculate the dominant eigenvector from here?
Answer: $x_0$ is close to the dominant eigenspace. $A^4x_0$ is even closer to the dominant eigenspace. Choose an entry (say, the first entry), and calculate the ratio between that entry in $A^5x_0$ and $A^4x_0$.
Comment: That's the right answer indeed according to solutions. But could you please elaborate on why that is the case?
Comment: @rato Elaborate on why what is the case? Could you be a bit more specific?
Comment: Because I don't really understand the logic behind the ratio of the component at 5th iteration with the same component on the 4th iteration being the dominant eigenvalue.
Comment: @rato Since $A^4x$ is almost an eigenvector corresponding to the dominant eigenvalue $\lambda$, we get $$A^5x=A(A^4x)\approx \lambda A^4x$$The easiest way to (approximately) find this $\lambda$ is just to see how much one entry is scaled by as you go from $A^4x$ to $A^5x$. If $A^4x$ were a true eigenvector, the entries would all scale by the same amount. Since it is instead close to a true eigenvector, the entries each scale a little differently, but they all scale close to the same amount.
Answer: The question only asks you to compute the dominant eigenvalue, which is approximated by the fifth root of 696.4.

Find dominant eigenvector


Writing a melody tips

Question: I have posted before about improvisation but may be jumping ahead of myself, I am familiar with basic music theory and have knowledge of major/minor scales and chords. I am interested in composition and before learning to compose a full song (which is what I previously asked for) I'm interested in creating melodies and techniques which would help me figure this out instead of spending so many years with trial and error. I have got a fair few tips out of the book by Michael Miller - Music Theory & Music Composition including:
-Stay within the scale
-Mix steps and skips
-Variety
-Degree of repetition
When I sit at the keyboard I cannot come up with anything remotely creative or good and want to get better/develop this skill and focus on it so I can apply it to my own compositions. Any books, tips etc. that will help.
Also, having studied basic theory and being familiar, what's the next step or would help with composing or is down to tonnes of practice, it's difficult for me because I really cannot get anything good yet.
Additionally, I recreated some MIDI files of piano which I found really inspiring (got me into all of this) and was wondering how to apply tips and tricks I can use towards my own creations. For example, I know I need to learn chord inversions and extending chords as that's been used but as far as the melodies go, each piece is unique and I'm not sure how to dissect it to help me write my own and figure out why it works..
Comment: This may very well be too broad of a question. I can very easily see myself reading a whole book on melody writing.
Comment: I had to go through several pages worth of my answers but I did finally get the question that this is a dup of.
Comment: Thanks Neil. On the other thread I'm glad you said this: "Starting to write melodies is a painful process. It needs a lot of practice to do effectively. It also is one of the reasons why Music Theory is such a crucial part of music education" - because I don't feel that unnatural at writing now :)
Answer: There are so many tips... It will depend a lot on what sort of music you're hoping to compose, but let's take some simple poppy type song. An idea is that you write the chords that fit to a key. Say C major. The chords will be C, Dm, Em, F, G, Am and Bo. Write them on bits of paper, one on each. Turn them face down. Since the piece will be in C, that's the first chord. Chances are it'll also be the last! Let's make it a 16 bar song. So for bar two we need chord two. Turn over a paper, write that down. If it's C again, so what? Put the paper back, shuffle, pick. Continue till you get to bar 15, as 16 is C. Play it through. You may find it works, you may want to change some round, for example, bar 8 could be back at C, or G could sound better.
When you're happy, play again, this time with a basic melody - which will have to fit the chords, as in where there's an F that bar will contain an F, A and/or C, along with a passing note or two. A tune will probably make itself apparent over the changes, so don't force it, let it happen. I've kept it straightforward, and later you could add in major/minor/dominant 7ths, 6ths etc.
So many tips, but this is just one. Give it a go!
Comment: Back to this thread, I have recently started learning songs on the keyboard after learning some basic theory in order to apply it. What is a good idea to help with writing melodies? I was hoping to become more comfortable with the keys in general and develop skills playing but want my focus to be more on improvising strong melodic lines. I'm not sure if it's a good idea to either practice songs, analyse songs or improvise my own melodies or all three?
Answer: The way I would teach melody writing would be as follows.

Choose an instrument. This includes being familiar with its range and knowing what clef it operates in. A good knowledge about how its phrasing marks work is also advantageous.
Pick a key. This includes instrument appropriate keys. We are not going to write melodies for guitar in Cb Major.
Pick a Time signature. This has some considerations. Compound Time Signatures will definitely swing effect to decide if you want this. If you want a Waltz you are going to have to operate in three time.
Decide on Form. This is probably the most important characteristic of a good melody. How does the line look? Don't jump too large intervals. Avoid jumps of sevenths. When you jump only jump to chordal notes. Don't jump twice in a row. When you jump up go down afterward. When jumping down go up afterwards. Have a pleasant line.
Choose Chords People don't believe me when I say this but melodies are build on chords. If you want an 8 bar melody choose 8 chords one for each bar. The notes from these chords form the nucleus of the melody. You try to end and start the bar with chord notes. You jump to and from only from them. You use the chord notes most often.
Cadences: Your phrases need to end with a pause (longer note) and you have to use cadences to end your phrases. Know the four of them and how they resolve. Don't use an cadence that ends on the tonic in the middle of the passage and conversely don't end the passage on the Imperfect or Interrupted Cadence.
Sevenths and leading tones have to resolve.
Rhythmic Sequence When you have ended a phrase with a cadence it is good form to have a rhythmical sequence. That is a rhythm from the previous passage that is repeated for two bars. You do not need to imitate those bars. The rhytm has to be same not neccessarily the notes.

**
Comment: I'll read try these techniques out thanks a lot! I'll also look at the thread you posted Neil - cheers for that!

Are there any specific websites or rules per se to follow when starting out other than those mentioned? Im going to analyse music pieces I've got to the tips discussed and see how it fits in. A lot of the music mixes notes with chords but sounds so pleasant, not necessarily using chord tones with each chord

Writing a melody tips


Cone and space homeomorphism question

Question: I am wondering:
Under what conditions is a space homeomorphic to its cone?
Moreover, if $M$ is a compact manifold, is it always homeomorphic to its cone? What about if for manifolds of different dimensions? That is, does there exists a dimension where $M^n$ is homeomorphic to its cone?
Comment: Have you tried any examples at all?
Comment: I'm just curious, I just suddenly woke up and thought of this, so I didn't have enough time. But thinking about this more, if we have the sphere, then it's cone is homeomorphic to the closed disk.  But the sphere is not homeomorphic to the disk, other than that, no.
Answer: There are certainly spaces where $CX \approx X$, but manifolds do never have this property.
Let $M$ be  manifold of dimension $n$. Then $CM$ contains an open subspace homeomorphic to $M \times (0,1)$ (simply remove the tip and the base $X \times \{0\}$ from $CX$). If $CM \approx M$, then $M$ would contain an open subspace homeomorphic to $M \times (0,1)$  i.e. a manifold of dimension $n+1$. This is impossible.
A positive example is the Hilbert cube $Q$  (the countable infinite product of closed unit intervals). We have $CQ \approx Q$; see here.
Comment: A cheaper, but perhaps slightly simpler example of a space homeomorphic to its cone would also be an infinite simplex.

Cone and space homeomorphism question


Irony AST generation throws nullreference excepttion

Question: I'm getting started with Irony (version Irony_2012_03_15) but I pretty quickly got stuck when trying to generate an AST. Below is a completely strpped language that throws the exception:
[Language("myLang", "0.1", "Bla Bla")]
    public class MyLang: Grammar {
        public NModel()
            : base(false) {

            var number = TerminalFactory.CreateCSharpNumber("number");
            var binExpr = new NonTerminal("binExpr", typeof(BinaryOperationNode));
            var binOp = new NonTerminal("BinOp");

            binExpr.Rule = number + binOp + number;
            binOp.Rule = ToTerm("+");
            RegisterOperators(1, "+");
            //MarkTransient(binOp);
            this.Root = binExpr;
            this.LanguageFlags = Parsing.LanguageFlags.CreateAst; // if I uncomment this line it throws the error
        }
    }

As soon as I uncomment the last line it throws a NullReferenceException in the grammar explorer or when i want to parse a test. The error is on AstBuilder.cs line 96:
  parseNode.AstNode = config.DefaultNodeCreator();

DefaultNodeCreator is a delegate that has not been set.
I've tried setting things with MarkTransient etc but no dice.
Can someone help me afloat here? I'm proably missing something obvious. Looked for AST tutorials all over the webs but I can't seem to find an explanation on how that works.
Thanks in advance,
Gert-Jan
Answer: Once you set the LanguageFlags.CreateAst flag on the grammar, you must provide additional information about how to create the AST.
You're supposed to be able to set AstContext.Default*Type for the whole language, but that is currently bugged.

Set TermFlags.NoAstNode. Irony will ignore this node and its children.
Set AstConfig.NodeCreator. This is a delegate that can do the right thing.
Set AstConfig.NodeType to the type of the AstNode. This type should be accessible, implement IAstInit, and have a public, no-parameters constructor. Accessible in this case means either public or internal with the InternalsVisibleTo attribute.
Comment: Hi Jay, thanks for your answer. Actually stopped using Irony as parser because of the available support. Pity, it looks very nice, too bad it's not catching on to what it deserves. Hope you got a necromancer badge out of this one!
Comment: @gjvdkamp What parser are you using now? I have the same problem and I'm also not satisfied with the documentation or web tutorials support for this project. It may be good, but it entirely fails to communicate it, making it useless.
Comment: The last grammar that actually flew well was with ANTLR on .Net, also much because of ANTLRWorks. I've been out of this topic for years now so a lot may have happened in the mean time. The new versions of both look pretty promising... On F# you might want to look at fParsec or Active Patterns.
Answer: To be honest, I was facing the same problem and did not understand Jay Bazuzi answer, though it looks like valid one(maybe it's outdated).
If there's anyone like me;
I just inherited my Grammar from  Irony.Interpreter.InterpretedLanguageGrammar class, and it works. Also, anyone trying to get AST working, make sure your nodes are "public" :- )
Answer: On top of Jay's and Erti-Chris's responses, this thread is also useful:
https://irony.codeplex.com/discussions/361018
The creator of Irony points out the relevant configuration code in InterpretedLanguageGrammar.BuildAst.
HTH


How to make setting persistent with 'adb shell settings'

Question: The next command enables phone call recording in OnePlus phones (may be others too):
<code>adb shell settings put global op_voice_recording_supported_by_mcc 1
</code>
But after reboot its effect is disabled. My phone is OnePlus 6T.
How to make this setting persistent?
Answer: https://forum.xda-developers.com/oneplus-5/themes/app-enable-call-recording-boot-t3634292
This link has other root-required methods you might want to try.
Unfortunately, I am also trying to find a way without root. As the setting automatically turns off, sometimes before reboot, when you have an active some-country sim card, my hypothesis is that there is a "checking" program going on under the hood. If there is an adb command to turn off that "checking", the result should be permanent.
Answer: jOnePlus Tools is an answer. This application sets settings up on every reboot.
Comment: Thank you, I didn't know this APP and now I have call service activated by default. Although I have to open the APP apply the settings at each reboot
Comment: There is an option "auto apply on start up" so no need to reapply settings every reboot
Comment: I don't find that option in the APP settings. Is it enabled only for root devices?
Comment: My device is not rooted
Answer: I also have a 6T, and what I could see about what causes recording to be disabled, is any application installation made by PlayStore.
If you keep the automatic update function of the applications deactivated, the recording remains activated, but anytime you do any installation on the PlayStore, the recording will be disabled and you will need to enable it with the command again.
Comment: It's actually worse. If you switch to airplane mode and then restore network connectivity the same will happen. It seems on Android 11 they added a region check whenever some change occurs on the phone, which disables call recording when they realize you're not in India (where it's enabled).


Use common templates for different states

Question: I want to be able to use two common components through out my app in all the states basically the header and the sidebar. I have read through the docs but i must have missed something. How can i reuse the header and sidebar in the states
  $stateProvider
    .state('home', {
        url: '/leads:id',
        views: {
          'details': {
              templateUrl: '../views/details.html',
              controllerProvider: function($stateParams) {
                  if($stateParams.id) {
                      return 'CompanyDetails as companydetails';
                  }else {
                      return 'NewCompanyDetailsController as companydetails';
                  }

              }
          },
          'sidebar': {
              templateUrl: '../views/sidebar.html'
            },
          'header': {
              templateUrl: '../views/header.html',
              controller: 'HeaderCtrl as header'
           },
          'vehicledetails': {
              templateUrl: '../views/vehicledetails.html',
              controller: 'VehicleDetailsController as vehicledetails'
          },
          'comments': {
              templateUrl: '../views/comments.html',
              controller: 'CommentsController as comments'
          },
          'saveupdate': {
              templateUrl: '../views/saveupdate.html',
              controller: 'SaveUpdateDetailsController as saveupdate'
          }
        }

    });

I want to create another state called 'data' for example which reuses the header and sidebar. How can I acheive this without requiring to write down all the the components again ?
I did a bit of reading and now, I have an updated state provider that displays the common header and sidebar on all routes but the data inside the actual container is not being displayed at all. Here is my updated code
$stateProvider
        .state('home', {
            abstract: true,
            views: {
              'header': {
                  templateUrl: '../views/header.html',
                  controller: 'HeaderCtrl as header'
              },
              'sidebar': {
                  templateUrl: '../views/sidebar.html'
               }
             },
             resolve: {
                  somedata: function(){return {}}
              }

        })
        .state('home.login', {
            url: '/',
            views: {
               'login@home': {
                          templateUrl: '../views/login.html'
                        }
                }
        })
        .state('home.leads', {
            url: '/leads:id',
            views: {
              'details@home': {
                  templateUrl: '../views/details.html',
                  controllerProvider: function($stateParams) {
                      if($stateParams.id) {
                          return 'CompanyDetails as companydetails';
                      }else {
                          return 'NewCompanyDetailsController as companydetails';
                      }
                  }
              },
              'vehicledetails@home': {
                  templateUrl: '../views/vehicledetails.html',
                  controller: 'VehicleDetailsController as vehicledetails'
              },
              'comments@home': {
                  templateUrl: '../views/comments.html',
                  controller: 'CommentsController as comments'
              },
              'saveupdate@home': {
                  templateUrl: '../views/saveupdate.html',
                  controller: 'SaveUpdateDetailsController as saveupdate'
               }
            }

        });

and my index.html

Comment: Have you already considered the parent state? I would vote for that. It could be few super root states .. abstract not effecting url.. but providing some same stuff to similar sub-state families... e.g. [here](http://stackoverflow.com/a/28826126/1679310) or [there](http://stackoverflow.com/a/29561066/1679310)
Comment: can you show the controller where you want to display that data?
Comment: The problem is that even the template inside the login.html doesn't show up. So i am guessing I am still missing something there
Answer: I actually managed to get this working now using this link https://stackoverflow.com/a/28826126/1679310
I will explain my answer since I couldnt understand how it worked before I did it on my own. You need this to be present for the child states to plug into it.
https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#scope-inheritance-by-view-hierarchy-only
Basically you create a main ng-view inside the index.html that serves as the container to your others partials then you basically contain all the child ui-views inside another layout that will serve as the parent to all the states.
So in essence your structure is something like this

and another file that has the layouts

Then you basically follow the pattern here
  $stateProvider
    .state('home', {
        abstract: true,
        views: {
            '@': {
                templateUrl: '../views/layouts.html'
                },
            'header@home': {
                templateUrl: '../views/header.html',
                controller: 'HeaderCtrl as header'
            },
            'sidebar@home': {
                templateUrl: '../views/sidebar.html'
             }
         }
    })
    .state('home.login', {
        url: '/',
        views: {
           'login@home': {
                      templateUrl: '../views/login.html'
                    }
            }
    })

For all your states. This worked for me and I am pretty sure that is the right way to do so.
Comment: Nice! Really nice. Enjoy UI-Router ;)
Comment: This solution uses a lot of repeated parts. It's best to use only a root view and sub states
Answer: There's a better way:
HTML part
Index file (index.html):

Base file (layout.html)

    Here's the header part

    Here's the sidebar part

    And here is where the app will be ran when you go to a state like "app.home"

States:
var states = {
    'app': {
        templateUrl: 'app/layout.html',
        controller: 'LayoutController as layout'
    },

    'app.home': {
        templateUrl: 'app/home.html',
        controller: 'HomeController as home'
    }
};

angular.forEach(states, function(config, name) {
    $stateProvider.state(name, config);
});

Comment: The reason why i organized it in that way was because the header is dynamic and it needed to have it's own controller for the sake of better code oranigzation.
Comment: That's not a problem. inside layout.html you can have smaller chunks of code with different scopes as well. You can even have a header.html file added via ng-include and with a custom controller through ng-controller.


how to create multiple table in SQLite using properties in windows phone 8

Question: how can I create multiple tables using entity classes
public class Info
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string imageUrl { get; set; }
         [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
         public DetailInfo objDetailInfo{ get; set; }
    }

    public class DetailInfo
    {
        public string phoneno { get; set; }
        public string address { get; set; }
    }

I am using the below code
public void createtable()
{
  SQLite.SQLiteConnection db= new SQLite.SQLiteConnection(dbPath);
   db.CreateTable<Info>();
   var data = new Info() { Id = "1", firstName = "Rehan", imageUrl = "safsdfsdf", lastName = "Parvez", objsty = new objDetailInfo{ address = "Nagpur", phoneno = "902136" } };
   db.Insert(data);

 }

while Executing db.CreateTable<Info>() it is giving me an Error
Comment: An exception of type 'System.NotSupportedException' occurred in mscorlib.ni.dll but was not handled in user code

If there is a handler for this exception, the program may be safely continued.
Comment: Anyone got the answer for this? We are in need of solution. Help us.
Answer: I am answer my question myself because I think It will help to my other friends
Use Ignore Keyword
public class Info
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string imageUrl { get; set; }
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [Ignore]
    public DetailInfo objDetailInfo{ get; set; }
}

public class DetailInfo
{
    public string phoneno { get; set; }
    public string address { get; set; }
}

public void createtable()
{
   SQLite.SQLiteConnection db= new SQLite.SQLiteConnection(dbPath);
   db.CreateTable<Info>();
   db.CreateTable<DetailInfo>();
}

Answer: Here is another way, as documented by sqlite-net,
Summery,
public class Stock
{
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        [MaxLength(8)]
        public string Symbol { get; set; }
}

public class Valuation
{
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        [Indexed]
        public int StockId { get; set; }
        public DateTime Time { get; set; }
        public decimal Price { get; set; }
}

With these, you can automatically generate tables in your database by calling CreateTable:
var db = new SQLiteConnection("stocks.db");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:
public static void AddStock(SQLiteConnection db, string symbol) {
        var s = db.Insert(new Stock() {
                Symbol = symbol
        });
        Console.WriteLine("{0} == {1}", s.Symbol, s.Id);
}

You can query the database using the Query method of SQLiteConnection:
public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
        return db.Query<Valuation> ("select * from Valuation where StockId = ?", stock.Id);
}

this query can also be written using Linq syntax so that you type safety and so that your refactors are safe:
public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
        return db.Table<Valuation> ().Where(v => v.StockId == stock.Id);
}

The generic parameter to the Query method specifies the type of object to create for each row. It can be one of your table classes, or anyother class whose public properties match the column returned by the query. The Table method requires that a table exists with the same name as the type being returned.
public class Val {
        public decimal Money { get; set; }
        public DateTime Date { get; set; }
}
public static IEnumerable<Val> QueryVals (SQLiteConnection db, Stock stock)
{
        return db.Query<Val> ("select \"Price\" as \"Money\", \"Time\" as \"Date\" from Valuation where StockId = ?", stock.Id);
}


The affine coordinate ring of twisted cubic curve, $Y$ is $A(Y)=k[x,y,z]/(z-x^3, y-x^2)$?

Question: I am working on the following problem:
Let $Y \subset A^3$ be the set $Y={(t,t^2,t^3)|t\in k}$
($A^3$ is the affine 3-space over $k$ an algebraically closed field.)
Show that $Y$ is an affine variety of dimension 1. Find generators for the ideal $I(Y)$. Show that $A(Y)$ is isomorphic to a polynomial ring in one variable over $k$.
I have found an answer which goes like this:
Clearly, $A(Y)=k[x,y,z]/(z-x^3, y-x^2)$. Note that $A(Y) =
k[x,x^2,x^3]= k[x]$ so Y is irreducible, and $Y$ is an affine variety. and dim $Y$ = dim $A(Y)$ = dim $k[x]$ = 1 and $I(Y) = (z-x^3,y-x^2)$
I am finding it difficult to understand this answer, it doesn't even look like it has addressed each part of the answer. In particular, how does one show $A(Y)=k[x,y,z]/(z-x^3, y-x^2)$?
I would also greatly appreciate a better way to approach this.
Comment: This is exercise 1.2 of Algebraic geometry by Hartshorne.
Answer: In order to show that $A(Y) = k[x, y, z]/(z-x^3, y-x^2)$, the simplest way is to show that $Y = Z(z-x^3, y-x^2)$, i.e. the variety in $\Bbb A^3_k$ that has the coordinate ring $ k[x, y, z]/(z-x^3, y-x^2)$ has the same underlying set of points as the image of the map $t \mapsto(t, t^2, t^3)$.
This is done by showing inclusion both ways. First of all, it's easy to check that $Y \subseteq Z(z-x^3, y-x^2)$, since for any $t \in k$ we have $t^3-t^3 = 0$ and $t^2 - t^2 = 0$.
For the other inclusion, say we have a point $(a, b, c) \in Z(z-x^3, y-x^2)$. That means that $c - a^3= 0$ and $b - a^2 = 0$, or in other words, $b = a^2$ and $c = a^3$. Then clearly $a \mapsto (a, b, c)$ by the parametrisation that defines $Y$, so $(a, b, c) \in Y$.
As for how to guess at $(z-x^3, y-x^2)$ as the defining ideal in the first place, it's mostly practice. There are, however, a few pointers to get you started: Since $Y$ is a curve in $\Bbb A^3_k$, you should try to look for two generators as a start. Some times you might need more (like for instance $t \mapsto (t^3, t^4, t^5)$, which corresponds to the ideal $(x^5 - z^3, x^4 - y^3, y^5 - z^4)$). Other than that, you just stare at the parametrisation and write down any relations that you see fit, in as low degree as possible. Some times you write too many, some times the presence of one generator means you can simplify another.
Comment: @cat Note that $$y^3 - z^2 + (y^2 + x^2y + x^4)(x^2 - y) - (z +x^3)(x^3-z) = 0$$Working it out directly took a small amount of work, but if you divide out by $(x^2-y,x^3-z)$ first, you can see directly that $y^3-z^2 \simeq x^6-x^6 = 0$.
Comment: Is $(z-x^3, y-x^2) = (z-x^3, y-x^2, y^3- z^2)$ ? The inclusion "$\subseteq$" is obvious, but I cannot see immediately if $y^3 - z^2 \in (z-x^3, y-x^2)$ or not....

The reason I ask is because I naively wrote down $(z-x^3, y-x^2, y^3- z^2)$ as the defining ideal of the twisted cubic curve, the quotient by this ideal is still $\cong k[t]$.
Comment: I see... So in general, can we say that: If $I\subset J$ are ideals of a (let's just say) commutative ring $R$, then $R/I \cong R/J$ implies $I =J$ ?
Comment: @cat Yes. For a fixed ideal $I$ there is a one-to-one correspondence between ideals $J \supseteq I$ and ideals $J' \subseteq R/I$. This is often one of the first theorems proven after introducing quotient rings in any textbook.
Comment: Why did you choose the polynomials $z-x^3$ and $y-x^2$? Why not $xy-z$ and $xz-y^2$?
Comment: @user46372819 It was almost five years ago. I honestly can't tell you why I made one choice over another back then. I don't think anyone could. But looking back at it, $z-x^3$ and $y-x^2$ look a lot prettier to me. They have more separation between the variables and seem to give quotients that are easier to work with. Also, it might be just because it's late and I'm tired, but it's not immediately obvious to me that $(z-x^3, y-x^2)\subseteq (xy-z, xz - y^2)$.
Comment: (OK, after actually picking up a pen and a piece of paper and scribbling for a minute, I see now that the two ideals probably are equal. I don't trust myself this late, though.)


Difference between a SVM and a perceptron

Question: I am a bit confused with the difference between an SVM and a perceptron. Let me try to summarize my understanding here, and please feel free to correct where I am wrong and fill in what I have missed.

The Perceptron does not try to optimize the separation "distance". As long as it finds a hyperplane that separates the two sets, it is good. SVM on the other hand tries to maximize the "support vector", i.e., the distance between two closest opposite sample points.
The SVM typically tries to use a "kernel function" to project the sample points to high dimension space to make them linearly separable, while the perceptron assumes the sample points are linearly separable.
Comment: Possible duplicate of [Comparing SVM and logistic regression](https://stats.stackexchange.com/questions/95340/comparing-svm-and-logistic-regression)
Answer: It sounds right to me. People sometimes also use the word "Perceptron" to refer to the training algorithm together with the classifier. For example, someone explained this to me in the answer to this question. Also, there is nothing to stop you from using a kernel with the perceptron, and this is often a better classifier. See here for some slides (pdf) on how to implement the kernel perceptron.
The major practical difference between a (kernel) perceptron and SVM is that perceptrons can be trained online (i.e. their weights can be updated as new examples arrive one at a time) whereas SVMs cannot be. See this question for information on whether SVMs can be trained online. So, even though a SVM is usually a better classifier, perceptrons can still be useful because they are cheap and easy to re-train in a situation in which fresh training data is constantly arriving.
Comment: SVMs can be trained online. From a dual solution you can obtain the corresponding primal and from this one you update weights in stochastic fashion.
Comment: http://www.jmlr.org/papers/volume6/bordes05a/bordes05a.pdf
Comment: Wait, what's the difference between a *kernel* perceptron and a SVM? You say "sounds right" but if we're talking about kernel perceptrons it's only 1/2 right - since kernel perceptron use a kernel just like SVM. So your saying the only difference is point #1 from the OP and online training?
Answer: SVM:
$$\min \|w\|_2 + C\sum_{i = 1}^{n}(1 - y_i(wx_i + w_0))_+ $$
Perceptron
$$\min \sum_{i = 1}^{n}(- y_i(wx_i + w_0))_+ $$
We can see that SVM has almost the same goal as L2-regularized perceptron.
Since the objective is different, we also have different optimization schemes for these two algorithms, from the $\|w\|_2$, we see that it is the key reason for using quadratic programming for optimizing SVM.
Why does perceptron allow online update? If you see the gradient descent update rule for the hinge loss (hinge loss is used by both SVM and perceptron),
$$w^t = w^{t-1} + \eta\frac{1}{N}\sum_{i = 1}^{N}y^ix^i\mathbb{I}(y^iw^tx^i \leq 0)$$
Since all machine learning algorithms can be seen as the combination of loss function and optimization algorithm.
Perceptron is no more than hinge loss (loss function) + stochastic gradient descent (optimization)
$$w^t = w^{t-1} + y^{y+1}x^{t+1}\mathbb{I}(y^{t+1}w^{t}x^{t+1} \leq 0)$$
And SVM can be seen as hinge loss + l2 regularization (loss + regularization) + quadratic programming or other fancier optimization algorithms like SMO (optimization).
Comment: Can one easily modify the Single Layer Perceptron algorithm to maximize the margin?
Answer: Perceptron is the generalization of SVM where SVM is the perceptron with optimal stability. So you are correct when you say perceptron does not try to optimize the separation distance.


iOS - Do I need to re-submit in-app purchases after rejecting binary

Question: Yesterday I set up 2 in-app purchases then uploaded the binary to go with them. Today I rejected the binary and immediately submitted another. Yesterday's in-app purchases are still showing as waiting for review.
I guess this means I don't need to redo and re-submit them as well?
Answer: If I understand correctly, you'll only need to resubmit in-app-purchases if they are moved to the "Developer Action Required" state. So as it stands right now, you should be fine.
Apple Support would be able to provide a much better answer though (anyone here would only be able to give you responses based on research and past experiences, which often are different from the present); you may want to shoot them an email.
Answer: "waiting for review" means they haven't even touched your binary yet. You're good.


A question about the span of functions.

Question: I am having trouble understanding the span of functions, my problem is:
What is $\operatorname{span}\{a\sin(x),b\}$, and what is its dimension?
I understand this in terms of vectors, but not in terms of functions, so any enlightenment would be very much appreciated.
Answer: Enlightenment: Functions are vectors.
Assuming you mean $a$ and $b$ are fixed constants in your base field $F$ (probably $\mathbb{R}$ or $\mathbb{C}$), then
$$
    \text{Span}_F\{a\sin x,b\} = \{f_1 a\sin x + f_2 b : f_1,f_2 \in F\}.
$$
When viewing $v = a \sin x$ and $w = b$ as vectors, the equation
$$
    f_1 a\sin x + f_2 b = f_1 v + f_2 w = 0
$$
means that for all values of $x \in F$ (or whatever the domain of $\sin x$ is assumed to be)
$$
    f_1 a\sin x + f_2 b = 0.
$$
Are there any constants $f_1$ and $f_2$ that make this true? If not, then the span has dimension $2$. If so, its dimension is less than two, since this says $v$ and $w$ are linearly dependent.
Comment: To make it true you would need $f_1,f_2\ne 0$ s.t $f_1a\sin(x)+f_2b=0,\,\forall x\in[0,1]$? (my function domian is $[0,1]$), in which case this is not true so I would believe the dimension is 2 correct?
Comment: That's correct! The dimension is in fact $2$, and for precisely the reason you mention.

A question about the span of functions.


Expected number of blue balls till end of process when sampling with replacement

Question: An urn has balls of 3 colors: Red, Blue, Yellow. There are an equal number of balls of each color. You start drawing balls from the urn with replacement, stopping when you draw a red ball. What is the expected number of blue balls drawn when the process stops?
I know that the expected number of non-red balls drawn in this case will be 1/p where p is the probability of success i.e. probability of drawing a red ball which is 1/3 in this case, so the expected number of non-red balls is 3. But is it correct to say that the expected number of blue balls in this case is 1/2 of 3 i.e. 1.5 since the non-red balls are equally likely to be blue or yellow?
Comment: Note:  your informal argument actually gives the right answer, if you are careful.  You expect to get the first $R$ on trial $\frac 1p=3$.  That means you expect $2$ non-red balls before the first red one, and as you say that means you expect $1$ blue one.  Two alternate arguments posted below.
Comment: Makes sense, thanks!
Answer: Let $E$ be the answer.  We consider what happens when you draw one ball...of course you get $R,B,Y$ each with probability $\frac 13$ so:  $$E=\frac 13\times \left(0+(E+1)+E\right)\implies 3E=2E+1\implies E=1$$
As an alternative way to see it:  the yellow balls are irrelevant, so ignore them completely.  The relevant strings are all of the form $B^nR$, which has probability $\frac 1{2^{n+1}}$so $$E=\sum_{n=0}^{\infty} \frac n{2^{n+1}}=1$$


Unable to change theme that applies to view

Question: In a drupal page view under advanced=>Theme:Information=>Change Theme, I'm able to select a theme from the dropdown. Custom templates I've created go bold as expected. But when I save the view and check the theme information, it always reverts to the site default theme. I've tried this with a custom theme I created and a view themes that came with my installation.
Comment: Is your custom theme set as default theme under yoursite/admin/appearance/settings?
Comment: No, the custom theme was created specifically with this view in mind.
Comment: The theme selector under the advanced view section is not for selecting a theme that should be displayed, it's only for informational purposes afaik.
Comment: I see. Any idea how to override the default theme just for that page?
Comment: I recommend this little tutorial for a start: https://www.ostraining.com/blog/drupal/views-templates/
Answer: To use a different theme for a specific page, try the ThemeKey module. It allows you to define rules for automatically selecting a theme. You can create a rule to switch theme for a particular path, which is probably the one you want. Another useful one is to select the theme based on the user's role. For example you can test theme modifications on a production site by showing one theme for anonymous users and your work-in-progress theme for the administrator role


How to use Oracle query hint in Hibernate

Question: I am trying to use Oracle hint in Hibernate to call force index, but didn't find any proper API in Hibernate 3.6.10.Final.
I somehow tried with projections in Hibernate criteria:
proList.add(Projections.sqlProjection("/*+ INDEX_DESC(CONTACT_USER_FK_I) */", new String[]{}, new Type[]{}));
                proList.add(Projections.property("objectId"));
                criteria.setProjection(proList);
                return criteria.list();

But I am getting the exception below:
    EXCEPTION
Caused by: 8 SQL Error  (could not execute query; SQL [select /*+ INDEX_DESC(CONTACT_USER_FK_I) */, this_.CONTACT_ID as y0_ from R4GDEV01_MBW.CONTACT this_ w
here this_.USER_ID=? and this_.ADDRESS_BOOK_ID in (?) and this_.DELETION_DATE is null order by lower(this_.FIRSTNAME) asc]; nested exception is org.hibernate
.exception.SQLGrammarException: could not execute query)
        at com.fusionone.pml.dao.hibernate.AbstractDao.executeCallback(AbstractDao.java:391)
        at com.fusionone.pml.dao.hibernate.AbstractContactDao.searchContacts(AbstractContactDao.java:1019)
        at com.fusionone.nab.core.service.impl.MergeServiceImpl.getFilteredContactIds(MergeServiceImpl.java:154)
        ... 91 more

I found out that the projection is appending a , after query hint.
Is there any other way to use Oracle query hint in Hibernate 3.6.10 criteria or in HQL?
Thanks
Comment: Is there any other way to use Oracle hint instead of hard coding the Index in the code, some thing like can we implement it from hibernate property file.
Answer: You should try to search first. Here is a simple trick to solve this, just transform the hint into a column:
"/*+ INDEX_DESC(CONTACT_USER_FK_I) */ 1 as MYHINT"

Comment: Thanks a lot for quick response, this solved the problem.
Answer: Your problem is that there is nothing previous to ,. Due to you want to add a projection on objectIdattribute, you could transform your criteria to somenthing like this:
Projections.sqlProjection("/*+ INDEX_DESC(CONTACT_USER_FK_I) */ objectId", new String[]{}, new Type[]{}))

Comment: Thanks i got the issue, is there any other way to use Oracle hint instead of hard coding the Index in the code, some thing like can we implement it from hibernate property file


In a multi-node Docker build, where is the layer cache stored? And when does cache garbage collection occur?

Question: I am building a Docker image with Buildkit on a remote arm64 platform. To achieve this, I setup the buildx builder as follows:
$ docker buildx install
$ docker buildx create --name=multiarch --driver=docker-container
$ docker buildx create --name=multiarch --append --node=arm-docker --platform=linux/arm64 ssh://firstname.lastname@example.com
$ docker buildx use multiarch

This setup step is working fine. I can then build the linux/arm64 image as follows:
# build 1: first remote build triggered from the local host
$ docker buildx build --platform=linux/arm64 /path/to/mydockerfile/

This results in the following build logs:
WARNING: No output specified with docker-container driver. Build result will only remain in the build cache. To push result image into registry use --push or to load image into docker use --load
[+] Building 188.5s (22/22) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.1s
 => => transferring dockerfile: 15.55kB                                                                                0.1s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:16.14-bullseye-slim                                                                                0.4s
 => CACHED [base 1/4] FROM docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                         0.0s
 => => resolve docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                     0.0s
 => [internal] load build context                                                                                0.1s
 => => transferring context: 64B                                                                                0.0s
 => [base 2/4] RUN apt update   && apt install -y git     gcc libgl1 libxi6 make     autoconf libtool pkg-config zlib1g-dev     python g++                                                           54.0s
...

My expectation is that subsequent builds will use the Docker layer cache. This is the case if I run the same command immediately: (notice the CACHED statements)
# build 2: second remote build triggered from the local host
$ docker buildx build --platform=linux/arm64 /path/to/mydockerfile/
WARNING: No output specified with docker-container driver. Build result will only remain in the build cache. To push result image into registry use --push or to load image into docker use --load
[+] Building 0.7s (22/22) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.1s
 => => transferring dockerfile: 15.55kB                                                                                0.1s
 => [internal] load .dockerignore                                                                                0.1s
 => => transferring context: 2B                                                                                0.1s
 => [internal] load metadata for docker.io/library/node:16.14-bullseye-slim                                                                                0.3s
 => [base 1/4] FROM docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                0.0s
 => => resolve docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                     0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 64B                                                                                0.0s
 => CACHED [base 2/4] RUN apt update   && apt install -y git     gcc libgl1 libxi6 make     autoconf libtool pkg-config zlib1g-dev     python g++                                                     0.0s
 => CACHED [base 3/4] RUN mkdir -p /openedx/app /openedx/env                                                                                0.0s
...

But then, if I wait a few minutes and run the same command again, the layers are no longer cached:
# build 3: third remote build triggered from the local host
$ docker buildx build --platform=linux/arm64 /path/to/mydockerfile/
WARNING: No output specified with docker-container driver. Build result will only remain in the build cache. To push result image into registry use --push or to load image into docker use --load
[+] Building 84.0s (20/23)
 => [internal] load .dockerignore                                                                                0.1s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load build definition from Dockerfile                                                                                0.1s
 => => transferring dockerfile: 15.55kB                                                                                0.1s
 => [internal] load metadata for docker.io/library/node:16.14-bullseye-slim                                                                                0.7s
 => [auth] library/node:pull token for registry-1.docker.io                                                                                0.0s
 => [base 1/4] FROM docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                2.8s
 => => resolve docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                     0.0s
 => => sha256:f819730668ed6ce893055fe48519a7562f409787a8c6484124a4ac81dd3ee2f3 452B / 452B                                                                                0.1s
 => => sha256:b8fb756f2ecf8b649e48f14874a4fb7cb1f399655453fe64b7fda7aa3d1086b8 2.76MB / 2.76MB                                                                                0.2s
 => => sha256:73d6fb98900661e1457a72cec5591ccec70d16856c7d0fdfca36a8cdc14ac2fe 34.49MB / 34.49MB                                                                                0.6s
 => => sha256:5dcf03983304e3396f5948d3c624e30b772d1ff3509c706caed83ef28438f1da 4.04kB / 4.04kB                                                                                0.3s
 => => sha256:6d4a449ac69c579312443ded09f57c4894e7adb42f7406abd364f95982fafc59 30.07MB / 30.07MB                                                                                0.6s
 => => extracting sha256:6d4a449ac69c579312443ded09f57c4894e7adb42f7406abd364f95982fafc59                                                                                0.8s
 => => extracting sha256:5dcf03983304e3396f5948d3c624e30b772d1ff3509c706caed83ef28438f1da                                                                                0.0s
 => => extracting sha256:73d6fb98900661e1457a72cec5591ccec70d16856c7d0fdfca36a8cdc14ac2fe                                                                                1.0s
 => => extracting sha256:b8fb756f2ecf8b649e48f14874a4fb7cb1f399655453fe64b7fda7aa3d1086b8                                                                                0.1s
 => => extracting sha256:f819730668ed6ce893055fe48519a7562f409787a8c6484124a4ac81dd3ee2f3                                                                                0.0s
 => [internal] load build context                                                                                0.1s
 => => transferring context: 1.56kB                                                                                0.1s
 => [base 2/4] RUN apt update   && apt install -y git     gcc libgl1 libxi6 make     autoconf libtool pkg-config zlib1g-dev     python g++                                                           48.6s
...

I'm guessing this means that the layer cache garbage collection was somehow run between the second and the third runs.
But if I ssh to the remote arm node and build the image from there multiple times (using the default buildx builder, not the multiarch one), I can see that the layers are properly cached, and for a long time:
# build 4: after a few builds triggered directly on the arm64 host
$ docker buildx build --platform=linux/arm64 /path/to/mydockerfile/
[+] Building 0.5s (23/23) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 15.55kB                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:16.14-bullseye-slim                                                                                0.4s
 => [base 1/4] FROM docker.io/library/node:16.14-bullseye-slim@sha256:d54981fe891c9e3442ea05cb668bc8a2a3ee38609ecce52c7b5a609fadc6f64b                                                                0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 64B                                                                                0.0s
 => CACHED [base 2/4] RUN apt update   && apt install -y git     gcc libgl1 libxi6 make     autoconf libtool pkg-config zlib1g-dev     python g++
...

The difference between the two environment seems to imply that the layer cache is stored on the nodes where the buildx command is run, not on the arm64 remote host. This is confirmed by pruning the build cache with:
docker buildx prune

This frees up some space on the local instance, thus confirming that the cache would be stored on the local instance.
My hypothesis is that the layers are removed from cache by some garbage collector. Indeed, checking the Docker docs, it appears that there is a default layer cache garbage collection configuration file somewhere: https://docs.docker.com/build/cache/garbage-collection/
The /etc/buildkit/buildkitd.toml file does not exist on my system (Ubuntu 22.04). But I can create it and disable garbage collection from there:
[worker.oci]
  gc = false

The problem is that I cannot test this configuration, because after I ran the docker buildx prune command above, I am no longer facing the initial issue...
This was rather a lengthy brain dump, sorry about that :-/ I have the following questions:

Am I right that the Buildkit layer cache is stored on the local host, and not on the remote?
In which folder is the buildkit cache stored?
Is there any way to view the activity of the cache garbage collector? for instance via some logs?
How should I configure the buildkit cache garbage collector to extend cache duration?
Answer: I've had to search long and hard to answer these questions, so I'll post the answers just as much for myself as for the rest of the world.

Am I right that the Buildkit layer cache is stored on the local host, and not on the remote?

No, this is incorrect. The BuildKit cache is stored on the remote host where the BuildKit container is running.
On the remote host, the container that runs BuildKit is called "buildx_buildkit_arm-docker" -- provided the builder was created using the command from the original question. The cache is stored is stored in a volume that is attached to this container.

In which folder is the buildkit cache stored?

The volume attached to the BuildKit container can be found by running docker inspect buildx_buildkit_arm-docker. In my case, on the host, this volume is stored in /var/lib/docker/volumes/buildx_buildkit_arm-docker_state. The amount of data that it uses can be monitored by running du -sm /var/lib/docker/volumes/buildx_buildkit_arm-docker_state/. Or: docker system df (see the "Volumes" lines).

Is there any way to view the activity of the cache garbage collector? for instance via some logs?

The builder needs to be configured with debug = true (see below on how to configure the builder). Then, garbage collection event are logged to stdout by the BuildKit container. Thus, on the remote host:
$ docker logs buildx_buildkit_arm-docker 2>&1 | grep garbage
...
time="2023-06-15T18:49:12Z" level=debug msg="content garbage collected" d=7.403837ms
...

How should I configure the buildkit cache garbage collector to extend cache duration?

The builder is configured whenever it is created for the first time, and only then. For instance, if you create a builder on two different hosts but configure the builder only the second time, then the configuration will be ignored, because the buildkit container is already running. The new configuration will only be taken into account once the container is stopped, removed, and restarted by a build (I think):
docker stop buildx_buildkit_arm-docker
docker container rm buildx_buildkit_arm-docker

To configure the builder, use the docker buildx create --config=./path/to/buildkitd.toml option. For instance, create buildkitd.toml on the local host:
# https://docs.docker.com/build/buildkit/toml-configuration/
# Enable debug logs
debug = true
[worker.oci]
  # Enable garbage collection
  gc = true
  # Not sure what this does. Keep data under 80GB?
  gckeepstorage = 80000000000
  # When storage exceeds 40GB delete data older than 4 days
  [[worker.oci.gcpolicy]]
    keepBytes = 40000000000
    keepDuration = 345600
  # Keep data under 80GB
  [[worker.oci.gcpolicy]]
    all = true
    keepBytes = 80000000000

Then, create the builder with:
docker buildx create --name=multiarch --driver=docker-container
docker buildx create --name=multiarch --config=./path/to/buildkitd.toml --append --node=arm-docker --platform=linux/arm64/v8 ssh://firstname.lastname@example.com
docker buildx use multiarch
docker buildx install

Once the BuildKit container has been created on the remote host (for instance after starting a build) you can verify that the configuration was properly loaded in the Buildkit container by running:
docker exec buildx_buildkit_arm-docker cat /etc/buildkit/buildkitd.toml

This should print a re-formatted version of your original configuration.


Our XServe FTP area is not allowing external access

Question: We are a graphic design agency and therefore we work pretty much solely on MacOSX. We have an XServe server and up until yesterday was fine. We have an FTP area where we can upload files to our clients and where the printers can download files from.
Everyone in the studio (who is connected up to the server) can access the FTP Area. Our project manager works on a Windows 7 Laptop and accesses the FTP area externally (in a similar way to our clients and printers). We all have an internet connection.
Our FTP area and the server itself suddenly cannot accept connections NOT on the LAN, so our project manager is out, and our clients accessing the FTP are out also. We've tried configuring it to different settings but cant seem to figure it out.
Can anyone offer a possible solution?
Cheers
Comment: Have you tried rebooting the firewall, router, and server?
Answer: What is the network layout? (ie. is there a firewall device? are you behind a nat?)
Also check what the rules are for the ftp access on the OS X server, you may have allowed access from LAN but not from outside of it.
You can print out the active rules with:
<code>ipfw list
</code>
on a terminal window
Once you have that figured out you'll know where the block is.
You can also run a tcptraceroute on port 21 (ftp) from outside and see where it dies.
Comment: how do I run a tcptraceroute?
Comment: I haven't tried it on windows. On linux it's a fairly standard command. On Mac (which is what you're using) you'll have to get it through darwinports (http://tcptraceroute.darwinports.com/)
It's a terminal program, the command would be
    tcptraceroute yourhost.com 21

Again, if the FTP server is on a NATed network, you will have to specify routes from outside your lan towards your ftp server.
It doesn't seem to be a Mac problem more than it is a network problem. Since anyone on LAN can access it, it's a matter of getting to it from the outside.


Como faz para capturar dois inteiros com espaço entre eles em python3?

Question: to querendo capturar dois inteiros, exemplo:

2 4

exatamente assim em python, mas ele por int(input()) normal n vai, eu tenho feito assim, mas deve ter outra forma:
var = input()
lista = []
lista = var.split(' ')
n,q = lista
n = int(n)
q = int(q)

Answer: A função input sempre retornará uma string, independente do conteúdo lido, então, se é necessário obter dois inteiros a partir de uma string, separados por uma vírgula, a lógica será basicamente a mesma que quando separados por um espaço em branco: só muda o caractere separador.
Por exemplo:
entrada = input('Entre com dois números separados por vírgula:')
x, y = (int(numero) for numero in entrada.split(','))
print(x, y)

Desta forma, inclusive, é possível entrar com entradas na forma "2, 3", com o espaço entre a vírgula e o número, pois, quando convertido para inteiro, o espaço será ignorado.
Answer: Com espaço, teria que ser algo assim... Mas se for por virgula, pode ser assim:
[a,b]=list(input("Insira dois numeros separados por virgulas: "))
print "Numero 1:", a
print "Numero 2:", b

No terminal:
Insira dois numeros separados por virgulas: 12,28
Numero 1: 12
Numero 2: 28

Comment: @PythonFocus: por favor, para melhorar a qualidade do site, evite marcar como "aceita" uma resposta que não funciona - mesmo que ela te inspire a aachar a resposta certa. Lembre-se de que outras pessoas estarão consultando essa resposta para referência - ao ver o "aceite" é assumido que está correto.
Comment: essa resposta sem o "split" está simplesmente errada.  Por que está com upvotes e aceita??
Comment: Descobri q assim tambem vai, quase a mesma coisa, mas fica mais compacto ^^
a,b = list(map(int,input().split(' ')))


How to use joins in Rails with squeel

Question: How to use joins or other ways to let me use the where query to compare other conditions in another model?
Model relation
class SonyAlarmLog < ActiveRecord::Base
  belongs_to :sony_alarm_test

class SonyAlarmTest < ActiveRecord::Base
  has_many :sony_alarm_bugs, :dependent => :destroy

It works, but returns me the columns of the SonyAlarmTest, I wanna the columns of sony_alarm_logs
SonyAlarmTest.joins{:sony_alarm_logs}
.where{ sony_alarm_logs.name =~ event_name }

It failed, get the ActiveRecord::ConfigurationError: Association named 'sony_alarm_tests' was not found on SonyAlarmLog; perhaps you misspelled it? Error
SonyAlarmLog.joins(:sony_alarm_tests)
.where{ name =~ event_name }

UPDATE (Fix: it should use the singular name)
But still got ActiveModel::MissingAttributeError: missing attribute: firmware_version error
I thought it may be mis-use of squeel syntax ?
SonyAlarmLog.joins(:sony_alarm_test)
.where{ name =~ event_name }
.where{ utc_time.gt (my{utc_time} + TIME_CORRECTION) }
.where{ sony_alarm_tests.round.eq(my{sony_alarm_test.round}) }
.where{ sony_alarm_tests.ip =~ my{sony_alarm_test.ip} }
.where{ sony_alarm_tests.firmware_version =~ my{sony_alarm_test.firmware_version} }

Comment: Try with singular `SonyAlarmLog`, because that is your model name, not the pluralized `SonyAlarmLogs`.
Comment: @vee sorry for the typos, I corrected it.
Comment: The `:sony_alarm_tests` in your `joins` also needs to be singular `:sony_alarm_test` which is the `belongs_to :sony_alarm_test` in your `SonyAlarmLog` model.
Comment: @vee Thanks for your help, do you know how to use the where clause with joins
Comment: Please see my answer below.  There needed to be a few changes in the syntax (basing this on the linked documentation of squeel).
Answer: Following up to the comments...  As per the documention of squeel, you could write your query as:
SonyAlarmLog.joins{:sony_alarm_test}.
  where{
    (name =~ event_name) &
    (utc_time.gt (my{utc_time} + TIME_CORRECTION)) &
    (sony_alarm_test.round.eq(my{sony_alarm_test.round})) &
    (sony_alarm_test.ip =~ my{sony_alarm_test.ip}) &
    (sony_alarm_test.firmware_version =~ my{sony_alarm_test.firmware_version})
  }

The reason you are getting the error is likely because of the either sony_alarm_tests.firmware_version or sony_alam_test.firmware_version.  Note one of them is plural and the other one is singular.  You want to be using "singular" version here as the association is "belongs_to".

How to use joins in Rails with squeel


Recommended procedure for factor analysis on dichotomous data with R

Question: I have to run a factor analysis on a dataset made up of dichotomous variables (0=yes, 1= no) and I don´t know if I'm on the right track.
Using tetrachoric() I create a correlation matrix, on which I run fa(data,factors=1).
The result is quite near to the results i receive when using MixFactor, but it´s not the same.

Is this ok or would you recommend another procedure?
Why does fa() work and factanal() produce an error? (Fehler in solve.default(cv) :
System ist für den Rechner singulär: reziproke Konditionszahl = 4.22612e-18)
Comment: I don't speak (German?) but the error looks like it's due to the tetrachoric matrix being singular (non-invertible). Even with a good sized sample some estimates of polychoric correlation matrices can fail to be proper correlation matrices. My hunch is that fa() is using principal components and factanal() is doing maxmimum likelihood FA, but that's not obvious to me from the documentation for fa().
Comment: @cada why are you running the factor analysis? If you are aiming to estimate participant ability, IRT may be a better approach. on the matter of fa versus factanal, fa uses minimum residual by default, while factanal uses an ML method.
Comment: @cada A CFA with 45 subjects would be surrealist :-) I'll try to add my thoughts later.
Comment: @cada How many items/subjects do you have? And what method is implemented in MixFactor?
Comment: @chl: way too few! I just started the survey and by now there are just 45 subjects. I cant collect new data in teh moment and that´s why I try to do as much of the r code as possible...
Comment: @cada If you have more items than subjects, then you cannot use ML-based FA. Even if this is not the case, you might have a ratio of subjects/items in the order of 10 at least to get meaningful results with ML. This also depends on the number of dimensions present in the data. Forget about IRT models with 45 subjects, unless you're willing to use MCMC.
Comment: @chl: ok, that means with my 22 Items-Test I should go for at least 220 subjects, right? (i talked about this problem with my supervisor before, but he said it would be ok.... i don´t think i´m going to have more than 100 subjects).
Comment: MixFactor uses "mixed Intercorrelationmatrices" (don´t know if i translated it right) depending on the single variables. In the case of dichotomous variables it calculates also tetrachoric correlations. What happens afterwards isn´t said in the documenation...
Comment: @cada Any reason to hypothesize that your scale is strictly unidimensional (I see that you ask for 1 factor only)?
Comment: @chl: yes, it´s a validation of a questionnaire which showed an unidimensional structure in the studies before. I think i could also try a confirmatory FA, but i´ve never done this before and i definately have to check this out in more detail first.
Comment: See also http://stats.stackexchange.com/q/215404/3277
Answer: To sum up, with n=45 subjects you're left with correlation-based and multivariate descriptive approaches. However, since this questionnaire is supposed to be unidimensional, this always is a good start.
What I would do:

Compute pairwise correlations for your 22 items; report the range and the median -- this will give an indication of the relative consistency of observed items responses (correlations above 0.3 are generally thought of as indicative of good convergent validity, but of course the precision of this estimate depends on the sample size); an alternative way to study the internal consistency of the questionnaire would be to compute Cronbach's alpha, although with n=45 the associated confidence interval (use bootstrap for that) will be relatively large.
Compute point-biserial correlation between items and the summated scale score; it will give you an idea of the discriminative power of each item (like loadings in FA), where values above 0.3 are indicative of a satisfactory relationship between each item and their corresponding scale.
Use a PCA to summarize the correlation matrix (it yields an equivalent interpretation to what would be obtained from a multiple correspondence analysis in case of dichotomously scored items). If your instrument behaves as a unidimensional scale for your sample, you should observe a dominant axis of variation (as reflected by the first eigenvalue).

Should you want to use R, you will find useful function in the ltm and psych package; browse the CRAN Psychometrics Task View for more packages. In case you get 100 subjects, you can try some CFA or SEM analysis with bootstrap confidence interval. (Bear in mind that loadings should be very large to consider there's a significant correlation between any item and its factor, since it should be at least two times the standard error of a reliable correlation coefficient, $2(1-r^2)/\sqrt{n}$.)
Comment: Thank you very much! Your answer is so detailed and really really helpful! Thank you!
Answer: This thread has a good Google position for the "System ist für den Rechner singulär: reziproke Konditionszahl" error using factanal (in English: "system is computationally singular: reciprocal condition number") - therefore I shall add a comment:
When the correlation matrix is calculated a priori (e.g., to pairwisely delete missing values), make sure that factanal() does not think that the matrix is the data to analze (https://stat.ethz.ch/pipermail/r-help/2007-October/142567.html).
PREVIOUS: matrix = cor(data, use="pairwise.complete.obs")  # For example
WRONG: factanal(matrix, 3, rotation="varimax")
RIGHT: factanal(covmat=matrix, factors=3, rotation="varimax")

BurninLeo


How to iterate through selected HTML table rows and retrieve data from each row

Question: I am displaying a list of data selected from an Oracle database on a jsp using Spring MVC.
The code for displaying the data in a table is as follows (using datatables plugin):
$("#addLocationsTable").DataTable({
  "bProcessing" : false, "bServerSide" : false, "responsive" : true, "sort" : "position", "oLanguage" :
  {
    "sEmptyTable" : "There were no matches found for the search. Try again with different criteria. "
  },
  "sAjaxSource" : "addLocations.htm",
  "responsive": "true",
  "order": [[0, "asc"]],
  aLengthMenu: [
    [25, 50, 100, 200, -1],
    [25, 50, 100, 200, "All"]
  ],
  iDisplayLength: -1,
  "scrollY":        "200px",
  "scrollCollapse": true,
  "paging":         false,

  "sAjaxDataProp" : "locationData", "bDestroy" : true,
  "aoColumns" :
    [
      {"mData" : "id"},
      {"mData" : "id"}
    ],
  'columnDefs' : [{
    'targets' : 0,
    'searchable':false,
    'orderable':false,
    'className': 'dt-body-center',
    'render': function (data, type, full, meta){
      return '<input type="checkbox" name="selectedID" value="' + $('
').text(data).html() + '">';
    }
  }]
});

This works to assign a checkbox to each row, and assigns the checkbox with the value of the id.  In my controller, I am able to test with the following code, which returns the value of the first selected checkbox:
@RequestMapping(params="saveLocations", method = RequestMethod.POST)
public String saveLocations(HttpServletRequest req){
    System.out.println(req.getParameter("selectedID"));
    return "redirect:/locations.htm";
}

On the jsp, this submit is handled using a basic submit button:
<button type="submit" class="btn btn-primary" id="saveLocations" name="saveLocations">Save</button>

What I am trying to do is retrieve each selected row in the table.  I know that I have to loop through the values somehow, but I'm not really sure how to do that.
ANSWER:  When returning multiple values, you need to use getParameterValues().  So the new controller looks like this:
    String[] values = req.getParameterValues("selectedID");
    for(int i=0;i<values.length;i++)
    {
    System.out.println(values[i]);
    }

Answer: SOLUTION
You can use the snippet below, where frm-example is ID of your form.
It will iterate over all checkboxes in the table and add those not present in DOM as <input type="hidden"> elements.
// Handle form submission event
$('#frm-example').on('submit', function(e){
   var form = this;

   // Iterate over all checkboxes in the table
   table.$('input[type="checkbox"]').each(function(){
      // If checkbox doesn't exist in DOM
      if(!$.contains(document, this)){
         // If checkbox is checked
         if(this.checked){
            // Create a hidden element
            $(form).append(
               $('<input>')
                  .attr('type', 'hidden')
                  .attr('name', this.name)
                  .val(this.value)
            );
         }
      }
   });
});

I'm not Java expert but it looks like you need to use getParameterValues() on the server-side instead of getParameter(). According to the manual getParameter() should be used when there is only one value.
DEMO
See jQuery DataTables: How to submit all pages form data for more details and demonstration.
Comment: I actually saw this on your site prior to posting my original question.  I attempted to use it, but my controller still just returns the first value.
Comment: @QuestionMarks, I'm not Java expert but it looks like you need to use `getParameterValues` instead of `getParameter`, according to the [manual](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29) [`getParameter`](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29) should be used when there is only one value.
Comment: BOOM!!  You got it, thanks!  I just had to make a String array of the results, add a "for" loop, and print each result.  Perfect, thank you!
Comment: I added my new controller to my original post using getParameterValues, if you'd like to add that to your answer as well.
Comment: Actually, the javascript piece isn't even necessary when using getParameterValues.


Interaction terms

Question: Suppose you have variables $X_{1}, \dots, X_{100}$ (can be discrete or continuous). If you want to test all possible interactions, should you include them all in 1 model? We are doing linear regression here.
Answer: No.  That would be about $10^{30}$ interactions, which is probably too many variables for the data you have available.
Comment: First, resolve whether you mean *all* possible interactions (which is how @PeterEllis interpreted your question) or just all possible *two-way* interactions (which is how @macro) interpreted it.
But I'd be cautious about a model with 100 variables, much less interactions among them. It's hard to conceive how such a model could be interpreted. What's the context?
Comment: *I* would hope to have some theoretical basis for choosing a subset of variables to look at.  If you want the data to dictate your choice you are in the world of data mining (I've added the data-mining tag) and should look up some of the methods there.
Comment: Where do you get $10^{30}$? Aren't there only $\binom{100}{2} = 4950$ possible pairwise interactions?
Comment: The question was all possible interactions:  x <- 0; for (i in 2:100){x <- x + choose(100,i)}; x
Comment: So how would you choose which variables to test for interaction?
Comment: You're right @PeterEllis. I guess I assumed he couldn't possibly be talking about _all possible_ interactions, since those would be a nightmare to interpret.
Comment: @PeterEllis - I didn't understand your notation, but using XL I got 1.369*10^30:  does that match your result?  Checking whether my method works.
Comment: I found interesting the related discussion at http://stats.stackexchange.com/questions/16480/how-to-quickly-select-important-variables-from-a-very-large-dataset
Comment: @rolando2, sorry about my notation, it should work if it's pasted as a single line into R.  I don't have the knack yet of the markup language for "comments".  I get 1.268*10^30.
Comment: @whuber I'm sure there are cases where this is sensible - but I just said be cautious. Yes, the interpretation is the same, mathematically, we're just controlling for more variables. But, substantively, I think there are few situations where controlling for 100 variables is going to be easy to interpret.
Comment: @Peter I have created regression models with 200+ variables using (many) two-way interactions.  The objective was *prediction* rather than interpretability, but interpretation was no problem: it's the same whether there are three variables or millions of them.  The challenge is to find which of the tens of thousands of interactions are useful.
Answer: Quoting the wise Andrew Gelman and Jennifer Hill (see p. 36) on hunting interactions:

In practice, inputs that have large main effects also tend to have large interactions with other inputs (however, small main effects do not preclude the possibility of large interactions). For example, smoking has a huge effect on cancer. In epidemiologial studies of other carcinogens, it is crucial to adjust for smoking both as a main effect and as an interaction[...]: high levels of radon are associated with greater likelihood of cancer but this difference is much greater for smokers than for nonsmokers.

Interaction terms


Do there exists permutations $\pi_1,\pi_2$ and polynomial size CFG that describe the finite language $\{w \pi_1(w) \pi_2(w)\}$ over alphabet {0,1}?

Question: Do there exists permutations $\pi_1,\pi_2$ and polynomial size CFG that describe the finite language {$w \pi_1(w) \pi_2(w)$} over alphabet {0,1}?
Polynomial size in $|w|=n$
Comment: You mean a polysize CFG for $L_n = \{w\pi_1(w)\pi_2(w) : w \in \{0,1\}^n\}$?
Comment: Also asked on cstheory.
Comment: You really need a sequence of permutations $\pi_1^n,\pi_2^n$, one of each possible size.
Comment: The only way to describe such a language with a CFG is by enumerating its words, there is really nothing good you can do.
Comment: @Chandok: That requires proof. If $w$ appeared only twice, then there is a choice of $\pi$ that results in poly-size grammars, namely the reversing permutation, which requires only a linear size grammar.
Comment: Link in cstheory: http://cstheory.stackexchange.com/questions/4962/do-there-exists-polynomial-size-cfg-that-describe-this-finite-language.
Answer: Without loss of generality, we can assume that a grammar for $L_n$ (such a language with specific $\pi_1,\pi_2 \in S_n$) is in Chomsky Normal Form. The language $L_n$ consists of the words $w(x) = x\pi_1(x)\pi_2(x)$ for all $x \in \{0,1\}^n$.
Using the Subword Lemma (see my previous answers), for each $w(x)$ we can find a substring $s(x)$ of length $$\frac{n}{2} \leq |s(x)| < n$$ generated by some symbol $A(x)$ and occurring at position $p(x)$.
Suppose that $p(x) = p(y)$ and $A(x) = A(y)$. Since $|s(x)|<n$, the subword $s(x)$ cannot intersect both the $x$ part and the $\pi_2(x)$ part of $w(x)$; we can assume it is disjoint from the $x$ part. Thus $w(x)$ is of the form $x \alpha s(x) \beta$. This implies that $A(x)$ generates exactly one string, namely $s(x)$. Therefore $s(x) = s(y)$.
Now $s(y)$ intersects either $\pi_1(y)$ or $\pi_2(y)$ in at least $n/4$ places, and thus determines at least $n/4$ bits of $y$. Therefore at most $2^{3n/4}$ strings $y \in \{0,1\}^n$ can have $p(x) = p(y)$ and $A(x) = A(y)$. Since there are at most $3n$ possibilities for $p(y)$, we get that there are at least $$\frac{2^{n/4}}{3n}$$ different non-terminals in the grammar.
Comment: The same proof works if $\pi_1,\pi_2 \in S_{\{0,1\}^n}$, i.e. are arbitrary permutations on the set of all $n$-bit words. Given $n/4$ bits of $\pi_i(y)$, there are exactly $2^{3n/4}$ preimages $y$.
Comment: Also in cstheory (due to their request): http://cstheory.stackexchange.com/questions/4962/do-there-exists-polynomial-size-cfg-that-describe-this-finite-language/4969#4969.
Comment: On cstheory you mention some unrelated tractable exceptions. I suppose by the exception $N_{\geq 1}$ you mean "at least one occurrence of terminal". Would this mean you can generate all permutations by intersecting with $\Sigma^{|\Sigma|}$?
Comment: Since $\Sigma^{|\Sigma|}$ is regular, intersecting with it does not increase the descriptive power of the grammar. So the argument still shows that it's hard to generate all permutations.
Comment: Huh???? Can you generate "at least one occurrence of terminal" in (1) REGL or (2) CFL?
Comment: I mean generate poly-size (thought your exception was this).
Comment: If you want *each* terminal to appear, then the same exponential lower bound applies.


Rails `unitialized constant` for a constant defined in app/classes subdirectory in staging env

Question: the error happens in :staging environment only
config/initializers/activity_api.rb:4:in 'block in <top (required)>'
Rails.application.config.to_prepare do
  config = YAML.load_file('config/activity.yml')[Rails.env] || {}
  config.deep_symbolize_keys!
  Activity::API.config = config
end

And I have Activity::API class definition in app/classes/activity/api.rb
module Activity
  class API
  ...
  end
end

Shall I explicitely define a module Activity in app/classes/activity.rb and require files in app/classes/activity or there is something I misunderstand?
Maybe app/classes subdirectories are not in autoload path?
Answer: Creating an empty module Activity would help.
You can also try to user the inline class declaration style:
class Activity::Api
end

Comment: maybe the unicorn process hasn't restarted, and runs on the old code?
Comment: Yes, you're right. Finally I found that unicorn hadn't restarted and worked with the release directory that were deleted by Capistrano.


Product of stationary stochastic process

Question: Suppose $z_{t} = x_{t}y_{t}$ where $x_{t}$ and $y_{t}$ are 0 mean, independent stationary stochastic process. What is the autocovariance function of $z_{t}$? Show that the spectral density can be written as $f_{z}(\omega) = \int_{-0.5}^{0.5}f_{x}(\omega-v)f_{y}(v)dv$.
Attempt:
If the series are independent, wouldn't the autocovariance function be $E[z_{t}z_{t+h}]$? This would then be $E[x_{t}y_{t}x_{t+h}y_{t+h}]$. I am unsure how to proceed from here. I am unsure how to prove how the spectral density can be written as the above integral. I know the autocorrelation function $\gamma_{z}(h)$ can be written in terms of the integral but I did not know there was an integral representation for $f_{z}(\omega)$.
So how does one represent the spectral density of z. From my textbook, this is $\sum_{h=-\infty}^{h=\infty}\gamma_{z}(h)e^{-2\pi\omega h}$
Answer: For the first question and because $\left( x_t \right)_t$ and $\left( y_t \right)_t$ are independent with
zero expectations
\begin{eqnarray*}
  \gamma_z \left( h \right) & = & E \left[ z_t z_{t - h} \right]\\
  & = & E \left[ x_t y_t x_{t - h} y_{t - h} \right]\\
  & = & E \left[ x_t x_{t - h} \right] E \left[ y_t y_{t - h} \right]\\
  & = & \gamma_x \left( h \right) \gamma_y \left( h \right)
\end{eqnarray*}
Comment: How does one find the spectral decomposition?
Comment: @phil12 It is not a good idea to ask two questions in one post. Anyway as hint, write $f_z$ as a function of $\gamma_z$, replace $\gamma_z$ by the product found in the first question, apply the inverse transform to $\gamma_x$, interchange summation and integration (after justifying why you could do it), apply the inverse transform to $\gamma_y$ and you've got your answer.


Security group to allow connection from OpenVPN network

Question: I am making a openVPN server in my AWS VPC. I want to make a security group that only accept SSH connection from my VPN. I already using my VPC CIDR (10.0.0.0/8), OpenVPN public address, and OpenVPN CIDR(tun0 / 192.168.0.0/30) but not works.
Here is my ifconfig from my OpenVPN Server
<code>eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 10.0.0.116  netmask 255.255.255.0  broadcast 10.0.0.255
        inet6 fe80::8f4:d5ff:fe76:1230  prefixlen 64  scopeid 0x20<link>
        ether 0a:f4:d5:76:12:30  txqueuelen 1000  (Ethernet)
        RX packets 8783395  bytes 5626116552 (5.2 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6575989  bytes 5676746788 (5.2 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 64  bytes 5920 (5.7 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 64  bytes 5920 (5.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 192.168.0.1  netmask 255.255.255.255  destination 192.168.0.2
        inet6 fe80::a316:dc9b:98b8:526  prefixlen 64  scopeid 0x20<link>
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 100
</code>
Update:
After some trying and error, i found out that i can connect to my instance if the security group is using my ISP address but not my VPN address. Is the problem about NAT?
Comment: If adding your public IP address to the security group changes anything, then you are not actually using the VPN connection.  You need to be connecting to the instance using its private IP.
Comment: But when i am using whatismyip.com it showing my VPN public IP address
Answer: After some troubleshooting, i know i had a mistake in which ip address i should connect. The cause i cannot connect SSH port is i am using ip public to connect. It should be using ip private .


How to deploy iOS App to client App Store Connect with App Manager Role

Question: I've built a small App for a client who doesn't know anything about programming (installing Xcode is not an option) - this client has granted me with the App Manager Role on App Store Connect
But I can't seem to figure out how to Sign In my Xcode Build to that account which is now linked to my personal account
that team account does not display in Xcode (only my personal one) - I don't have the password to their App Store Account - how do I Sign the App In given that I have App Manager Role on their App Store Connect it should display ?
Comment: You accepted the customers invite? Does the team appear as an option at top right of App Store connect when you're logged in?
Comment: Yes I accepted customer invite & his name appears in the App Store connect
Comment: I'm not sure if it's an individual account though is it an issue if i'm part of the team ?
Comment: That's normal, you can be a member of multiple teams. Does the clients team appear in Xcode Prefs > Accounts ?
Comment: No it doesn't appear only my personal account : (
Comment: I accepted the request & have access to his account from my App Store Connect though does it not work because he took individual membership instead of company ?
Comment: It doesn't matter , an individual or company can invite devs to their team. Horrible solution but have you tried logging out / in Xcode prefs ?
Comment: I've just tried Sign out / in & still only my account shows up :/
Answer: You need to add the developer or distribution certificate in your mac keychain. Login in the provisioning/developer portal and create the certificates from there.
You can go through a good article on how to code sign IOS apps.


Permissions for adding bundles to custom entities

Question: I've made some custom entities using the Entity API and I would like to give some users the ability to add bundles to them.
However it seems that in order to add bundles they have to have the "Administer site configuration" permission. I am a bit concerned about giving users that, especially as we might be doing a multisite system where different organisations will own different sites. I'm worried that they might be able configure directories and file paths and end up getting access to things on the other sites.
There is a special permission for creating content types, so I wonder whether there could also be one for creating bundles of other kinds of entities. It seems an oversight that there is not.
Comment: Drupal isn't aware of your custom entities or bundles like that. But you can implement a permissions callback and create them dynamically per bundle, and then use them in access checks.
Comment: I wrote about this a little bit ago. This is for taxonomy terms, but you can use it as a guideline to implementing for your entity type: http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8
Comment: I've got halfway there. I used the drupal console entity generator to make the entities, and told it I wanted bundles. This tells it to generate files in src/Entity called FooType.php etc. In those files, there is an "admin_permission" setting that defaults to "administer site configuration". You can create a custom permission for each entity in .permissions.yml and use that instead. However, although this allows the user to create new bundles, it does not allow them to add any fields!
Answer: Writing in here, since its a faux paux to link to blog articles.
In your permissions.yml file of your module, you can define a permissions callback like so:
permission_callbacks:
  - Drupal\mymodule\MyModulePermissions::permissions

Then in your MyModulePermissions class:
namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModulePermissions implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructor for MyModulePermissions.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity_type.manager'));
  }

  /**
   * Get permissions for MyModule.
   *
   * @return array
   *   Permissions array.
   */
  public function permissions() {
    $permissions = [];

    foreach ($this->entityTypeManager->getStorage('myentity')->loadMultiple() as $type) {
      $permissions += [
        'create ... ' . $type->bundle() => [
          'title' => $this->t('Allow creation of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'update ... ' . $type->bundle() => [
          'title' => $this->t('Allow update of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'delete ... ' . $type->bundle() => [
          'title' => $this->t('Allow deletion of %type', array('%type' => $type->label())),
        ]
      ];
    }

    return $permissions;
  }
}

Something like that. Code is untested. This will loop through and create CRUD permissions for each bundle.
Comment: Thanks for the comprehensive reply but I don't think it answers my question. I asked how to allow users to create bundles. E.g. if the entity type is Person, I want users to have the permission to create types of Person like Volunteer, Client. To create the actual bundles themselves. Not how to grant CRUD permissions on entities of that type once the bundle exists already - which is what I think your code does


History of the baby grand piano

Question: The first pianos were made in around 1700. Researching a little online, I've been able to find lots of info on the history of the piano. But when was the "baby grand" piano first created and/or marketed for sale?
Comment: 9 months after mummy grand & daddy piano got married ;) [sorry, sometimes I just can't resist]
Comment: @tommsch, I don't mean to ask "when was a ~5-ft piano first created?" but rather: what was the rough date of creation of the first *product* that was called a 'baby grand' piano?
Comment: Pianos got bigger and bigger during history. Thus I think there is no date when the "baby grand" was created first. I think, most of the early pianos where "baby grands".
Answer: Maybe the German word for "Baby-Grand" helps you with your search: "Stutzflügel". If German Wikipedia is correct, then

Der erste Stutzflügel nach heutigem Größenverständnis als Neukonstruktion, d. h. ohne einen längeren Flügel zu stutzen, wurde von der Ernst Kaps Klavierfabrik AG im Jahr 1865 gebaut.

In English: "The first Baby-Grand (which was not made by cutting off a big grand) was built in 1865 by Ernst Kaps Klavierfabrik AG".
See also: https://en.wikipedia.org/wiki/Ernst_Kaps#Baby_grand

In 1865, Kaps built the first double overstrung grand piano. ... Previous attempts at producing a successful small grand piano failed until this time and subsequently, the Kaps Double overstrung 5 ft grand piano, quickly became a revelation. Hailed as the first successful small grand, later known and promoted by another maker as the "baby grand piano", launched Kaps pianos into commercial success.
Comment: Thanks! I searched the company name and found some useful information. If you edit in a link to [**this page**](https://en.wikipedia.org/wiki/Ernst_Kaps#Baby_grand), I'll accept this answer.
Answer: Then Sohmer must be the "other who promoted and manufactured"... I found this "In 1884, Sohmer created the first baby grand piano, the first smallest grand pianos ever manufactured at only five feet long. The company also patented the agraffe bars and actions in 1882, in 1887 an agraffe for a quadruple strung "reverbation scale" and a pianissimo pedal in uprights, and bridge agraffes in 1890."
Comment: This is good information. Could you edit in some supporting references or links?

History of the baby grand piano


Java thread/process with retry and failover

Question: I'm looking to implement a mechnism in Java in which I spawn a task.  What the task does is actually not relevant here and it can be done via a thread or new process.
What I really need is this:

The task can be set to retry N times
If something nasty happens within the tasks, the parent that spawned it is protected
Both of the above should be abstracted away from me

Does anyone know of any frameworks that would do that in Java?
Comment: Sounds like you are looking for a [Thread](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html). They do all that for you. Perhaps a [Timer](http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html).
Comment: I think Akka will solve this.  Happy to answer my own question if someone can confirm?
Answer: I've been thinking about this for quite a while now and finally got something you might consider useful.
First part of our little "framework" is the Task interface:
public interface Task {
    void work();
    void stop();
}

Implementing this we can set up our WorkTask:
public class WorkTask implements Task {
    @Override
    public void work() {
        // Do something useful...
        // might throw SomethingNastyHappenedException
    }

    @Override
    public void stop() {
        // implement as needed e.g. to break inner loops
    }

}

To comply with your requirement to be able to retry this we create a Wrapper class:
public class RetryingTaskWrapper implements Task {
    private Task wrappedTask;
    private int maxTries;
    private boolean running = false;

    public RetryingTaskWrapper(Task wrappedTask, int maxTries) {
        this.wrappedTask = wrappedTask;
        this.maxTries = maxTries;
    }

    @Override
    public void work() {
        running = true;
        boolean success = false;
        int tries = 0;

        while (running && !success && tries < maxTries) {
            try {
                wrappedTask.work();
                success = true;
            } catch (SomethingNastyHappenedException e) {
                // something nasty happed so retry
                tries++;
            } catch (Exception e) {
                // something even worse happened -> end
                running = false;
            }
        }

        running = false;
    }

    @Override
    public void stop() {
        running = false;
        wrappedTask.stop();
    }
}

Finally we need somthing to run our tasks...
public class TaskRunner implements Runnable {
    private Thread thread;
    private Task task;
    private boolean running = false;

    public TaskRunner(Task task) {
        this.task = task;
    }

    public synchronized void start() {
        if (thread != null) {
            return;
        }

        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        running = true;

        if (task != null) {
            try {
                task.work();
            } catch (Exception e) {
                // log your exception
            }
        }

        thread = null;
        running = false;
    }

    public void stop() {
        if (running) {
            if (task != null) {
                task.stop();
            }
            if (thread != null) {
                thread.interrupt();
            }
        }
    }
}

Now we have all we need to is to set up a TaskRunner and start it:
WorkTask workTask = new WorkTask();
TaskRunner runner = new TaskRunner(new RetryingTaskWrapper(workTask, 5));
runner.start();

If you want to run your WorkTask only once without retrying that is also possible:
WorkTask workTask = new WorkTask();
TaskRunner runner = new TaskRunner(workTask);
runner.start();

If you wanted to you could even run your WorkTask in an infinite loop without having to change your WorkTask itself. All you need is to create another Wrapper
public class InfiniteLoopTaskWrapper implements Task {
    private Task wrappedTask;
    private boolean running = false;

    public InfiniteLoopTaskWrapper(Task wrappedTask) {
        this.wrappedTask = wrappedTask;
    }

    @Override
    public void work() {
        running = true;

        while (running) {
            try {
                wrappedTask.work();
            } catch (SomethingNastyHappenedException e) {
                // log that something nasty happened
            } catch (Exception e) {
                // something even worse happened -> end
                running = false;
            }
        }
    }

    @Override
    public void stop() {
        running = false;
        wrappedTask.stop();
    }

}

and run it...
WorkTask workTask = new WorkTask();
TaskRunner runner = new TaskRunner(new InfiniteLoopTaskWrapper(workTask));
runner.start();

Answer:
If something nasty happens within the tasks, the parent that spawned it is protected

So I guess you have 3 options.

is to run the task in another process.  See something like Get Java Runtime Process running in background.  I don't know of a framework that would help with this.  There aren't too many lines of code this framework would be saving you.
Run in another thread on the same JVM.  See below.
Run in another process on another server.  You are going to have to write the client/server or use a web framework or RMI to do the remoting.  I don't know of any framework that will do this for you automatically.

In terms of running it in the same JVM, I'd not use a framework at all.  I'd just run the task in a loop with proper exception handling:
for (int i = 0; i < retries; i++) {
   try {
      doTask();
   } catch (Throwable t) {
      // log the throwable here
   }
}

Seems like a framework would just be too complicated.  If the task runs out of memory then running it in another thread would not help and you will have to spawn another process to handle the task.
If you needed it to run in the background then @assyliaas' initial answer about using thread-pool is the right way to go.
Comment: Indeed - I got carried away by the title!
Comment: That doesn't solve the issue around protection.  What is the Thread goes OOM?
Comment: Np dude.  You are spot on if he needs it to run in the background @assylias.
Comment: @imrichardcole You should amend your question to make your goal clearer and explain what solutions you have considered that don't work for you.
Comment: If the thread goes OOM, then the whole JVM is going to be affected @imrichardcole.  Putting it in another thread won't help.  If you need to spawn another process then I guess you could exec it.
Comment: I didn't commit to thread or process in my original question.  I was also clear about "If something nasty happens within the tasks, the parent that spawned it is protected"