Conjecture I came up with

Question: For each number translated into binary
$0$, $1$, $10$, $11$, $100$, $101$, $110$, $111$, $1000$, ...
find a number where, when you take the length of the binary number, the binary number and the number modulus the first of that many integers greater than $1$ are the same.

Example:
$n=23$.  In binary this is $10111$ which has length $=5$.
$23 \equiv 1\pmod{2}$
$23 \equiv 2\pmod{3}$
$23 \equiv 3\pmod{4}$
$23 \equiv 3\pmod{5}$
$23 \equiv 5\pmod{6}$
Taking these as digits, we get the number $12335$.  However, $10111\neq  12335$, so
$23$ does not fit.

I thought it would be a neat test. I'm not sure if there are any possible matches besides zero and one. How would I go about proving or disproving whether or not there are? There is no solution other than $0$ and $1$ up to $2$ billion.
Comment: You would need to phrase this question better. What do you mean by "are not the same"? In base 2 or base 10?
Comment: It'd be great if you could create a more informative title, too.
Comment: It's unusual for randomly formulated processes to interact with other processes. Without evidence to suggest an interaction in this case, I don't find this a significant question.
Comment: that's a rather strange question...
Answer: A non-trivial solution cannot exist. The question is equivalent to asking whether for some n-digit number $N$ written in base 2 (I'll enumerate the digits starting $a_1$ to $a_n$), $$a_j \equiv n (\mod 2+n-j),$$ for $j=1,2,...n$. This seems to be the only interpretation, because if the second number is taken to be in base $10$ the resulting number would have approximately $\lfloor\log_{10}2^{n}\rfloor \approx \lfloor0.3n\rfloor < n$, so there would trivially be no solutions.  Now since $N$ has n digits, $a_n=1$ (because we only have two choices and it can't be zero) and so $n \equiv 1 (\mod 2)$, or in other words n is odd.
Now by the Chinese Remainder Theorem, a system of congruences has a solution if and only if $$a_i \equiv a_j (\mod \gcd(i,j))$$ for all $i,j$, which implies that all the digits must equal $1$ (to see this, notice that because $n$ is odd, the odd-numbered digits must all be congruent to $a_n$ modulo $2$ and hence must also be $1$; similarly we must have $a_{n-1} \equiv a_{n-4} \equiv 1(\mod 3)$ so all $a_{3k} = 1$  etc. for all $a_{p\alpha}$ for primes $p \leq \sqrt{n}$. In particular, $a_2=1$, which is key) so we have a number of the form $N=111...1$. But this implies that $$a_2 \equiv 1 \equiv n \equiv 0 (\mod n),$$ a contradiction. Not a terribly rigorous proof but I hope this helps.
Comment: Did you mean $a_j \equiv N (\mod 2+n-j)$ instead of $a_j \equiv n (\mod 2+n-j)$ ?
Answer: There are no such numbers exist above 63.
Let $\ n = \overline{b_1b_2\dots b_k},\ \ k>6$
$b_1=1\ \ \Rightarrow\ \ n\equiv 1(\mod 2)\ \ \Rightarrow\ \ \forall m\in\mathbb{N}\ \ \  n\not\equiv 0(\mod 2m)\ \ \Rightarrow\ \ \forall m\in\mathbb{N}\ \ b_{2m-1}=1$
So, there are no two adjacent zero bits in n.
$b_7=1\ \ \Rightarrow\ \ n\equiv 1(\mod 8)\ \ \Rightarrow\ \ n = \overline{b_1b_2\dots 001}$
Contradiction.

Conjecture I came up with


Custom Function to Count Number of Used Cells in a Column in Excel 2010

Question: I'm trying to create a user defined function to count the number of used cells in column A and then multiple this by 10.
Unfortunately, UDF are a completely different coding beast than the macros I usually put together.
Function UsedCells() As Long
n = Worksheets("Marginal").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
y = n * 10
End Function

This doesn't work -- anyone provide assistance?  Thanks!
EDIT EDIT
This code ended up working based on Christmas' code:
Function UsedCells(Col As String) As Long
n = Range("A" & Rows.Count).End(xlUp).Row
UsedCells = n * 10
End Function

Answer: The formula is the variable.  So set the name of your function (UsedCells) = to your result:
UsedCells = n * 10
EDIT:  Please note this will not recalculate if you use more cells in col A.  To make it calculate dynamically use:
Function UsedCells(Col As String) As Long
n = Worksheets("Marginal").Range(Col & ":" & Col).Cells.SpecialCells(xlCellTypeConstants).Count
UsedCells = n * 10
End Function

Then in any given cell in your sheet, place the forumla =UsedCells("x") where x is the letter of the Column you want to check.
Working solution:
Function UsedCells(Col As String) As Long
UsedCells = Sheets("Marginal").Range(Col & Rows.Count).End(xlUp).Row * 10
End Function

Comment: Sorry confused by what you mean?  what do you mean by name
Comment: The name of the Function `UsedCells` is the variable.  I am adding more details to make this more functional for you.
Comment: Alternate method added. Added more detail.
Comment: Hi Christmas, this works but unfortunately counts ALL cells in the column.  I used your code as a skeleton but this worked for me:
n = Range("A" & Rows.Count).End(xlUp).Row
UsedCells = n * 10


Two related limit questions - Measure theory

Question: Let $(X, \mu)$ be a measure space and $f:(X, A) \rightarrow (\mathbb{R}, B(\mathbb{R}))$ a non-negative function with $\int_{X}f d\mu < \infty$ I want to show
1: $\lim_{i \to \infty}\int_{\{x \in X: f(x) >i\}}f d\mu = 0$
2: $\lim_{i \to \infty}i \mu (\{x \in X: f(x) >i\})=0$
Attempt:
For 1: I want to use DCT but am not sure what function I can take as my sequence.
Let $f_{i}$ be a sequence converging to $0$ pointwise and be lebesgue integrable. Initially I choose $f_{i}=\frac{1}{i}$ but I think that fails on the integrability criteria? Then let the dominating function be $f_{1}$. Then there exists an integrable function $f$ such that $f = \lim_{i \to \infty}f_{i}$ and we would then have $\lim_{i \to \infty}\int_{\{x \in X:f(x)>i\}}f_{i} d \mu = \int_{\{x \in X: f(x)>i\}}\lim_{i \to \infty}f_{i} d\mu = \int_{\{x \in X:f(x)>i\}}f d\mu = 0$
I do know since $f$ is non-negative I can find a monotonic sequence that converges to $f$.
2: This looks like I can maybe apply Chebyshev Inequality:
$\mu(\{x \in X: f(x)>i\}) < \frac{1}{i}\int_{\{x \in X: f(x) >i\}}f d\mu$ Which by part 1 I know this limit converges to $0$ so the result follows?
Answer: Notice that $|\chi_{\{f>i\}}f| \le |f|$ and that pointwise $\chi_{\{f>i\}}f \to 0, i \to\infty$. Since since $f \in L^1$, DCT implies:
\begin{equation*}
\lim_{i \to \infty}\int_{\{f>i\}}f \mathrm{d}\mu = \lim_{i \to \infty}\int_{X}\chi_{\{f>i\}}f \mathrm{d}\mu =0 \;.
\end{equation*}
It follows that
\begin{equation*}
i\mu[f>i] = \int_{\{f>i\}} i\mathrm{d}\mu \le\int_{\{f>i\}} f\mathrm{d}\mu \to 0, \qquad i \to\infty\;.
\end{equation*}
Comment: Does the answer to this question solve your doubt? https://math.stackexchange.com/questions/3412510/using-dominated-convergence-theorem-with-continuous-limits
Comment: Thanks that makes sense. Does my part 1 look okay, or does it need amending. If it needs amending it looks like I can use a similar argument and just take $f_{i} = \chi_{f >i}f_{i}$?
Comment: after looking at your post again, I'm a bit confused. What have you taken as your sequence of functions $f_{i}$?


If Using Enterprise Library, Is log4net better to log with?

Question: For a project we are using Enterprise Library 5, and will be using several of the blocks.  I'm inclined to use the Logging application block since its built into this framework.  But I do see a lot of recommendations for log4net, so what have people chosen to do and if choosing log4net, why did you choose it over some of the others?
Thanks.
Answer: Take a look at this question on SO:  log4net vs. Nlog
The top voted answer looks especially pertinent, comparing EntLib, log4net, and NLog.
For what it's worth, I was evaluating log4net and NLog and chose to go with NLog;  I just wanted something that would be easy to set up and would "just work", and so far NLog has been that.
Answer: I would probably go with Enterprise Library's logger, as I'd generally prefer one integrated library over using two separate libraries.
If you were only going to be using the logging block from EntLib, then I would probably choose log4net, but in this case, where you are going to be using EntLib anyway, the advantages of log4net over EntLib are minor enough as to not make them whilewhile to drag in another dependancy.


Multiple Voices in "Rock" Piano

Question: I generally get the idea of "multiple voices" in music such as explained in this question and answer.
Is it also correct that in modern (e.g. non-classical) music multiple voices are used to show different instruments in a more compact way?
For example, in this part of "With or Without You" it looks like the bassline is in the bass clef and accompaniment chords are shown with stems pointing down and the vocal line is shown with stems pointing up.

Also, I am sure the best answer is, "whatever sounds better" but is there a convention as to what a Pianist is supposed to play when there are multiple voices?
For another example, this section of "Hang on Sloopy" (found here) is confusing:

Although there is an extra treble clef dedicated to the sung part of the song, it seems like the same notes are added to the accompaniment part of the score. Additionally (having tried it) playing only the stem down notes from the lower treble clef makes it sound like things are missing (for instance the first F note), however it is clearly in a different voice.
Even if someone could play all of the right hand notes, later sections of the song are quite awakward to play all of the notes in the middle trebble clef.
Is there some sort of standard to know what is expected to be played on Piano when looking at sheet music like this?
Comment: It sounds like the problems you mention in "later sections" of "Hang on, Sloopy" might be underlying this post. If that's the case, I suggest opening a second post to address those specifically in terms of how to play them. Before doing so, though, check out [What is the best way to play a chord larger than your hand?](https://music.stackexchange.com/a/110124/70803) to see if it addresses the issue(s).
Comment: "Even if someone could play all of the right hand notes" .... There's never more than three simultaneous notes.  How is that unplayable?
Comment: Did someone say it was unplayable @JimL.?
Answer: Is it also correct that in modern (e.g. non-classical) music multiple voices are used to show different instruments in a more compact way?
Correct. There's nothing about this kind of multiple-voices-on-the-piano approach that is unique to classical music.
In the first example, the piano is covering the bass, voice, and guitar chords, as described.
Is there a convention as to what a pianist is supposed to play when there are multiple voices?
The second example is the same, except that the topmost staff is there for a vocalist, not the pianist. It's easier for a singer to read from a dedicated staff, so it's often included, even when the piano part also has the vocal line. This allows for three options:

Solo piano: play the two piano staves as written, so the vocals are covered, and the extra staff can be ignored.
Voice and piano 1: play the two piano staves as written, so the piano will double the singer.
Voice and piano 2: leave out the top-most notes in the piano part (or whichever notes are doubling the vocals), and just play the remaining notes to provide the harmony.
Voice and piano bonus option: Since chord symbols are included, the pianist can play off of those, including the written bass part, or creating one based on the chord symbols.

Sometimes one might encounter music in which the piano part does not include the vocal line. So, three staves as with "Hang on Sloopy", but in that case, a solo piano would have to read all three. And since the arrangement was created with a singer in mind, there could be situations where the span between the written piano part and the vocal part is too wide, awkwardly overlapping, or in some other way "unplayable".
For a solo pianist in this situation, compromises have to be made, with priority going to maintaining the vocal line. How to handle this depends on the abilities of the individual.

Some pianists will play the vocal part and intersperse chords as they can, according to the symbols provided.
Another pianist will play the vocal part, and play as much of the written piano part as possible.
And yet another pianist will do a combination of both.

Is there some sort of standard to know what is expected to be played on Piano when looking at sheet music like this?
As described above, it depends on the musician(s) involved. But simply:

A solo pianist who primarily plays from a fully notated score would be expected to play the lower two staves as written.
A solo pianist who plays from chord changes would be expected to play the vocal line and create their own bass and chord parts.

Multiple Voices in "Rock" Piano


How to get user data by providing user name or user profile field

Question: I am using postman. I want to provide the username or a user profile field say roll no and fetch the user's information. What should be the URL.
I am able to fetch the user information when I provide the uid using the following URL :
http://[yourdomain]/[endpoint]/user/[uid]

Answer: If you want to get the user data by providing username, you can use pass name (username) as a parameter to the service URL like follows
http://example.com/<endpoint path>/user?parameters[name]=krishna

If you want to pass either username or other user profile fields you can achieve that using Services Views module. After installing this module make sure to enable it under service resources list.
Create a view with contextual filter(s)
Executing view via views resource
After enabling "views" resource in your services endpoint you can do GET request to:
http://example.com/<endpoint path>/views/<view name>

This will execute a view and pass results.
Possible arguments:
- display_id: views display

args: array of view arguments
filters: array of view filter values
offset: views offset
limit: limit views number of results
format_output: boolean whether we would like to get themed view or data
Comment: http://example.com//user?parameters[name]=krishna this works !
Comment: i made a view and added User:Name in contextual filters.So what should be the url now.
Comment: tried few urls. they are not working. please help.
Comment: @TulikaSharma URL would looks like follows-
`http://example.com//views//[filter]`
make sure that you've created services view.
Comment: it gives error 404 not find : Could not find the controller
Comment: but args[0]=8728 works where 8728 is the field value
Comment: Ok will try that
Answer: Please get the user token with below URL:
http://[yourdomain]/[endpoint]/user/token (you might need to login first)
Use the token as x-csrf-token with headers with your URL with GET method:
http://[yourdomain]/[endpoint]/user/[uid]
if above is working then you can choose query parameter as below.
http://[yourdomain]/[endpoint]/user?name=kalpan
Comment: I think this doesn't provide an answer to the question. OP wants to get the user information by providing username or  user profile field.
Comment: Sure, i have updated my answer.
Comment: I think by providing `?name` doesn't gives the result. It returns all the users instead
Comment: yes it provides all the users. doesnt work.


Como mudar um valor de um Custom Data

Question: To criando uma pagina onde vai um botão do youtube para se inscrever, queria de alguma forma mudar uma custom data que esta nele.

seria o data-layout queria que o valor dele fosse para default quando chegasse a um certo tamanho de tela, mais nao to sabendo como mudar esse valor dentro del em javascript.
Answer: Use setAtribbute:
let div = document.getElementsByClassName('g-ytsubscribe')[0].
div.setAtribbute('data-layout', 'default').

Como mudar um valor de um Custom Data


decltype error with free function

Question: I was playing with decltype and found strange thing. Why do I have this error when trying to decltype a free function? It works well with lambdas, but not with a free function. What do I do wrong here?
#include <iostream>
using namespace std;

int fun()
{
    cout << "inside fun" << endl;
    return 1;
}

int main()
{
    decltype(fun()) x = 2;
    cout << x << endl;

    auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
    decltype(lambda) l = lambda;
    l();

    decltype(fun) f = fun; // ERROR
    f();
}

The error is:
prog.cc: In function 'int main()':
prog.cc:19:19: warning: declaration of 'int f()' has 'extern' and is initialized
     decltype(fun) f = fun; // ERROR
                   ^
prog.cc:19:23: error: function 'int f()' is initialized like a variable
     decltype(fun) f = fun; // ERROR
                       ^~~

Wandbox URL: https://wandbox.org/permlink/E7BbGlyQD8FcHr5j
Comment: If you are asking about compilation-errors - please copy-paste the error in question, into your question.
Comment: `decltype(&fun) f = &fun`
Answer: Here is essentially the same error without using decltype:
#include <iostream>
using namespace std;

int fun()
{
    cout << "inside fun" << endl;
    return 1;
}

int main()
{
    // was: decltype(fun()) x = 2;
    int x = 2;
    cout << x << endl;

    auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
    decltype(lambda) l = lambda;
    l();

    typedef int fn_type();
    fn_type* f = fun;  // no problem
    fn_type g = fun; // ERROR
    f();
}

You have declared f to be of type int() i.e. it's like you're trying to copy the function into a new variable, which C++ does not support (functions are  not first-class objects). It's permissible to create a function pointer, which is probably what you want, and assign directly from fun, which will be automatically treated as a function pointer in that context.
This doesn't happen for lambdas because they implicitly declare a new class (just a regular class in the usual sense). They act like functions because they have an overloaded operator() method, but they are not actually functions in the traditional C++ sense.
Answer: decltype(fun) returns the function type, not the fn ptr type. You can't 'assign' a function, only a function ptr. If you want to wrap a free function, you have these choices:

Take a function ptr
Wrap the fun() call in a lambda
Wrap fun in std::function<> (note: this is a virtual call)

decltype error with free function


Call another process's method in Python

Question: My setting is the following - I have a Tornado based HTTP server which is pretty much the "hello world" example:
server = tornado.httpserver.HTTPServer(app)
server.bind(8888)
server.start(2)
tornado.ioloop.IOLoop.instance().start()

Now in this setting, I also have another process (let's call it control process) spawned by the root process. Thus this control process is a sibling to the two Tornado handler processes. Naturally I can communicate between the handler processes and the control process through a pipe created by the root process. I however, am more interested in calling a method of the control process and getting it's output.
What is the best approach to do such a thing? If I use the pipe for sending the request from a handler to the control and return the result, should I use a lock to implement process-safety?
Answer: You don't need a lock with pipes. The pipe is its own synchronization. Or, put a different way, the two sides of the pipe are separate objects.
(Of course the control process may need a lock internally, e.g., if it's handling the pipe from a different thread than the main event loop and needs to share any data with code that runs in the main loop, but that's not related to inter-process safety.)
Anyway, if you step back and think about this from a higher level, what you're implementing is the exact definition of an RPC mechanism. If what you're doing is simple enough, implementing it from scratch this way is fine, but if not, you may want to have add another protocol to control and let Tornado manage it along with your existing protocol(s).
Comment: Yes, it is exactly an RPC. And yes, I somehow got confused, that two inputs from the two handlers and their outputs may get mixed up somehow (shame on me). As I'm quite new with Tornado, could you specify what you meant by "adding another protocol to `control`"?
Comment: @DJV: I meant… whatever you meant by it the four times you used that name in your question. You want some "handler process" to make requests against "the control process". So, if that "control process" is already using Tornado to implement, e.g., a web app server, or a JSON-RPC-over-sockets server, or whatever, just add another protocol for the other process to use, instead of implementing something independent from scratch.

Call another process's method in Python


.SQLiteException: no such table: tblPhong (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM tblPhong

Question: It seems i don't have tblPhong table in my database, maybe my createTable() isn't correct, but it's correct on another app i built, i can't find the mistake of my code, pls help me !
This is my PhongTroDB class
public class PhongTroDB {

    String dbName = "phongtro.db";
    Context context;
    SQLiteDatabase db;

    public PhongTroDB(Context context) {
        this.context = context;
    }
    public SQLiteDatabase openDB(){
        return context.openOrCreateDatabase(dbName,Context.MODE_PRIVATE,null);
    }
    public void createTable(){
        String sql = "CREATE TABLE IF NOT EXISTS tblPhong(" +
                "MAPHONG INTEGER PRIMARY KEY AUTOINCREMENT," +
                "TANG INTEGER," +
                "DIENTICH INTEGER," +
                "GIATIEN INTEGER," +
                "MOTA TEXT)";
        db = openDB();
        db.execSQL(sql);
        db.close();
    }

    public int countPhong(){
        String sql = "SELECT * FROM tblPhong";
        db = openDB();
        Cursor cursor = db.rawQuery(sql,null);
        int count = cursor.getCount();
        return count;
    }

    public void insertPhong(int tang, int dienTich, int giaTien, String mota){
        db = openDB();
        ContentValues cv = new ContentValues();
        cv.put("TANG",tang);
        cv.put("DIENTICH",dienTich);
        cv.put("GIATIEN", giaTien);
        cv.put("MOTA",mota);
        db.insert("tblPhong",null,cv);
        db.close();
    }

    //Select
    //Select *
    public ArrayList<PhongTro> getPhongTro(){
        ArrayList<PhongTro> tmp = new ArrayList<>();
        String sql = "SELECT * FROM tblPhong";
        db = openDB();
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()){
            int maPhong = cursor.getInt(0);
            int tang = cursor.getInt(1);
            int dienTich = cursor.getInt(2);
            int giaTien = cursor.getInt(3);
            String mota = cursor.getString(4);
            PhongTro phongtro = new PhongTro(maPhong,tang,dienTich,giaTien,mota);
            tmp.add(phongtro);
        }
        db.close();
        return tmp;
    }

}

This is class Data, Where i put data to my database
public class Data extends Application {
    PhongTroDB phongTroDB;

    @Override
    public void onCreate() {
        super.onCreate();
        phongTroDB = new PhongTroDB(this);
        phongTroDB.createTable();
        if (phongTroDB.countPhong() == 0){
            phongTroDB.insertPhong(1,6,3000000,"Phòng thoáng mát, có ban công, full nội thất");
            phongTroDB.insertPhong(1,5,2800000,"Phòng thoáng mát, có cửa sổ, có tủ lạnh");
            phongTroDB.insertPhong(1,5,2800000,"Có cửa sổ, tủ lạnh, máy giặt");
            phongTroDB.insertPhong(2,7,3200000,"Phòng thoáng mát, có ban công, view sông, full nội thất");
            phongTroDB.insertPhong(2,7,3200000,"Phòng thoáng mát, có ban công, view sông,full nội thất");
            phongTroDB.insertPhong(2,7,3200000,"Phòng thoáng mát, có ban công, view sông,full nội thất");
            phongTroDB.insertPhong(3,8,3500000,"Phòng thoáng mát, có ban công, view LandMark81,full nội thất");
            phongTroDB.insertPhong(3,8,3500000,"Phòng thoáng mát, có ban công, View LandMark81,full nội thất");
        }
    }
}

This is my adapter
public class PhongTroAdapter extends  RecyclerView.Adapter<PhongTroAdapter.PhongTroVH>{

    Context context;
    ArrayList<PhongTro> lstPhong;

    public PhongTroAdapter(Context context, ArrayList<PhongTro> lstPhong) {
        this.context = context;
        this.lstPhong = lstPhong;
    }

    @NonNull
    @Override
    public PhongTroVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
        return new PhongTroVH(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PhongTroVH holder, int position) {
        PhongTro phongtro = lstPhong.get(position);
        if(phongtro == null){
            return;
        }
        holder.tvPhong.setText(phongtro.getMaphong());
    }

    @Override
    public int getItemCount() {
        if(lstPhong != null){
            return lstPhong.size();
        }
        return 0;
    }

    public class PhongTroVH extends RecyclerView.ViewHolder{

        TextView tvPhong;
        public PhongTroVH(@NonNull View itemView) {
            super(itemView);
            tvPhong = itemView.findViewById(R.id.tvPhong);
        }
    }
}

This is my MainActivity, I use RecyclerView GridLayout
public class MainActivity extends AppCompatActivity {

    RecyclerView rvPhong;
    ArrayList<PhongTro> lstPhong;

    PhongTroAdapter phongTroAdapter;
    PhongTroDB phongTroDB;

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

        phongTroDB = new PhongTroDB(this);

        rvPhong = findViewById(R.id.rvPhong);

        lstPhong = phongTroDB.getPhongTro();

        phongTroAdapter = new PhongTroAdapter(this,lstPhong);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rvPhong.setLayoutManager(gridLayoutManager);

        rvPhong.setAdapter(phongTroAdapter);
    }

Answer: Can't see where your 'Data' class is being used to then call createTable() but in any case why not change PhongTroDB class to extend SQLiteOpenHelper and implement onCreate(SQLiteDatabase db) (and onUpgrade etc.) and put your table creation there.


Problema em consumir JSON com AngularJS

Question: Estou tentando executar um teste para obter os dados de um arquivo JSON mas não estou conseguindo.

app.component.html

 {{ cursos.id }}

json

{"id":7006,"content":"Hello, World!"}

app.curso.js

angular.module("appCursos").controller("meusCursos", function ($scope, $http) {
  var cursos = [];

  var baseUrl = 'http://rest-service.guides.spring.io/greeting';

  $http.get(baseUrl).then(function (response) {
    $scope.cursos = response.data;

  })
});

Comment: *AngularJS* ou *Angular 5*?
Comment: E seu model, tem como mostrar?
Comment: **Paula**, recomendo você a fazer o [**Tour**](https://pt.stackoverflow.com/tour) para saber como funciona a **comunidade**. Sua pergunta diz que está com problemas em consumir *JSON* em *Angular 5*, mas seu código é *AngularJS*. Você pode [**editar**](https://pt.stackoverflow.com/posts/289547/edit) sua pergunta e esclarecer melhor qual das versões está utilizando, você pode também acessar o tópico [**Como fazer uma boa pergunta?**](https://pt.stackoverflow.com/help/how-to-ask)
Comment: Pelo o que o erro mostra, não existe a coluna `id` do objeto cursos, verifique o json retornado com um console.log($scope.cursos), adicione esse json à pergunta.
Answer: Não consegui replicar a mensagem de erro que você obteve com teu código e sim um erro de injecting. Quando corrigi o problema, consegui ler o JSON:
<!doctype html>

        <meta charset="utf-8">

{{ cursos.id }}

{{ cursos.content }}

É necessário colocar tanto $http quando $scope dentro dentro do controle.
Outra alternativa seria não usar $scope e trabalhar com o this para acessar/criar atributos do/no próprio controle:
var baseUrl = #...;
meusCursos = this;
meusCursos.cursos = [];
# ...
    meusCursos = result.data;
# ...

E daí acessá-los no HTML como meusCursos.cursos.id e meusCursos.cursos.content.
Comment: segui os passos coloquei $http e o $scope e continuo obtendo o mesmo erro
Comment: Teste este meu exemplo no Firefox mas no Chromium ele reclamou de algumas coisas, corrigi o problema (era fora do programa) e ele passou a funcionar. Meu exemplo está em AngularJS 1.6.8 e creio que você esteja usando o Angular 2, correto?
Comment: estou usando a versão 1.6.9
Comment: Salvando o código que colei na resposta em um arquivo HTML e o abrindo no navegador (Chrome, Firefox etc), dá o mesmo erro?
Comment: sim. Tentei exemplos sem ler arquivos e está acontecendo a mesma coisa. Acho que é algum problema com o angular, parece que as expressões e diretivas não estão sendo reconhecidas
Comment: eu segui esse exemplo (http://spring.io/guides/gs/consuming-rest-angularjs/) criando o projeto com "ng new my-app". Modifiquei o arquivo index.html de acordo com a sua resposta. Os erros são os mesmos.
Comment: Peguei o exemplo do pessoal do Spring e ele funcionando quando executado diretamente pelo navegador, isto é, `firefox hello.html` tanto com as versões 1.4.3 (original do exemplo) como 1.6.8 (última versão da série 1.x). Mas você disse que está usando "ng new ...", isso não é do Angular 2?

Problema em consumir JSON com AngularJS


Erasing a specific selected portion of a bitmap

Question: I am building a Flash Paint application. The basic structure is this.
I have two layers namely topLayer_mc and bottomLayer_mc. The actual vector drawing is drawn on the top layer and onmouseUp of the tool, a bitmap copy of the vector graphics on the top layer is taken and added as a bitmap to the bottom layer. The top layer is cleared subsequently. It is working for the pencil tool.
Now I need to create an eraser tool. This is where things get tricky. In the application there is an option to save the image as png, so alpha has top be preserved. So the coventional method of draw a brush using the vector and using the draw method of bitmap will not work. Of course, on a visual level it would work if the brush drawn using the vector is to have the same color as that of the background.
What I need is to excatly erase the pixels.
Now I have created a brush tool using the conventional technique and clearing is possible but what I need is to exactly erase the pixels. Is there some technique to draw this ?
This is the code that I am using:
I have also uploaded the swf and source code,
http://bobbythecoder.blogspot.com/2011/04/doubt-bitmap.html
When trying out, please draw all over the stage using the pencil (press Pencil button and start drawing)
The source fla is also provided,
http://www.easy-share.com/1914823453/Paint Brush Expt.fla
I have been trying hard for some time so it would be greatly appreciated if you can assist.
topLayer_mc and bottomLayer_mc have alpha set to zero now.
I have also not created a draggable brush, just two hard coded positions are cleared. To draw using pencil, just press the pencil button and draw. To clear, just press the eraser button.
What I need is a technique to erase the pixels in the area marked by a brush not just drawing over it.
Comment: @Timofei Davydik  . Sorry brother I was not aware of it. I started using stack regularly only recently. Extremly sorry.
Answer: If you pick through the AS3 documentation you'll find a few things that are significant. First of all, you're trying to draw with blendmode "erase" (BlendMode.ERASE), which only works if the DisplayObject parent Bitmap has it's blendMode changed from flash.display.BlendMode.NORMAL to flash.display.BlendMode.LAYER. If you do intend to use erase mode, I recommend using the constant flash.display.BlendMode.ERASE rather than hardcoding the literal "erase", for forwards compatibility reasons.
But.. you might not be intending to use BlendMode.ERASE, did you pick that intentionally with full knowledge of how it works? It is not necessary to use this blend mode with BitmapData. It should be sufficient for your erase tool to use BlendMode.NORMAL with your BitmapData.draw() operation, and draw transparent pixels of color 0x00000000, which you will get by specifying beginFill(0x000000, 0);
Comment: Hi Adam, thanks for answering. But I tried changing it to mcBMPD1.draw(topLayer_mc.draw_mc, null, null, BlendMode.NORMAL);
and gfx.beginFill( 0x000000, 0). If I draw a line on the stage it still does not appear to have been cleared. I hope you had seen the code.
Comment: I looked at your example FLA. There is no mystery why it's not working :-) Look at your eraserInit function--you're creating a bitmap called mcBMP1, drawing into it, then never doing anything with it. The circles you see are just the ones you draw to "gfx", your mcBMPD1 and mcBMP1 bitmap objects are completely unused and available to be GC'd as soon as you exit from eraserInit();
Comment: I'm pretty sure you meant to draw to the bitmap that already exists (mcBMP you attached to bottomLayer_mc), but you don't save a reference to that so you can't easily do it (apart from something silly like bottomLayer_mc.getChildAt(0) as Bitmap... save a reference and update that bitmap rather than adding a new one to bottomLayer_mc with each pencil draw mouseup (huge memory usage issue there)
Comment: OK, I looked at your FLA, and I think I worked out what it is you're trying to do--and it's not simple. You can disregard my response above, the beginFill with alpha=0 does not do what I expected. What you really want to do is essentially write zero-value pixels into just the alpha channel of your bottom layer bitmap. There's no easy way to do this for arbitrary shapes like circles (only for rects or individual pixels). There is undoubtedly some combination of copyChannel extraction, copyPixels addition and copyChannel back that will work, but it will take some trial and error.
Answer: Drawing transparent pixels (any colour with 0 alpha) should do the trick!
Comment: Hi Dain. I hope you had seen the code. I just changed there the line gfx.beginFill(0xcccccc, 1);   to   gfx.beginFill(0xcccccc, 0); but it did not help. I hope that was what you meant. Or is there something else I need to do.
Comment: It did not work because of the BitmapData.draw() call in your code specifying BlendMode.ERASE instead of BlendMode.NORMAL. I added an answer with a more complete explanation.
Answer: You can create a bitmap, fill it with a green rectangle, and then draw a red fill circle in it. Now, you can use copyChannel, use the source channel as GREEN, and the destination channel as Alpha. So, it will end up creating an erase effect with a circular brush.
Answer: I think I'd create third transparent clip for erasing. When you click on it while holding erasing tool just put whight circle on it.


jQuery Drag And Drop Using Live Events with .On

Question: I have used this example for a Jquery Live Dragable:
jQuery Drag And Drop Using Live Events
But want to convert it to use the .on in jquery 1.7 tried all sorts of permutations can anyone help?
Here is my working code using .live to create a .livedragable method:
(function ($) {
$.fn.liveDraggable = function (opts) {
  $(this).live("mousemove.liveDraggable", function() {
      $this = $(this);
     $this.draggable(opts);
      $this.off('mousemove.liveDraggable'); // kill the mousemove
  });
  return $();
 };
}(jQuery));

Here is the call to the livedraggable:
    $(".item").liveDraggable({
            revert: true
    });

I am using this because I have a number of draggables that are loaded via ajax from a DB.
I have now tried:
    this.on("mousemove",".liveDraggable", function() {

but it doesn't work.
UPDATE
Finally got to this via Joel Purra's answer (see below) and it works great!!
(function ($) {
  $.fn.liveDraggable = function (draggableItemSelector, opts) {
    // Make the function chainable per good jQuery plugin design
    return this.each(function(){
      // Start the event listener for any contained draggableItemSelector items

    $(this).on("mouseenter", draggableItemSelector, function() {
        var $this = $(this);

        // If the item is already draggable, don't continue
        if($this.data("is-already-draggable") === true)
    {
      return;
    }
    // Make the item draggable
    $this.draggable(opts);

    // Save the fact that the item is now draggable
    $this.data("is-already-draggable", true);
     });
   });
  };
}(jQuery));

Plus the selector
$(function() {
  $("#my_div").liveDraggable(
   ".item",
    {
      revert: true
   });
});

Answer: I don't know your reasoning for wanting the live drag and drop events but Im going to take a stab in the dark and guess it something very similar to what I needed it for a few months back.
basically I had some div's that were draggable.  I was adding more divs to the screen via ajax but because their loaded after the draggable event was fired, the new divs don't drag.  Fingers crossed I'm right here.
I got around it by basically setting up my code in such a way that the draggable function could be called again and again no matter how many items I added to the page.   See this example: http://jsfiddle.net/BLMTw/
Try the link above and you will see when you click the 'Add Box' link and try and drag the new box it doesn't drag.  Now uncomment the line shown the example and try again.  It works because I've fired the draggable again.
Apologies if Ive got your needs wrong.
Comment: Ive spent quite a lot of time with jquery draggables in the last 6 months and Ive had my fair share of headaches.  I also used the same bit of code for liveDraggables you are using during my testing but now I wont look back ^^
Answer: Edit: I would call the custom .liveDraggable(...) function on a container that contains all .item that you will add from your database. The function and call needs to be rewritten though. Try this piece of code. I also switched to the mouseenter event, since it doesn't execute as often as mousemove - but enough times to keep functionality.
(function ($) {
  $.fn.liveDraggable = function (draggableItemSelector, opts) {
    // Make the function chainable per good jQuery plugin design
    return this.each(function(){
      // Start the event listener for any contained draggableItemSelector items
      this.on("mouseenter", draggableItemSelector, function() {
        var $this = $(this);

        // If the item is already draggable, don't continue
        if($this.data("is-already-draggable") === true)
        {
          return;
        }

        // Make the item draggable
        $this.draggable(opts);

        // Save the fact that the item is now draggable
        $this.data("is-already-draggable", true);
      });
    )};
   };
}(jQuery));

Call the function once, when your page loads. This assumes you will add your .item inside

.
$("#my-item-container").liveDraggable(
  ".item",
  {
          revert: true
  });

Original answer: You might be mixing up the syntax for jQuery's CSS selectors and jQuery's event namespacing.
The event you are listening to in your .live(...) call, mousemove.liveDraggable is only fired from the .liveDraggable code if the event has been explicitly namespaced - and I don't see any such code in your example. Listening to the event won't work, as it will be filtered out by jQuery. The same goes for .on(...).
You can still use .on("mousemove", ".liveDraggable", function ...) if you are using the class .liveDraggable to distinguish your draggables.
Since you are turning off the listener right away, also have a look at .one(...).
Comment: I tried  'code' this.on("mousemove",".liveDraggable", function() { 'code' but it doesn't work.
Comment: I had to fix the syntax and use $(this). instead of this. and then it worked fine, thanks alot (I have attached my final code)
Comment: @JeffBoxall: Great! Wrote the code on the fly, so no surprise to see small bugs like that. Glad you got it to work =)


Extracting string of dates in a big query

Question: I have used the below code
select --split( INDIVIDUAL_NAMES, '->') as Assigned_to_individual,

regexp_extract( split( INDIVIDUAL_NAMES, '->'),r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)') from [table name ]where _ID  in('071632')

Here we need to extract date and i have given it a try by using d so it gives me numeric fields but this is not giving me complete date.
Comment: It would help a lot to see your input data
Comment: Please give an example value of `INDIVIDUAL_NAMES`.
Comment: Please edit your question to show a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) of the code that you are having problems with, then we can try to help with the specific problem. You can also read [How to Ask](http://stackoverflow.com/help/how-to-ask).
Comment: INDIVIDUAL_NAMES includes Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> **(06/27/2017 05:30:48 PM)** -> Sneha Singh (06/28/2017 03:11:34 AM). I would need the date highlighted in bold as this is the first date where no user is assigned
Answer: Since I do not have access to your table, I used WITH clause to emulate your input table, using the provided input sample. With that, the following query produces the desired output dates. Note that this is a StandardSQL query:
#standardSQL
WITH
  input AS (
  SELECT
    "Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)" AS input_group),
  split_output AS (
  SELECT
    SPLIT(input_group, "->") AS output
  FROM
    input)
SELECT
  REGEXP_EXTRACT(output,r"(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)") AS date
FROM
  split_output so,
  so.output

Output (null is for the "Start" entry - note that sql output is not ordered):
Row date
1   03/15/2017 02:10:12
2   01/06/2017 08:08:44
3   11/11/2016 08:24:24
4   06/20/2017 12:52:27
5   06/28/2017 03:11:34
6   01/30/2017 10:34:33
7   06/27/2017 05:30:48
8   null
9   11/11/2016 11:15:33
10  03/23/2017 12:42:52

Answer: Below is for BigQuery Standard SQL
#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')) AS date_as_timestamp
FROM yourTable, UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item
-- ORDER BY 3

above can be slightly simplified to remove redundant portions - for example as
#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
)
SELECT
  id,
  LTRIM(SPLIT(CONCAT(' ', item), ' (')[OFFSET(0)]) AS name,
  date_as_string,
  PARSE_DATETIME('%m/%d/%Y %r', date_as_string) AS date_as_datetime,
  PARSE_TIMESTAMP('%m/%d/%Y %r', date_as_string) AS date_as_timestamp
FROM yourTable,
  UNNEST(SPLIT(INDIVIDUAL_NAMES, ' -> ')) AS item,
  UNNEST([REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)')]) AS date_as_string
-- ORDER BY 3

Output is as below
id  name        date_as_string          date_as_datetime    date_as_timestamp
1   Start       null                    null                null
1   Akumar      01/06/2017 08:08:44 PM  2017-01-06T20:08:44 2017-01-06 20:08:44 UTC
1   Akumar      01/30/2017 10:34:33 AM  2017-01-30T10:34:33 2017-01-30 10:34:33 UTC
1   Akumar      03/15/2017 02:10:12 PM  2017-03-15T14:10:12 2017-03-15 14:10:12 UTC
1   Akumar      03/23/2017 12:42:52 PM  2017-03-23T12:42:52 2017-03-23 12:42:52 UTC
1   Akumar      06/20/2017 12:52:27 PM  2017-06-20T12:52:27 2017-06-20 12:52:27 UTC
1               06/27/2017 05:30:48 PM  2017-06-27T17:30:48 2017-06-27 17:30:48 UTC
1   Sneha Singh 06/28/2017 03:11:34 AM  2017-06-28T03:11:34 2017-06-28 03:11:34 UTC
1               11/11/2016 08:24:24 AM  2016-11-11T08:24:24 2016-11-11 08:24:24 UTC
1   Akumar      11/11/2016 11:15:33 AM  2016-11-11T11:15:33 2016-11-11 11:15:33 UTC

would be really great if you can suggest a similar instance in legacy sql

You can try below for BigQuery Legacy SQL
#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM yourTable
  ), item)
)
-- ORDER BY date_as_string

You can test it with dummy data you provided as below
#legacySQL
SELECT
  id,
  IF(name = CONCAT('(', date_as_string, ')'), '', name) AS name,
  date_as_string
FROM (
  SELECT
    id,
    NTH(1, SPLIT(item, ' (')) AS name,
    REGEXP_EXTRACT(item, r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d [AP]M)') AS date_as_string
  FROM FLATTEN((
    SELECT id, SPLIT(INDIVIDUAL_NAMES, ' -> ') AS item, INDIVIDUAL_NAMES
    FROM (
      SELECT 1 AS id, 'Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)' AS INDIVIDUAL_NAMES
    ) AS yourTable
  ), item)
)
ORDER BY date_as_string

Comment: I recommend to move to BigQuery Standard SQL as soon as you can  - meantime see version for Legacy SQL
Comment: this would be really great if you can suggest a similar instance in legacy sql as the tables we have do not support standard sql. This field is just one of the columns we are fetching whereas with legacy sql we have already built mutiple columns and unfortunately that table does not support standard sql.
Comment: this is a life saver, kudos to you


Is $|z-i| = |z+i|$?

Question: I computed a Mobius transformation $-\frac{z-i}{z+i}$ that maps the upper half plane to a disk, with i mapping to the center of the disk, $w = 0$.
How do I know that the disk is a unit disk and not anything bigger or smaller?
I tried using the definition of modulus: $w = f(z) = |\frac{z-i}{z+i}| = \sqrt{\frac{x^2+(y-1)^2} { x^2+(y+1)^2}}$, but does this equal $1$?
Or, better still, is $|z-1| = |z+1|$ and $|z-2| = |z+2|$, etc.  Is there such a relation?
Thanks,
Comment: Unfortunately there is no such nice relation. You can plug in $z=i$, $z=1$, and $z=2$ into you title equation and last two equations respectively to see that none of these work out (and why no such relation will be true in general)
Comment: $z=i$ is a trivial counterexample.
Answer: In fact, $$\vert z+i\vert=\vert z-i\vert$$ is satisfied by no $z\in\mathbb C\setminus\mathbb R.$ Square each side to get $$(z+i)(\bar z-i)=(\bar z+i)(z-i)$$ which expands to $$z\bar z+i(\bar z-z)+1=z\bar z+i(z-\bar z)+1$$ or $$\bar z=z\implies z\in\mathbb R.$$ General relations like $$\vert z+a\vert=\vert z-a\vert$$ if $a\in\mathbb C$ can be solved similarly: we get $$(z+a)(\bar z-\bar a)=(z-a)(\bar z+\bar a)$$ or $$a\bar z-\bar az=0$$ after some manipulation. What number must be real for this to hold?
Answer: Hint: to compare $|z-a|$ and $|z+a|$, what happens when $z=a$ (or $z=-a$)? Can there be any meaningful relationship between them?
Comment: very good point, @cameronwilliams; that'd give me 0 = |2a| and vice versa , which is nonsense.  Then...how can I know that the image mapping is indeed a unit disk ...and not some arbitrarily large / small disk?
Comment: I'm guessing it would have to come from the context of the problem, @cameronwilliams.  But for now I have $e^{i\pi}$ (z-i)/(z+i), just from using symmetry:  i and -i are symmetric w.r.t. to the real axis, but they map to 0 and $\infty$, respectively, which tells us the image of the real axis must be a circle centered at the origin (symmetry preservation of linear fractional transformations).  Then i mapping to 0 tells us that the UHP maps to the interior of the disk.  Now, my only problem left is ...how big is this disk?
Comment: The reason that it works out is that - as you showed - $$\frac{|z-i|}{|z+i|} = \frac{\sqrt{x^2+(y-1)^2}}{\sqrt{x^2+(y+1)^2}}.$$ The denominator is larger than the numerator in general since $(y-1)^2 \le (y+1)^2$ for $y \ge 0$ (i.e. for those $z$ in the upper half plane). Hence $$\frac{|z-i|}{|z+i|} \le 1.$$
Comment: oh, gosh... :-( of course.  Thanks so much @CameronWilliams!!
Comment: You're very welcome! Sometimes you lose sight of the forest despite all of the trees right in front of you. It happens to all of us.
Comment: yes... for z in the UHP, so for y greater than or equal to zero, the quotient is less than or equal to 1.  Thanks for adding the context that I was looking for, too, @cameronwilliams.  Tip of the tongue...I just couldn't spell it out for some reason...
Comment: exactly.... :-(
Answer: The locus of points that are equidistant from two points is the perpendicular bisector of the segment connecting the two points. The locus of points so that $|z+i|=|z-i|$ is the set of points on the perpendicular bisector of the segment connecting $-i$ and $i$; that is, the real axis. Thus, the locus of points so that $\left|\frac{z+i}{z-i}\right|=1$ is the real axis. In other words, $\frac{z+i}{z-i}$ is on the unit circle if and only if $z$ is real.

Is $|z-i| = |z+i|$?


Obtaining residual variance from glmnet

Question: I am working with glmnet and I'd like to see how we can obtain a residual variance for a given penalty parameter in prediction. I use glmnet's QuickStartExample example (here) and focus on L1 penalty with a given lambda. My code is as follows:
require(glmnet)
data(QuickStartExample)
fit <- glmnet(x, y, intercept = F, standardize = F, thresh = 1e-20, alpha = 1)

Following, I extracted coefficient vector using predict function to get the exact solution for 25th lambda as follows:
beta_glmnet = as.matrix(predict(fit, s = fit$lambda[25]/(2*dim(x)[1]), type = "coefficients", exact = T)[-1,])

My question is how we can obtain an estimate (preferably an unbiased one) of residual variance for the above model. My initial thought was fit$dev.ratio[25]/fit$df[25].
Any ideas?
Answer: In my understanding it is in deviance function of glmnet
data.table(l=fit$lambda, d=deviance(fit))[abs(l-reg.lambda) == min(abs(l-reg.lambda))]$d[1]

Comment: Is the deviance the residual _variance_ or the square root thereof?
Comment: never mind: experiments indicate it is indeed variance, as it scales with $y$ _squared_. That is, running a `glmnet` fit twice, once with $y$, once with $10y$ results in deviances that are 100x bigger.
Comment: ahh, but you must adjust for the number of observations, as deviance is like a raw sum of squares.

Obtaining residual variance from glmnet


Blank white screenshots while taking screenshots with selenium webdriver in C#

Question: Following this SO post I was able to take screenshots but they turned out to be just white. I tried couple of workarounds with no avail

Tried using one monitor instead of usual two
Used different image format
Included System.Drawing reference even though I didn't an compiler error.

Code

Screenshot ss=((ITakesScreenshot)driver).GetScreenshot();
  ss.SaveAsFile("test.png", System.Drawing.Imaging.ImageFormat.Png);

What should be my next steps. I am using C# 4.0
Comment: What is the application you are taking a screenshot of? As Matt has said it can depend on what you are capturing. It could also be you are focusing on a different window when taking the screenshot?
Comment: I was hoping taking screenshot of the firefox window. If I see some output, instead of white screen then I would know that I am atleast in the right direction.
Answer: My mistake, I was not using the selenium API correctly. I doubt any one would again do the same mistake again but here is the fix. I did the first call

Screenshot ss=((ITakesScreenshot)driver).GetScreenshot();

in a constructor and second savefile at the place I want to create the screenshot

ss.SaveAsFile("test.png", System.Drawing.Imaging.ImageFormat.Png);

They both should be combined at one place.
Answer: Perhaps you are taking a screenshot of WebGL object?
Traditional screenshots may not work in this case.
Comment: Its firefox window that I am hoping to capture and it does not have any webgl objects


Is number of knot strands an invariant?

Question: Question: Does the number of components in a knotwork depend on the particular planar embedding?

I've been investigating how to compute the number of components ("separate strands") in a Celtic knot based on the underlying planar graph structure. (See relationship between knots/links and planar graphs here).

Apparently the calculation for general graphs is a little complicated; for example, the reference in this question points out that for a uniform $m\times n$ grid of squares, the number of components is $\mathrm{lcd}(m,n)$.

It would satisfy me to find a formula for computing the number of components ("strands"), or a relationship between the number of strands and various graph properies such as its degree, spectrum, etc., even if those properties were hard to calculate.

One approach I've taken is in terms of connected components: each separate strand  follows a particular trajectory, and the connected components of those trajectories correspond exactly to the strands. You can define the trajectory as a transition function mapping (some additional structure plus) each edge to its successor; this is a permutation on (structured) edges whose cycles are the components.

The transition function can be encoded as its own, derived, directed graph (similar to a graph-encoded map), whose connected components are the components of the knotwork. From linear algebra, we know that the number of connected components can be recovered as the multiplicity of the zero eigenvalue of the adjacency matrix's Laplacian.

However, I know that the same graph $G$ can have multiple non-isomorphic planar embeddings (i.e. whose duals are non-isomorphic). So far in my experience, this has changed some of the knotting properties (such as number of twists in each component) but not the number of components:

My question is this:

Question: Does the number of components in a knotwork depend on the particular planar embedding? How do we prove it?

My intuition says that the number of components is an invariant, but I haven't been able to produce a counterexample or proof using my approach above.

Conjecture: If $G$ is a graph, then the corresponding knotwork has $c$ components, where
$$T_G(-1,-1) = (-1)^{|E(G)|}\cdot (-2)^{c - 1}$$
and $T_G$ is the Tutte polynomial, and $|E(G)|$ is the number of edges in the graph. (?)
Comment: And is a thread the same as a strand? The usual word in knot theory for what I think you're asking about is the number of *components* of a link. The number of components is certainly an invariant, independent of the particulat diagram of a given link.
Comment: Can you clarify what "threads" means? I can't extract a definition from either what you've written or your diagram.
Comment: Thanks for pointing that out. I meant the same thing by thread/strand/component of a link. If there was a nuance, it was that "strand" is informal, describing the physical object, and "component" is its formulation as a mathematical model.
Comment: @GerryMyerson Thanks, yes. The number of components is an invariant of the knotwork. But each planar (embedding of a) graph gives rise to a knotwork, and I think different embeddings of the same G may give rise to *different* knotworks (e.g. different #s of twists), though the knotworks from the different embeddings will share some properties in common. I'm wondering how to prove that "# of components" is independent of choice of embedding.
Comment: OK. I'm not sure I understand how a graph determines a knot. It seems to me that when you leave a crossing you may have a choice of which crossing to go to next, and different choices can lead to different numbers of components (and this is regardless of how you subsequently choose the overs and unders). Even with the triangle graph, I don't see what's to stop you from making three little, separate, figure-eights.
Comment: Okay, so maybe the problem is that I didn't understand what you meant by "knotwork." Do you mean a knot diagram? What information are you keeping about the crossings?
Comment: @QiaochuYuan I think I understand your question.  Every connected planar graph gives rise to a "knotwork", which is embedded in the plane with crossings specified (see final picture) and I believe is unique up to exchanging all "over" crossings with "under" crossings.  I'm not sure how it relates to the formal concept of a link.
Comment: @GerryMyerson A strand crossing an edge has a current state specified by giving the edge and one of its endpoints. The transition rule is that a strand in state (E,x) goes to state (F,y), where E and F are consecutive edges around vertex x in clockwise order, and y is the endpoint that F has and E lacks. (Some special cases required for self-loops etc.)
Comment: OK, I think I finally understand the question, and unfortunately I have no idea how to answer it. Have you done any examples, drawing very different embeddings of the same graph, and then counting the components of the resulting knot/link?
Comment: @GerryMyerson I've tried a few; they seem to have the same number of components, though different twists. Except for just trying a few like the figure above, I'm not sure how to find a simple graph that has very different embeddings available.
Comment: Try something like two drawings of a prism, one where it's all inside a triangle, one where it's all inside a square.
Comment: @GerryMyerson Oh, thanks for the pointer! I've just tried various embeddings of the prism graph; from what I can tell, it has exactly one strand no matter which embedding you choose.
Answer: Let $D$ be the diagram of a link. For example, $D$ could be the diagram of the Celtic knot or link pictured in your post. Let $G$ be the checkerboard graph of $D$. The graph $G$ is the graph described in your first bullet point.
Answer: The number of components of $D$ is determined by the abstract graph $G$ and does not depend on how $G$ is embedded in the plane.
To the best of my knowledge, this was first proved by Michel Las Vergnas in 1979. He showed that the number of components of $D$ is determined by the Tutte polynomial evaluation $T_G(-1,-1)$. Since the Tutte polynomial doesn't depend on a particular embedding of $G$, the result follows. The reference for this paper is

Las Vergnas, Michel. On Eulerian partitions of graphs. Graph theory and combinatorics (Proc. Conf., Open Univ., Milton Keynes, 1978), pp. 62–75,
Res. Notes in Math., 34, Pitman, Boston, Mass.-London, 1979.

I could not easily find a copy of the above paper, so here's another way to get the solution, due to Dan Silver and Susan Williams (arXiv link). They define a matrix $Q_2(G)$ whose entries are in the field with two elements $\mathbb{F}_2$ as follows. Both the rows and columns of the matrix are indexed by the vertices $v_1,\dots,v_n$ of $G$. If $i\neq j$, then the $ij$ entry of $Q_2(G)$ is the number of edges between vertices $v_i$ and $v_j$ (taken$\mod 2$). The $ii$ entry of $Q_2(G)$ is the sum of the other entries in the row $i$ (again taken$\mod 2$). Equivalently, we could say the $ii$ entry in $Q_2(G)$ is the sum of the other entries in the column $i$.
In Theorem 1.1 of the linked paper, they prove that the number of components of $D$ equals the nullity of $Q_2(G)$. They note in Remark 1.2 that this implies the number of components of $D$ is independent of the plane embedding of $G$.
Edit: I don't have access to the Las Vergnas paper, but I can give another explanation of the result using the Tutte polynomial and the Jones polynomial.
Let $L$ be an alternating link, let $D$ be an alternating diagram of the link, and let $G$ be the checkerboard graph of $D$. Then the Tutte polynomial $T_G(x,y)$ of $G$ and the Jones polynomial $V_L(t)$ of $L$ are related as follows:
$$V_L(t) = f_D(t) T_G(-t,-t^{-1})$$
for the function $f_D(T)$ defined by
$$f_D(t) = (-1)^{w(D)}t^{\frac{1}{4}(|E| - 2(|V|-1)+3w(D))}$$
where $w(D)$ is the writhe of $D$, $|E|$ is the number of edges in $G$, and $|V|$ is the number of vertices of $D$. Notice that $|f_D(1)|=1$, and thus $|V_L(1)| = |T_G(-1,-1)|$.
The Jones polynomial satisfies the skein relation
$$(t^{\frac{1}{2}}-t^{-\frac{1}{2}})V_{L_0}(t) = t^{-1}V_{L_+}(t) - tV_{L_-}(t)$$
where $L_+,L_-,$ and $L_0$ are as below.

Setting $t=1$ in the above skein relation yields $V_{L_+}(1)=V_{L_-}(1)$. In other words the Jones polynomial evaluated at $t=1$ does not change under crossing changes, and thus $V_L(1)=V_{\bigcirc\sqcup\dots\sqcup\bigcirc}(1)$ where $\bigcirc\sqcup\dots\sqcup\bigcirc$ is the trivial link with the same number of components as $L$. The Jones polynomial of $\bigcirc\sqcup\dots\sqcup\bigcirc$ is $V_{\bigcirc\sqcup\dots\sqcup\bigcirc}(t) = (-t^{\frac{1}{2}}-t^{-\frac{1}{2}})^{m-1}$ where $m$ is the number of components of $\bigcirc\sqcup\dots\sqcup\bigcirc$. Thus
$$|T_G(-1,-1)|=|V_L(1)|=|V_{\bigcirc\sqcup\dots\sqcup\bigcirc}(1)| = 2^{m-1}.$$
The above case handles when $L$ is alternating. If $L$ is non-alternating, then proceed as follows. Let $D$ be any diagram of $L$. Define $D_{\text{alt}}$ to be a diagram with the same shadow as $D$ but whose crossings are changed to be alternating, and define $L_{\text{alt}}$ to be the link whose diagram is $D_{\text{alt}}$. Note that $D$ and $D_{\text{alt}}$ have the same checkerboard graph $G$. The above argument implies that $|T_G(-1,-1)|=2^{m-1}$ where $m$ is the number of components of $L_{\text{alt}}$. Since $L_{\text{alt}}$ and $L$ have the same number of components, the result follows for $L$ as well.
Comment: Thanks very much. The connection to the Tutte polynomial is especially useful.  One question---I think T(-1,-1) is sometimes negative, e.g. when the graph is an odd-length path graph. Does "determined by the Tutte polynomial evaluation" mean that component count is the abs value of T(-1,-1), or is it some more complicated relationship?
Comment: @user326210: See my edit above for an explanation.
Comment: Extremely clear & helpful. Thanks for your explanation.

Is number of knot strands an invariant?


How do I specify particular points for discretization in Pyomo?

Question: I have a continuous-time Pyomo model of the form:
from pyomo.environ import *
from pyomo.dae import *

m      = ConcreteModel()
m.t    = ContinuousSet(bounds=(0,150))
m.T    = Param(default=150)
m.S    = Var(m.t, bounds=(0,None))
m.Sdot = DerivativeVar(m.S)

discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m,nfe=100,ncp=3,scheme='LAGRANGE-RADAU')

m.obj  = Objective(expr=m.S[122],sense=maximize)

But, when I run the above code, I get the following error:
KeyError: "Error accessing indexed component: Index '120' is not valid for array component 'S'"

Looking at list(m.t), I see that, sure enough, 122 is not included as a discretization point:
..., 121.73257700000001, 122.467423, ...

How can I specify points to be included in the discretization?
Answer: You can force the discretizer to include specific points by adding them to the ContinuousSet before discretizing the model (see the online documentation).  The easiest way for your particular case is probably to include the points in an initialization list:
m.t = ContinuousSet(bounds=(0,150), intialize=[122])
print list(m.t)
# [0, 122, 150]

m.S    = Var(m.t, bounds=(0,None))
m.Sdot = DerivativeVar(m.S)
discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m,nfe=100,ncp=3,scheme='LAGRANGE-RADAU')
print list(m.t)
# ..., 121.323184, 122, 122.271339, ...


The dual space of a line in $\mathbb R^2$

Question: I am trying to develop a feeling for duality and stumbled upon the following question:
Say we are in $\mathbb R^2$ and let $U=\operatorname{span}([2,1]')$ be our subspace. My question is: what is $U^*$ (the dual space of $U$)?
I assume that since $\dim V = \dim V^*$ for any finite-dimensional vector space (and $U$ is one) $U^*$ should be a line as well, a line in $(\mathbb R^2)^*$ with row vectors so to speak. Yet it looks like anything from $(\mathbb R^2)^*$ would go: $$ \varphi: U \to \mathbb R, [x,y]' \mapsto [3,4]*[x,y]'$$ seems to be linear as well and so by definition $ \varphi \in U^* $. So whatever we have instead of $[3,4]$ the function is still linear.
And how should we construct the dual basis for $[2,1]'$? I understand the $\delta_{ij}$ way when we are dealing the the dual space of a "true" vector space (meaning it's not a subspace of any other vector space except itself).
Answer: A member of the dual space is a linear functional on $U$.  Such a linear functional is determined by its value on the vector $[2,1]'$, i.e. $f(t [2,1]') = t f([2,1]')$.
Yes, the restrictions of members of $({\mathbb R}^2)^*$ to $U$ are members of $U^*$, but different members of $({\mathbb R}^2)^*$ can have the same restriction to $U$, e.g.
$u \mapsto [3,4] \cdot u$ is the same as $u \mapsto [10,0] \cdot u$.  So it's still a one-dimensional set.  As such, any nonzero member of it constitutes a basis.
Answer: Or you could apply the Riesz representation theorem that tells you that if $H$ is a Hilbert space then the map $h \mapsto \langle \cdot , h \rangle$ defines an isometric isomorphism.
$U$ itself is a Hilbert space hence using Riesz you "see" that $U^\ast$ looks like $U$ itself.


Local Reparametrization of Surface using known Vector Field (Differential Geometry)

Question: I need help with the following problem:
"Let $X$ be a vector field defined on surface $S$, and $p \in S$ such that $X(p) \neq 0$. Prove that there exists a local parametrization $\phi \colon U \to S$ with $U$ an open set of $\mathbb{R}^2$ such that $X|_{\phi(U)} = \phi_1$ where $\phi_1$ is the derivative of the parametrization with respect to it's first parameter."
I intuitively imagine I need to use the vector field in a creative way to satisfy the condition requiered. In a way I think I need something like
$$
\phi(s,t)=\int_0^s \int_0^t X(s,t) ds dt
$$
But that doesn't really work.  I was wondering if anyone could guide me to the good parametrization so I can complete the rest...
Comment: I got a comment from someone that the problem can be solved by using the inverse function theorem or by describing the problem through an apropiate ODE. Still I don't know from where to start
Answer: Here is a sketch of a solution.  A few significant details are omitted.
By ODE theory: There exists an open neighborhood $W \subset S$ of $p$ and an $\epsilon > 0$ such that for every point $q \in W$, there exists a smooth curve $\gamma^q\colon (-\epsilon, \epsilon) \to S$ solving the initial-value problem
$$\begin{cases}
(\gamma^q)'(t) = X(\gamma^q(t))\\
\gamma^q(0) = q.
\end{cases}$$
Such curves are called integral curves of the vector field $X$.
Let $\psi\colon V \to S$ be any local parametrization with $\psi(0,0) = p.$
Define a local parametrization $\phi\colon (-\epsilon, \epsilon) \times (-\delta,\delta) \to S$ by
$$\phi(t,y) = \gamma^{\psi(0,y)}(t).$$
Let $U = (-\epsilon, \epsilon) \times (-\delta,\delta)$.  For all $(t_0, y_0) \in U$:
$$\left.\frac{\partial}{\partial t}\right|_{(t_0, y_0)}\phi(t,y) = \left.\frac{d}{d t}\right|_{t = t_0} \gamma^{\psi(0,y_0)}(t) = X(\gamma^{\psi(0,y_0)}(t_0)) = X(\phi(t_0, y_0)).$$
In other words, $\phi_1 = X|_{\phi(U)}$.
Comment: That's probably the main "significant detail" that I omitted: There exists an open neighborhood $W \subset S$ of $p$ and an $\epsilon > 0$ such that every integral curve $\gamma^q$ starting at $q \in W$ is defined on $(-\epsilon, \epsilon)$.
Comment: The other omitted details are: (1) $\delta > 0$ has to be chosen small enough so that $\psi(0,y)$ lies in $W$ for all $y \in (-\delta, \delta)$, and (2) that $\phi$ is a local parametrization (homeomorphism onto its image) -- possibly after shrinking its domain -- follows from the Inverse Function Theorem: to this end, one should check that the total derivative (Jacobian matrix) of $\phi$ at $(0,0)$ is invertible.
Comment: Isn't there a problem with the fact that the width of the interval (-\epsilon, \epsilon) changes with each curve \gamma^q? Or is it independant of the point and only depends on the original parametrization?
Comment: One last doubt: How can we use the inverse function theorem on \phi if it goes from R^3 to R^2?


Where are the cvCreateCameraCapture, cvCreateFileCapture, etc in JavaCV?

Question: I've been trying to follow tutorials for javacv from various tutorial sites, but the biggest problem was that almost every single tutorials use cvCreate... methods to bring images and videos. But when I type those in, I can't find the methods in any libraries. I downloaded the latest javacv-bin file from bytedeco and added all the libraries from that download to my project, but it's still not working. Other classes such as Mat, CvCapture work perfectly. What can be the problem?
here's one tutorial i've been following:
https://www.youtube.com/watch?v=oliqc3B9Wrc&index=3&list=PLDk0xqo2QeH-4XZ93KH38jOoGOd60-2GO
P.S.
Can you recommand any javacv and java tutorial for beginners?
I'm stuck trying to use built in webcam on my laptop to do basic camera features such as capturing and recording.
Comment: I wanted to, but then when I try to search for tutorials, a lot of them uses javacv instead of opencv. I would use opencv definitely if there's a way to EASILY find all the classes and methods I can use and their usage explanations as well
Comment: oh, and I'm using Windows 8.1 and Eclipse Mars
Comment: why don't you use [OpenCV for Java](http://docs.opencv.org/doc/tutorials/introduction/desktop_java/java_dev_intro.html)?
Answer: Did you statically import packages like below ?
<code>import static org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_imgproc.*;
import static org.bytedeco.javacpp.opencv_videoio.*;
</code>
Comment: thx for the reply. I tried static import but got some errors later on. So I just gave up on that tutorial and started studying with books from amazon. Things are working a little better, but still with hundreds of errors again. I'll just vote you up as answer and close this question.
Comment: This does solve the problem, mentioned in the question however. I just want to know, how do you know this? Where can I find a comprehensive guide on where each class is, and what it does?


NLP Classificação de texto usando Python

Question: Acho que meu problema é de classificação de texto, onde eu recebo uma string como entrada, então eu preciso combinar essa string com a escolha certa. Eu preciso de uma acurácia maior que 98,3%. Que tipo de algoritmo eu preciso estudar para resolver esse problema apresentado? Eu dei uma olhada no Bag of Words e no Word embedding mas eu não estou certo se eles resolvem o problema
Exemplo 1:
    Entrada:
    onix 1.4 mpfi ltz 8v

    Possíveis combinações:
    onix hatch ltz 1.4 8v flexpower 5p mec. (combinação correta)
    onix hatch lt 1.4 8v flexpower 5p mec.
    onix hatch effect 1.4 8v f.power 5p mec.
    onix hatch activ 1.4 8v flex 5p mec.

Exemplo 2:
    Entrada:
    gol 1.0 i 8v

    Possíveis combinações:
    gol city (trend)/titan 1.0 t. flex 8v 4p
    gol (novo) 1.0 mi total flex 8v 4p (combinação correta)

Exemplo 3:
    Entrada:
    aircross 1.6 shine 16v

    Possíveis combinações:
    aircross shine 1.6 flex 16v 5p aut. (combinação correta)
    aircross live 1.6 flex 16v 5p aut.
    aircross feel 1.6 flex 16v 5p aut.

Estou tentando combinar nomes de modelos de carros de um site com nomes de modelos de carros de outro site.
Comment: Lendo a pergunta é só uma busca léxica, pois entendi o problema assim : Há um arquivo de texto que descreve modelos de veículos por seus atributos, separados por espaço, sendo um modelo de veículo em cada linha, o usuário digitaria um texto de pesquisa e a engine de pesquisa deve encontrar a linha ou linhas cujo a distancia de edição seja mais próximo do texto a ser pesquisado. Se for esse o problema e se apresentar uma amostra de dados faço um exemplo.
Comment: O algorítmo Naive Bayes deve te atender
Answer: Você pode trabalhar com uma biblioteca que faça um fuzzy de string.
Fuzzy de string serve para achar similaridades nas strings mesmo se houver algum erro de digitação. Fuzzywuzzy trabalha com a distancia de Levenshtein para calcular as diferenças entre as sequências.
instalando os pacotes necessários
!pip install python-Levenshtein
!pip install fuzzywuzzy

importando as libs
from fuzzywuzzy import fuzz
from fuzzywuzzy import process

Exemplo 1
opcoes = ["onix hatch ltz 1.4 8v flexpower 5p mec.",
          "onix hatch lt 1.4 8v flexpower 5p mec.",
          "onix hatch effect 1.4 8v f.power 5p mec.",
          "onix hatch activ 1.4 8v flex 5p mec."]

process.extractOne("onix 1.4 mpfi ltz 8v", opcoes, scorer = fuzz.token_sort_ratio)

Saída
('onix hatch ltz 1.4 8v flexpower 5p mec.', 59)

Exemplo 2
opcoes = ["gol city (trend)/titan 1.0 t. flex 8v 4p",
          "gol (novo) 1.0 mi total flex 8v 4p"]

process.extractOne("gol 1.0 i 8v", opcoes,  scorer = fuzz.token_sort_ratio)

Saída
('gol (novo) 1.0 mi total flex 8v 4p', 55)

Exemplo 3
opcoes = ["aircross shine 1.6 flex 16v 5p aut.",
          "aircross live 1.6 flex 16v 5p aut.",
          "aircross feel 1.6 flex 16v 5p aut."]

process.extractOne("aircross 1.6 shine 16v", opcoes ,scorer = fuzz.token_sort_ratio)

Saída
('aircross shine 1.6 flex 16v 5p aut.', 79)

Vale notar que no exemplo 2 gol 1.0 i 8v a informação pode ser extraída para as duas strings, pois essa é uma ocorrência muito genérica.
Consulte a lib para saber mais.

Outra abordagem
Utilizando o CountVectorizer e a similaridade do cosseno
Exemplo 1
Importando as libs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity

Definindo as opções, nesse caso aqui vamos comparar o primeiro elemento da lista com o restante. O token_pattern eu coloquei para ele inserir na tokenização também os números 1, 1.4 e etc.
opcoes = [
          "gol 1.0 i 8v",
          "gol city (trend)/titan 1.0 t. flex 8v 4p",
          "gol (novo) 1.0 mi total flex 8v 4p"
]

count_vectorizer_gol = CountVectorizer(token_pattern=r'(?u)\b[a-zA-Z0-9_.]+')
count_matrix_gol = count_vectorizer_gol.fit_transform(opcoes)

Verificando o primeiro elemento contra os outros elementos
cosine_similarity(count_matrix_gol[0:1], count_matrix_gol[1:])

Saída
array([[0.5       , 0.53033009]])

Quanto maior este número, melhor. Neste caso o "gol (novo) 1.0 mi total flex 8v 4p" foi o que teve maior pontuação.
Exemplo 2
opcoes = [
          "aircross 1.6 shine 16v",
          "aircross shine 1.6 flex 16v 5p aut.",
          "aircross live 1.6 flex 16v 5p aut.",
          "aircross feel 1.6 flex 16v 5p aut."
]

count_vectorizer_aircross = CountVectorizer(token_pattern=r'(?u)\b[a-zA-Z0-9_.]+')
count_matrix_aircross = count_vectorizer_aircross.fit_transform(opcoes)

cosine_similarity(count_matrix_aircross[0:1], count_matrix_aircross[1:])

Saída
array([[0.75592895, 0.56694671, 0.56694671]])

aircross shine 1.6 flex 16v 5p aut. obteve maior pontuação
Exemplo 3
opcoes = [
          "onix 1.4 mpfi ltz 8v",
          "onix hatch ltz 1.4 8v flexpower 5p mec.",
          "onix hatch lt 1.4 8v flexpower 5p mec.",
          "onix hatch effect 1.4 8v f.power 5p mec.",
          "onix hatch activ 1.4 8v flex 5p mec.",
          "onix hatch ltz 1.2 8v flex 5p mec."
]

count_vectorizer_onix = CountVectorizer(token_pattern=r'(?u)\b[a-zA-Z0-9_.]+')
count_matrix_onix = count_vectorizer_onix.fit_transform(opcoes)

cosine_similarity(count_matrix_onix[0:1], count_matrix_onix[1:])

Saída
array([[0.63245553, 0.47434165, 0.47434165, 0.47434165, 0.47434165]])

onix hatch ltz 1.4 8v flexpower 5p mec. obteve maior pontuação


stale mount on linux

Question: I am running CentOS 6.9 and randomly one of the nfs mount goes stale and in the log/messages I see the message "server not responding, still trying". Forcing the mount does not work and neither reboot options from cmd. I tried reboot, shutdown -r now, reboot -f, but nothing works. Only option is to hard restart the server.
Any ideas as to what could be the cause and how to sort this?
Thanks.
Comment: Try to umount the partition, clear all open file and process which is using that partition, comment that line in fstab, then try **mount -a**, if still not work reboot with commented lines.
Answer: you should investigate hard vs soft nfs mount. depending on your requirements soft mount can be better.
most of the time this happens due to network problem, but also it might be the case that nfs server is overloaded and fails to respond in a timely manner.
also, this does not solve the root issue, but you can try to run:
<code>reboot -f
</code>
command as root to instantly reset and reboot your server (might corrupt data).

stale mount on linux


Livewire - Bootstrap select not rendering

Question: I´m struglling for hours on this, i just can´t seem to put the bootstrap-select working inside a livewire component, so i´ll try to be specific on my scenario and hopping someone could help me. I have a laravel project using this adminlte, so my code is:
web.php
Route::livewire('/new','new')->layout('adminlte::page');

Then, i have my page A where i´m including the livewire component which by the way it´s a bootstrap modal.
@livewire('new')

Inside my app.scss i have:(i installed the bootstrap select with npm)
// Bootstrap
@import '~bootstrap/scss/bootstrap';
@import '~bootstrap-select/sass/bootstrap-select.scss';

And inside my app.js i have:
require('./bootstrap');
require('../../node_modules/bootstrap-select/dist/js/bootstrap-select');

After this, i went to my livewire blade file and tried to use the example 'Select/deselect all options:
<select class="selectpicker" multiple data-actions-box="true">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>

but nothing happens, so i discovered this link and used the solution that is given but the result is the same.
Could anyone point me in the right direction? i just don´t know what am i missing, i also tried other links but if i put everything here it´s gonna be a long question.
Thanks for you time
Answer: From what you have posted here the problem is not quite clear. with the snippets you posted we cant really track where the issue is. it's always best to include the minimal code to reproduce the issue so we could easily find a solution for you and others who might stumble upon it. but i'm gonna give it a go and answer your question anyways.
some blade file with necessary libraries loaded welcome.blade.php

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://email@example.com/dist/css/bootstrap-select.min.css">

    @livewireStyles

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Open Modal
</button>

//

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     ×
                </button>

              <livewire:bootstrap-select-multiple />

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

    @livewireScripts

Livewire Component Class: BootstrapSelectMultiple.php
<?php

use Livewire\Component;

class BootstrapSelectMultiple extends Component
{
    public $customers = [];

    public function render()
    {
        return view('bootstrap-select-multiple');
    }
}

Livewire Component View: bootstrap-select-multiple.blade.php

    <select class="form-control show-tick" data-style="btn-primary" title="Select Customer..." multiple wire:model="customers" data-container="#for-customers" data-actions-box="true">
      <option  value="John Doe">John Doe</option>
      <option  value="Jane Doe">Jane Doe</option>
      <option  value="John Wick">John Wick</option>
    </select>

  Customers List

  @forelse($customers as $key => $value)

{{$value}}

  @empty
    Currently there are no selected customers.
  @endforelse

Playaround updated as well BootstrapSelectMultiple and see it in action.
Comment: Hi BezhanSalleh, i have discouvered the source of my problem.The thing is, my livewire component is a bootstrap modal that is called from a view, when you click a button the modal appears(and this modal is the livewire component). So i tested it in this "mother" view and the bootsratselect apeared currectly, but inside the modal it does not. Funny thing is, all my blade file @extends('adminlte::page'), so my livewire route has ->layout('adminlte::page');...why does it not appear in the modal? regards
Comment: @Japa i have updated the answer based on your comment. now the livewire component is inside the bootstrap modal and also the playground is update so you could see it in action.


How to calculate sample size for a financial risk experiment

Question: I want to experiment with a change to a financial transaction limit. The focus of the experiment will be the change of loss per at-risk transaction. I want to calculate the sample size required to detect a given effect size.
I know very little about statistics, so I'm not sure where to start with this. I think these are the important/relevant details:

There are very few at-risk transactions. ~19 monthly average for the last 5 months.
Loss is infrequent. 0.8% of at-risk amount per month, arising from 2 events in the last 5 months.

I want to know when a larger loss in the experimental group will be attributable to a change in the limit. I don't know what method(s) to use here.
Comment: What does your data look like?
Answer: "I want to calculate the sample size required to detect a given effect size.": The problem with this is that your answer is a function of the effect size and the effect size is unknown. So this can't be calculated.
"I'm not sure where to start with this": Thankfully, there's a very simple solution. Since you're able to control which people can receive the 'treatment' of a limit change, we don't even have to apply a statistical model -- we can simply do a randomized controlled trial, as follows.
Let the total number of customers be $N$. Choose a proportion, p, of customers that will experience a limit change (s.t. $N*p$ customers will have a changed limit; $N*(1-p)$ customers won't have a changed limit). Denote $n*p$ and $n_{1}$ and $n*(1-p)$ as $n_{2}$. Make sure the allocation to the two groups are completely random (e.g. can use a random number generator), to ensure that on average, the two groups are 'equivalent', i.e. have similar incomes, credit scores, etc. (whatever info you have about the customers). A higher number of customers will help here (in the sense of producing higher-confidence results), as would making $p$ as close to 0.5 as feasible.
Then, you must wait a while to observe behavior.
Finally, let $\bar{x_{1}}$ the the average loss of the treated group (where limits were changed) and $\bar{x_{2}}$ be the average loss of the control group (where limits weren't changed). Similarly, let $s_{1}$ and $s_{2}$ be the sample standard deviations of the losses of the two groups. Note for people with no losses should be included, e.g. if the first group contains 8 people with losses: 0,0,0,450,0,212,0,0; $\bar{x_{1}}=82.75$ and $s_{1}=165.9016$ (obviously in reality, there will be much more than 8 people).
$d=\frac{(\overline{x_1}-\overline{x_2})}{SE(\overline{x_1}-\overline{x_2})}$
Where:
$SE(\overline{x_1}-\overline{x_2})=\sqrt(\frac{s_1^2}{n_1}+\frac{s_2^2}{n_2})$
To assess statistical significance, you use a one-sided t-test (not two sided because we know increasing limits will never decrease loss in population (may happen in-sample just by chance)). If you have more than a couple of hundred of people in each group, the distribution of the 'd' statistic (which is a t-statistic) will be approximately normal. This means that if 'd' is greater than 1.64 for example, you can conclude increasing the limit led to an increase in the average loss with 95% confidence. For other confidence levels, and for what to do for smaller sample sizes, refer to standard normal tables and t-statistic tables respectively. If you have a statistically significant result, your estimate of the difference in average loss is simply $\bar{x_{1}} - \bar{x_{2}}$, and you can be confident that the 'true' value of this difference is greater than 0 with 95% confidence.
There is one issue and that is (if I'm understanding correctly), that there was only two losses in a five-month sample period. This means you have very low 'sampling variation' which will increase the standard error (denominator of d), thereby decreasing d, thereby (all else equal) leading to results that will be less statistically significant. You will need to use a greater number of people to produce statistical significance. As stated before, the exact number is unknown because the effect size is unknown. If this is not feasible, you can simple compare the averages without using the above statistical tests, with the knowledge that random chance will have a large effect impact on results. However as a rough guide, if you expect the control group to have, say, 10 nonzero losses in a given period, I would imagine that would be the minimum time-frame necessary to be confident in the conclusions of the above experiment. But the more losses, the better (for the efficacy of this experiment that is, not your business). Less than 0 means that random chance will have a very substantial impact and the observed difference may be substantially difference that what will happen in the future.
Comment: Thank you for taking the time!


javascript if state function doesn't read boolean

Question: My code work with resize function boolean change with width,
but my function contain if statement doesn't read the boolean,
what is problem with my code?
I used = ==, but I don't know how to use them exactly
var footerMenu = ['#about', '#help']
var slideSwitch = false

function slideDown(){
  footerMenu.forEach(function(list){
      $(list+' p').click(function(){
        $(list+' ul').slideToggle(300)
      })
    })
}

function slideClear(){
  for( let i = 0; i < footerMenu.length; i++){
    $(footerMenu[i]+' p').click(function(){
      var choice = footerMenu[i]
      footerMenu.splice(i, 1);
      footerMenu.forEach(function(list){
      $(list+' ul').slideUp(300)
      })
      footerMenu.splice(i, 0, choice);
    })
  }
}

function slideTotal(){
  if(slideSwitch = true){
    slideDown()
    slideClear()
  }
}

$(document).ready(function() {
  checkWidth();
});
$(window).resize(function(){
  checkWidth();
});

function checkWidth(){
  $vWidth = $(window).width();

  if($vWidth <576){
       console.log("Width: Less than 576");
       slideSwitch = true
  }else{
       console.log("Width: More than 576");
      slideSwitch = false
  }
}

slideTotal()

I hope correct my code, if I don't have any wrong please advice me how to solve it
Comment: This: `slideSwitch = true` is an assignment statement - not an equality evaluation
Answer: = is the assignment operator. It changes the value of what is on the left hand side. It is usually not what you want in an if statement unless you really know what you are doing.
== and === are the comparison operators. The different between them is that == automatically converts the two arguments to the same type, whereas === does not. But that doesn't really matter, my advice is to always use === to compare variables in an if statement.
Also, comparing to true (x === true) is completely pointless because that is what an if statement already does; it is unnecessary.
(side note: you could do if (x === true === true === true), and that would be the same as if (x).)
The code you want is:
function slideTotal() {
  if (slideSwitch) {
    slideDown();
    slideClear();
  }
}

Answer: Well, to start:
function slideTotal(){
  if(slideSwitch = true){
    slideDown()
    slideClear()
  }
}

change: slideSwitch = true
to: slideSwitch == true


How to get the parent elements by quering the child elements in the json data.Explanation is given below

Question: I am new to Apigee,I had tried a query to extract the value from the json data child and i need to get the parent element from the json data.
JSON is Here:
<code>{ "Booksstall": [
        { "serialId": "10123456",
            "Name": "magic"
            "books": [
                { "Order": 3,
                    "Name": "Supermax"
                }
            ],
            "NormalserialIds": [
                {"serialId": "1234556",
                    "Status": "InStock",
                    "books": [
                        {"type": "400001623",
                            "Code": "PATR"
                        }
                    ]
                },
                {"serialId": "789101",
                    "Status": "OutoffStock",
                    "books": [
                        {"type": "400001623",
                            "Code": "NFES"
                        }
                    ]
                }
            ]
        }
    ]
}
</code>
I tried this query in online json validator ,but if I tried same in the Apigee extract variable policy by doing substitution Its not returning me any values.
<code>$.Booksstall[?(@.NormalserialIds[0].serialId=="1234556")].serialId
</code>
The above query result is: 10123456.
Please suggest how can I try this.
Answer: You can also use Javascript Policy to extract same. It should be simple and straight forward with Javascript Policy.
Cheers,
Anil Sagar


Random effects model with PLM: "System is computationally singular"-Error?

Question: I am currently trying to estimate some panel data models in R using PLM package. This includes the estimation of basic pooled, fixed effects and random effects models. Therefore I make use of this code:
# read in data
mydata<- read.csv2("Panel.csv")
attach(mydata)

# define dependant variable
standarddeviation <- cbind(sd)
# define independant variable
x <- cbind(ratio1, ratio2, ratio3, ratio4, mean)

# Set data as panel data
pdata <- plm.data(mydata, index=c("id","t"))

# Pooled OLS estimator
pooling <- plm(standarddeviation ~ x, data=pdata, model= "pooling")
summary(pooling)

# Between estimator
between <- plm(standarddeviation ~ x, data=pdata, model= "between")
summary(between)

# First differences estimator
firstdiff <- plm(standarddeviation ~ x, data=pdata, model= "fd")
summary(firstdiff)

# Fixed effects or within estimator
fixed <- plm(standarddeviation ~ x data=pdata, model= "within")
summary(fixed)

# Random effects estimator
random <- plm(standarddeviation ~ x, data=pdata, model= "random")
summary(random)

Now here's the problem: I can without any problem estimate all models except for the random effects model. After entering the "random"-formula, R produces the following error:
"Error in solve.default(crossprod(X.m)) :
  system is computationally singular: reciprocal condition number = 9.57127e-023"

First guesses:

Linear combinations in x?
A first guess would be that there are exact linear dependencies of the exogenous variables in x. The data is balance sheet data and I would like to explain the standard deviation (y) of a specific balance sheet position  by other balance sheet positions (or the ratio of the position and the balance sheet sum). Of course, the variables in x are related to each other. For example some of the ratios are calculated by dividing by the mean which is also a separate independant variable. And the dependant variable, which is the standard deviation, is also calculated by using this mean. But again: There should be no EXACT correlation. But: If I exclude some of my exogenous variables, the problem disappears, but I have to include them actually.
Unbalanced panel / NAs?
The data is unbalanced and there are NAs. Fixed effects output says: n=16, T=18-40, N=455. Probably the unbalanced data or the NAs are the reason for the error?

Traceback-Code:
random <- plm(standarddeviaution ~ x, data=pdata, model= "random")
Error in solve.default(crossprod(X.m)) :
  system is computationally singular: reciprocal condition number = 9.57127e-023
traceback()
8: solve.default(crossprod(X.m))
7: solve(crossprod(X.m))
6: diag(solve(crossprod(X.m)) %*% crossprod(X.sum))
5: swar(object, data, effect)
4: ercomp.formula(formula, data, effect, method = random.method)
3: ercomp(formula, data, effect, method = random.method)
2: plm.fit(formula, data, model, effect, random.method, inst.method)
1: plm(standarddeviation ~ x, data = pdata, model = "random")

Is there anybody who can give me a hint what this error does actually mean and especially: how to solve the problem? How do I have to correct the code in order to get results? Thanks a lot!
Comment: I have the same problem. I saw [here](http://stats.stackexchange.com/questions/76488/error-system-is-computationally-singular-when-running-a-glm) that it maybe due to high correlation among the dependent vars, but that did not fix my problem. Did you ever get around this problem? When I run the same data set and the same model in STATA, my random effects model actually works. Its only R that produces this error.
Comment: Can you make the data available?
Answer: Caveat: I haven't used the plm package.
It's impossible to recreate this error because we don't have access to your data. But if the matrix is computationally singular, then you have a problem of multicollonearity. As you've identified, there's essentially two reasons that can happen.

Multicollinearity. Even if the pairwise correlations are low, it's possible that more than two columns of IVs are highly collinear with another IV column. Another piece of evidence toward this conclusion is that excluding some variables removes the error: you're removing some of the collinear columns, so the estimators are uniquely identifiable given the available data. Removing highly collinear columns doesn't change the amount of information to the regression -- the removed variables are completely or mostly determined by the remaining ones -- so it's perfectly valid as a solution. It's purely a question which explanatory variables you are more interested in.
More features than observations You speculate that this could be problem with this remark.

Unbalanced panel / NAs? The data is unbalanced and there are NAs. Fixed effects output says: n=16, T=18-40, N=455. Probably the unbalanced data or the NAs are the reason for the error?

I don't know what "n=16, T=18-40, N=455" means to you (What are n, T, and N?). But a regression with more columns than observations is likewise not identified by the data.
Answer: I had the same problem (see this question), and actually I haven't found yet a solution I am happy with, but I can give you a hint about the cause of the error and how to work around it.
As reported here, the problem is related to the fact that R approximates with zero extremely low values (in your case 1e-023). When it computes the inverse of a matrix, the mistakenly reported zeros make the model say that the matrix is singular, actually computationally singular.
That's the reason why Stata correctly processes your data, it has just a larger tolerance before approximating very small quantities with zero.
I worked around the problem by changing the random.method settings from "swar", the default one, to "walhus". This solves the computational problems and makes the model run. Whether this is statistically a desirable option is up to you to decide.
Hope this helps.
Comment: You're describing floating point round off error. This isn't unique to R, but an inherent problem with floating point numbers — they're just an approximation to real numbers, so some operations with specific data are imprecise. Likewise, R implements integers, which do not have roundoff error (but are only exact within a specific range).
Answer: I tried all the possible options in random.method, but I still got the same message -
Error in solve.default(vcov(x)[names.coefs_wo_int, names.coefs_wo_int],  :
system is computationally singular: reciprocal condition number = 9.29205e-18

The reciprocal condition number changes for the different options.
However, when I log transformed one of the variables, the issue didn't occur.
Edited: Aug 20, 2022 - I think this is because of degrees of freedom issues and also STATA can model such a case but R's current package is unable to.
Comment: It might help to elaborate on why this was, & when it could be appropriate
Comment: @Scortchi-ReinstateMonica - I myself don't know the reason, I just shared the output after trying the approach suggested in the earlier comments. If I am able to identify the reason, I will surely update!
Comment: Your variable was linearly dependent on the others.  The log transformation, being nonlinear, would likely cure that problem.  This indeed is a possible solution to the original problem, but (absent access to the data) there's no way to tell.
Comment: @whuber - Thanks. The correlation of the raw and log form are very less with other variables. The VIF is also less than 4 for all. Seems something else is the reason. I am also trying to find.
Comment: The correlation is irrelevant because it does not tell you much (if anything) about the *overall* collinearity with *all* the variables.
Comment: @whuber - Both correlation and VIF are important, that's why I mentioned both.
Comment: In the case you describe, that is not so, for the reasons I have given.  The *entire* linear structure of all your explanatory variables matters, of course--but a single correlation coefficient is no substitute for that information.
Comment: Empirical research papers mention both correlation and VIF values. I think both should be reported and used for any justification in the analysis.