text:
Q:  does not display validation messages of  on one of my pages, it is possible do open a file upload inside of a dialog. I want possible validation messages from the file upload component to be displayed inside of the dialog. As I understand it, I should be able to customize style and positioning of the validation messages that <p:fileUpload> produces (for example invalidSizeMessage) using <p:messages> , like this:
<h:form id="frmDocUpload" enctype="multipart/form-data">

    <p:dialog header="headtext" id="dlgDocUpload"
              widgetVar="dlgDocUpload"
              dynamic="true" modal="true" fitViewport="true" resizable="true" closable="true" closeOnEscape="true">
        <p:hotkey bind="esc" handler="PF('dlgDocUpload').hide();" />

        <p:fileUpload
                fileUploadListener="#{bean.handleFileUpload}"
                id="fileUploader" widgetVar="fileUploader"
                mode="advanced" dragDropSupport="true" multiple="true"
                process="@form" sequential="true"
                oncomplete="PF('dlgDocUpload').hide();"
                sizeLimit="#{bean.documentService.getUploadSizeLimit()}"
                invalidSizeMessage="Size Limit (#{bean.documentService.getUploadSizeLimitMB()} MB)!"
                skinSimple="true" />

        <p:messages for="fileUploader"/>
    </p:dialog>
</h:form>

However, when I try that, nothing happens, the validation messages stays at the top right where it's always been. What am I doing wrong?


text:
Q: WordPress Adding a template via a plugin I'm writing a plugin for a website, and one of the pages on the websites requires a custom template. How can I add a template via the plugin, without having to go into the theme's folder and adding it manually?
Any help would be appreciated.

A: if you don't want to change the existing theme you can always create a child theme: Wordpress Codex: Child Themes

redpajama_set_name: RedPajamaStackExchange


text:
Q: HapiJS scopes: Custom error message instead of "Insufficient scope" I'm using HapiJS for my REST API. I'm also using scopes functionality to implement simple role-based access to resources. Example route configuration objects looks like this:
{
    method: 'GET',
    path: '/users/{userID}',
    config: {
        auth: {
            access: {
                scope: ['user-{params.userID}']
            }
        },
        handler: getUserHandler
    }
}

By default when currently authenticated user doesn't have scope required to access given endpoint (eg. scope: 'user-1' when trying to GET /users/1), there's an error response returned:
{"statusCode":403,"error":"Forbidden","message":"Insufficient scope"}
What I want is to replace this 403 error with a custom status code and error message – I want to return 404 Not Found instead. And I want to do this only for certain endpoints. Is this possible?

A: You can do it through server.ext('onPostHandler', (request, reply) => {...
You can get the route and response object inside request.
The response object contains isBoom, if it is true, you should get the response.output.statusCode which you may validate if it is 403.
The route object contains the path which you may validate if it is the endpoint you want.
Something like this:

server.ext('onPostHandler', (request, reply) => {

  const response = request.response;

  if (response.isBoom &&
     response.output.statusCode === 403 &&
     request.route.path === 'your_endpoint') {

    // your code here
  }

  return reply.continue();
});


text:
Q: Can least-squares linear regression ever produce no solution at all? Is it ever possible for least-squares linear regression (linear in both features and weights) NOT to produce a solution? That is, after we set each partial derivative to zero, can the resulting system of n linear equations in n weights be "inconsistent"? An example of "inconsistent system of linear equations" is two parallel lines (for 2 weights) or two parallel planes (for 3 weights). If the answer is yes, can you please give a simple numerical example with 2 or 3 data points?

A: A linear system $Ax=b$ can have no-solution case due to the inconsistencies introduced in its equations. But, linear regression does not aim to satisfy $Ax=b$, it merely tries to minimize $||Ax-b||_2$. This is a simple optimization problem, and you'll have your solution, either unique or infinitely many. Intuitively, one can always draw a line as best fit to a given set of points.

A: You probably mean "unique" solution not inconsistent which is a different concept. Yes, linear regression problem can have degenerated solution, i.e. multiple solutions equally good in a sense of the lowest sum of squared residuals.
A simple example is to have two identical variables in the equation, such as a temperature in Fahrenheit and Celsius. The numbers will be different in columns, but the one can be obtained from another by a trivial linear transformation. This leads to an infinite number of solutions of least squares problem.

A: No. One way of thinking of a multiple regression is as the best fitting line in a multidimensional space. There is always such a line, even if the fit is terrible. Look at all possible lines - one will be best. Unless there is exact collinearity, in which case, more than one will be best.

A: If I understand the question correctly, one situation in which OLS breaks down is when covariance matrix is singular (i.e. its determinant is 0), which indicates linear dependency between columns (i.e. variables) in your dataset.
Note that if the determinant of a singular matrix is zero, matrix inverse would fail to be calculated.


text:
Q: Grouping preserving order I have the following trait:
trait Tr{
    val value: Int
}

and a non-ordered sequence:
val s: Seq[Tr] = //...

Now I want to split this sequence s by groups with the same value --
 Seq[Seq[Tr]] so that the resulting sequence is sorted by value in ascending order. Is there a way to do so?

A: Try s.groupBy(_.value).toSeq.sortBy(_._1).map(_._2)


text:
Q: How to Mask user email addresses with different domain in MYSQL I want to replace user domains with some other domains in mysql. for eg. I want to change :
james.wilson@rocket.com to james.wilson@abxy.com.

A: Your questions is not very clear,you can use REPLACE if you just need to change the domain of it,similar sql as below:
UPDATE table1 SET address=REPLACE(address,'@rocket.com','@abxy.com')

A: I also have tried this and it worked as well.
update table1 set email =concat(SUBSTRING(email,1,INSTR(  email,'@'  )),'abxy.com')


text:
Q: Algebraic Curves and Phase Diagrams of Physical Systems Lots of low degree curves arise naturally as the phase spaces of physical systems (that is, the curve parameterized by $(q,p)$ where $q$ is a generalized position variable and $p$ is a generalized momentum variable (such that $p=\dot{q}$, etc).
For instance, if degree is 1, then we can construct the curve as the phase space of a particle moving with constant velocity, and it is parameterized by $(x,0)$, so is given by the equation $y=0$, up to a choice of coordinates.
For $d=2$, a conic, we can use, for instance, a spring, whose position is $\cos(x)$, and so $(\cos x,\sin x)$ parameterizes a circle (ellipses are also fairly easy to see how to do this way, and parabolas are linearly accelerated particles, though I don't see hyperbolas immediately)
For $d=3$, it is well known that a simple pendulum has phase space an elliptic curve with roots the initial height, the length of the pendulum, and minus the length.
Are there other nice examples like this? Is there a natural physical system that realizes hyperbolas? Does every real elliptic curve arise in this way? How about quartic or higher curves? I assume there are physical systems that work, as every ODE is modeling SOME system, but are there well-known examples that arise naturally in physics?

A: The phase space of Kovalevskaya's top is an Abelian surface. If you fix some natural invariant you usually get a curve of small genus. If memory serves right, fixing the energy gives you a genus 2 curve.

A: You get (approximately) elliptic trajectories in 2D phase space whenever you are close to a nondegenerate stable equilibrium.  This is one way to explain why harmonic oscillators are so universal.  Similarly, you get hyperbolic trajectories when you are close to a nondegenerate unstable equilibrium.  The standard example is a ball on top of a smooth frictionless hill or an upside-down pendulum, in the limit of small deviations.

A: I have a nice example concerning the electric field in two dimensions, which I'm not sure if physicists know about. One can easily phrase it in terms of ODE.
The electric field lines of a system of point charges in two dimensions form a pencil of (real) algebraic curves, the degree of which equals the sum of (the absolute values of) the charges (which have to be integers to begin with, and the system only has finite number of charges). You get a lot of singular ones in particular, and irreducible singular ones.
I'd be happy to see a reference of it. It's so natural that one would expect that the 19th century physicists/mathematicians know about them.


text:
Q: Validation in Windows Form I am developing a Windows Form Application which has lots of Forms and each Form has several controls. In order to implement Validation I have to implement "Validating" event for each controls as following:
    private void txtSalary_Validating(object sender, CancelEventArgs e)
    {
        if (txtSalary.Text.Trim() == String.Empty)
        {
            errorProvider1.SetError(txtSalary, "Salary is Required");
            e.Cancel = true;
        }
        else
            errorProvider1.SetError(txtSalary, "");

    }

Is there any way by which i can do something generic? Rather than declaratively defining the "Validating" event for each control(Form Design View -in controls properties) could i associate the event with the controls in a generic way through code?

A: You can use only one event for each form, as an example you could use something like this
private void textboxValidation_Validating(object sender, CancelEventArgs e)
{
    TextBox tb = sender as TextBox;

    if (string.IsNullOrEmpty(tb.Text.Trim()))
    {
        errorProvider1.SetError(tb, tb.Tag +" is Required");
        e.Cancel = true;
    }
    else
        errorProvider1.SetError(tb, "");
}

This could be used for all the textboxes in the form, you just need to add what would be required by each textbox in its Tag property.
It is also possible to use one event for all forms. Take a look at Set up single event handler for multiple forms

A: you can create a separator method for validation  and call it on button click , try this:
private void SubmitButton_Click(object sender, EventArgs e)
    {
        if (ValidateControls()==0)
        {
           //Form is validated
        }
    }

    int ValidateControls()
    {
        int flag = 0;
        errorProvider1.Clear();
        if (txtAge.Text.Trim() == String.Empty)
        {
            errorProvider1.SetError(txtAge, "Age is required");
            flag = 1;
        }
        ............................................
        ............................................
       // validate all controls
        ............................................
        ............................................

        if (txtSalary.Text.Trim() == String.Empty)
        {
            errorProvider1.SetError(txtSalary, "Salary is required");
            flag = 1;
        }

        return flag;
    }

A: If all your inputs are of the same type and you're okay with doing the same validation on each input and you name your controls consistently, coolmine's answer can be extended by adding something like the following code in your form's constructor (after initialization):
foreach(Control c in Controls)
{
    if(c is TextBox)
    {
        c.Tag = c.Name.Replace("txt","");
        c.Validating += textboxValidation_Validating;
    }
}


text:
Q: Vba Excel Formula for following condition(Circular Referencing)

Hi, i tried to put a formula like ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""India"",RC,"""")" If the country is not India then Check1, Check2 and Check3 should be empty otherwise they should display their own value. when i tried to put that formula the excel has given me circular referencing warning. I just want that formula. Any help would be appreciated greatly.

A: When a formula refers back to its own cell, either directly or indirectly, it creates a circular reference.
ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""India"",RC,"""")"

You are writing the formula in activecell and the formula says if RC[-1]="India"
and if its true RC which is same as activecell. Hence you are getting the circular reference error.
But if you put this formula in Column E as below it would work.
Range("E2:E" & lastRow).FormulaR1C1 = "=IF(RC[-4]=""India"",RC[-3],"""")"

Alternatively below is simple VBA code.
Sub sample()
    Dim lastRow As Long
    lastRow = Range("A65000").End(xlUp).Row

    For i = 2 To lastRow
        If (InStr(1, Cells(i, 1), "India") <= 0) Then
            Range("B" & i & ":D" & i).Clear
        End If
    Next
End Sub

A: You can't use RC as a result only as this is referencing the current formula.
Option 1: You need to have another cell to be the validated cell, e.g.the following will create a cell to the left one of the current cell:
ActiveCell.Offset(0,1).FormulaR1C1 = "=IF(RC[-2]=""India"",RC[-1],"""")"

Option 2 after comment: If your line of code is only going to clear the current cells value if the left cell is not India then use this:
If ActiveCell.Offset(0,-1).Value <> "India" Then ActiveCell.Value = ""

Option 3: If your default value in RC has to stay but a formula is needed to override it if the value of RC[-1] becomes a not equal to India you must hard code your value in the formula like so:
ActiveCell.FormulaR1C1 = "=IF(RC[-1]=""India"",""" & ActiveCell.Value & ""","""")"


text:
Q: Identify type of data based on first couple of characters in a cell I have a range of 412 cells (A1: A412). Each cell has a string of data that I OCR'd and exported to Excel.  It is a list of names and addresses.
I need VBA code that will loop through each cell, look at the first 5 or 6 characters and determine if the string of text is a Name, Address or City (state&zip) and transpose that data out.
I have code that will transpose the data after every n number of rows, but the data does not get exported this way. Ex: the name might take up two different cells, but I want to merge those two cells in the process.
For example: public information from a state government source
CURRENT LIST (Sheet 1):
Cell A1: A. E. Ewell Investment Co.
Cell A2: P.O. Box 27
Cell A3: Ardmore, OK 73402
Cell A4: Aimie A. Akers, Trustee of the Howard A.
Cell A5: and Aimie A. Akers Revocable Joint Trust
Cell A6: Agreement dated 5/03/1996
Cell A7: 11 Nichols Road
Cell A8: Luray, VA 22835
Cell A9: Alison Evans Taylor
Cell A10: And James Andrew Taylor
Cell A11: 1523 Glenwood Avenue
Cell A12: Oklahoma City, OK 73116

Result: (Sheet 2):
Cell A1: A. E. Ewell Investment Co. Cell B1: P.O. Box 27 Cell C1: Ardmore, OK 73402
Cell A2: Aimie A. Akers, Trustee of the Howard A. and Aimie A. Akers Revocable Joint Trust Agreement dated 5/03/1996 Cell B2: 11 Nichols Road Cell C2:Luray, VA 22835
Cell A3: Alison Evans Taylor and James Andrew Taylor Cell B3: 1523 Glenwood Avenue Cell C3: Oklahoma City, OK 73116

I know this is very specific and there needs to be rules in place, but I just need the base code and I'll implement the rules.


text:
Q: The Rook Conjecture: arrangement of $p$ primes being distinct $\pmod{p}$ through $p^2$ For any prime $p$, divide $[1,p^2]$ into $p$ equal intervals of length $p$, so that the first interval is $[1,p]$, the next $[p+1,2p]$, and so on. It is definitely unproven but seems likely that there will always be a prime in every one of these intervals. It is even probably true when you substitute any natural $n$ in place of the prime $p$ above.
I've noticed a stricter condition that seems to hold. If you divide $p^2$ as described above, not only will there be a prime in every interval of length $p$, but there will always be at least one way to select those primes such that no value is repeated $\bmod{p}$.
A good name for this might be the Rook Conjecture, as this is equivalent to saying that if you number the squares of a $p\times p$ sized chessboard, there is always at least one way to place $p$ rooks on prime-numbered squares yet have no rooks share a rank or file.
Examples
$p=3,\qquad S=\{3,5,7\}\equiv\{0,2,1\} \pmod{3}$
$p=5,\qquad S=\{5,7,11,19,23\}\equiv\{0,2,1,4,3\} \pmod{5}$
etc.
I've verified this for $p\leq 1000$. As usual, I am curious whether this is a known result and/or where to look for related work, and of course any counterexamples should they exist. I'm also curious whether this result seems to others to be surprising, or expected; I'm having a hard time deciding the answer for myself.

A: The GRH neither implies that there is a prime in $[p^2-p,p^2]$ nor that the least prime $\equiv a\bmod p$ is $\le p^2$. Thus your conjecture is very strong and there is no fear to use the random model for the primes.
You are saying that for some permutation $\sigma$ of $[1,p-1]$, all the $np+\sigma(n),n\in [1,p-1]$ are primes.
The probability that they are all primes is  $$\approx\prod_{n=1}^{p-1}\frac1{\log( np+\sigma(n))} \approx \frac{C}{\log^{p-1} p}$$ the probability that no permutation works is $$\approx (1-\frac{C}{\log^{p-1} p})^{(p-1)!}\approx \exp(- \frac{C (p-1)!}{\log^{p-1-\epsilon} p}) $$
The probability that no permutation works for some $p\ge k$ is $$f(k)\le \sum_{p\ge k}\exp(- \frac{C (p-1)!}{\log^{p-1-\epsilon} p})$$
Since the series converges and $$\lim_{k\to \infty} f(k)=0$$
then the random model predicts that your conjecture holds for $p$ large enough.
(Why did I use the $\approx$ symbol ? Because the random model is case specific : we can and we should take in account the "congruences constraints" before assuming all the implied random variables are independent, which is what we need to simplify everything. Here I don't have any good argument for why this computation does take in account the relevant congruence constraints.)


text:
Q: Galaxy trucker gold club struggle I'm trying to collect my three recommendations. I've gotten the one from the businessman, and one from the scientist. Presumably, the last one is from the instructor, or the Barman. The instructor keeps eating his pizza and says he's busy. I've delivered the barmans drinks, so I'm not sure what to do. Any hints?

A: Turns out the game was in a bit of a weird state.
Parts of the game knew I had my class three license and parts didn't, for example, my instructor.


text:
Q: Can Andrica's conjecture be proven by proving a tighter upper bound for prime gaps? I checked some differences between square roots of various natural numbers and I am wondering what is required to prove Andrica's conjecture. Would a tighter upper bound for the prime gap above $n$ be sufficient? Would prime gaps have to be bounded by the product of a constant and the square root of $n$ for this conjecture to be proved?
Does Andrica's conjecture imply anything about prime gaps?

A: Andrica's conjecture is
$$
g_n<2\sqrt{p_n}+1,
$$
or equivalently
$$
\sqrt{p_n+g_n}-\sqrt{p_n}<1,
$$
where $g_n=p_{n+1}-p_n$ is the n-th prime gap.

A: Yes, Andrica's conjecture can be proven by proving a tight enough bound for the prime gap above $n$.
If prime gaps above $n$ for all $n \geq 7$ are bounded by the constant 2 multiplied by a prime < $\sqrt n$, then Andrica's conjecture is true because for Andrica's conjecture to be proven, it would have to be proven that the prime gap above $n$ is bounded by the constant 2 multiplied by $\sqrt n$.
As to what Andrica's conjecture implies will require investigation.


text:
Q: MySQL: Fatal Error encountered attempting to read the resultset Whenever my code runs, it works but then also crashes. I'm not sure if it is a time thing, or if another thing happens before that. The error code I get is this
At first, I thought it was just my connect was being closed, but it was not. I'm not sure if it is my command text or what now and all the questions like this haven't been of help.
The code that I have is this
private void On_ProcessExit(object sender, System.EventArgs e)
        {
            Console.WriteLine("Server has crashed...");
            _Proc.Exited -= new EventHandler(On_ProcessExit);

            DB.UpdateActivePID(ServerName, 0);

            if (_UserStop == true && _Proc.HasExited) {return; } //No need to restart server
            else if (_UserStop == false && _Proc.HasExited) //Need to restart the server
            {
                Start();
            }
        }

public static MySqlConnection Connection
        {
            get
            {
                if(connection == null)
                    Open();
                IsConnected();
                return connection;
            }
        }

public static MySqlCommand PrepareCommand(string query, object[] bindings)
        {
            for (int i = 0; i < bindings.Length; i++)
            {
                var regex = new Regex(Regex.Escape("?"));
                query = regex.Replace(query, "@param" + i, 1);
            }

            var cmd = Connection.CreateCommand();
            cmd.CommandText = query;
            cmd.Prepare();
            int index = 0;
            foreach (object o in bindings)
            {
                cmd.Parameters.AddWithValue("@param" + index, o);
                index++;
            }
            return cmd;
        }

  public static void ExecuteUpdate(string query, params object[] bindings)
        {
            if (Connection == null) return;

            MySqlCommand cmd = PrepareCommand(query, bindings);
            Console.WriteLine("SQL Line: " + cmd.CommandText);
            cmd.ExecuteNonQuery();
        }
public static void UpdateActivePID(string serverName, int pid)
        {
            if (Connection == null) return;
            string query = "UPDATE ServerParameters SET ActivePID = ? WHERE ServerName = ?";
            ExecuteUpdate(query, new object[] { pid,serverName } );
        }

A: looks like a wrong utf datatype like using utf8mb3_general_ci instead of utf8mb4_general_ci


text:
Q: Is the game tree of any impartial game well-founded? Why or why not? I'm trying to understand why the game tree of any impartial game (even transfinite, like transfinite Nim) must be well-founded under the "is reachable from" relation (say, if the position $G'$ is reachable from $G$ after some moves, then $G'\mathcal R G$). Why must every non-empty set of positions of an impartial game have some minimal elements? Why can't there be infinite descending chains of game positions in such a non-empty set?

A: The Wikipedia article on impartial games states that there must be a finite number of positions, so an infinite descending chain of different positions is not possible.  It does not specify that there be no cycles, so one could have a game that returned to a position seen earlier.  The Wikipedia article on the Sprague-Grundy theorem does specify that all impartial games must end, so they are well-founded.  In the early definition of a game in Winning Ways they say that games must end, but admit that some of the games they consider do not meet all the rules.  In fact, they discuss in passing the game On, which has just one move from the starting position back to the starting position.
You need to look carefully at the definition you are using of an impartial game to see if they must be well founded or not.


text:
Q: How to use of print("HelloWorld") instead of System.out.println("Hello World"); I want to know how can I use just:
Print("statement")

instead of a full path like:
System.out.println("Statement");

What lib do I have to import to do this?

A: You can make only
out.println(...);

using
import static java.lang.System.*;

A: Something like this can work
static void print(String statement)
{
    System.out.println(statement);
}


text:
Q: AWS - Lambda and SQS behavior I have setup an SQS, DeadLetterQue (DLQ) and a lambda. I am having some questions regarding the body format that the SQS receives.
After some tries, I can see some messages are ending up in a DLQ.
I have read many documentations, but really I still can't figure some basic things.
My task is fairly simple. I will use Axios to send some payload to external API. That API might give me an error, or not available at that time. This code is very simple, but at the end it will include Axios implementation:
exports.handler = async (event, context) => {
    event.Records.forEach(record => {
    const { body } = record;
    const { messageAttributes } = record;
    console.log(body)
    console.log(messageAttributes);
  });
    let somethingWentWrongWithApi = new Error();
    throw somethingWentWrongWithApi;
};

After this is run, after some time I see message in DLQ, and original SQS is empty, as I expected.
In real code, I will have catch block. And inside it I will throw the error, exactly as in example. Lambda will try to execute it three times (I am not sure where I got this information). Then, it will return it to SQS, where in turn the SQS will push it to DLQ.
I wonder, should I implement in Lambda retries, and after three times throw the error... or just throw it and rely on existing process (three times retrial)?
I am still reading about different setting on both SQS and Lambda.

A: To extend execution tries you have to go to:

*

*SQS service;

*Right click on your SQS;

*Choose a configure Queue option;

*Under the Dead Letter Queue Settings line you can see a
Maximum Receives property (which you can set between 1 and 1000).

About errors. If something going wrong on lambda side then lambda throwing an error, you can check what kind of errors throwed with cloudwatch.

*

*Go to aws CloudWatch;

*On the right panel find Logs;

*Chose Log Group.

If you have any additional questions just summon me. I'll try to answer them and I'll extend that answer.


text:
Q: Vuex: How to avoid errors when updating store (or: how to correctly watch for changes in store)? I am building an app that contains several entries of different months. To show them, the user chooses a month (with a slider) and the app returns the machting entries. Only months (or better: month-year combinations) exist if there are corresponding entries. Until here, this works fine.
However, when I want to add an entry, I get weird errors: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
I noticed that it all works fine if the corresponding month of the new entry already exists.
To get the current month-year combinations, I use a getter:
entriesMonths(state) {
  // Return an ordered arrays of all months present among entries
  var entriesMonths = [];
  var months_unique = [];
  var current_index = 0;

  const entries = state.entries;

  //Sort entries
  var order = -1;
  entries.sort(function(a, b) {
    a = new Date(a.date);
    b = new Date(b.date);
    var results = a > b ? -1 : a < b ? 1 : 0;
    return results * order;
  });

  // Add entry if not present yet
  for (var i in entries) {
    var month = moment(String(entries[i].date)).format("MM");
    var year = moment(String(entries[i].date)).format("YYYY");
    var displayMonth = moment(String(entries[i].date)).format("MMMM YYYY");

    if (!months_unique.includes(displayMonth)) {
      // Push if displayMonth not existent yet
      months_unique.push(displayMonth);
      entriesMonths.push({
        index: current_index,
        month: month,
        year: year,
        displayMonth: displayMonth,
      });
      current_index++;
    }
  }

  return entriesMonths;

To also get the months after an entry was added, I use the getter within a computed property:
computed: {
  entriesMonths() {
    return this.$store.getters.entriesMonths;
  },
},

If I use the getter in data(), I don't get an error after adding a new entry, but the app also does not show the new entry.
Adding the new entry to the store seems to work fine. So does the re-calculation of entriesMonths (I used debugger to check).
The full code can be found on Github: https://github.com/juliangermek/haushaltsbuch
The error message doesn't really tell what is wrong (and I don't think that it is an internal bug) and I can't find out what really is. Can you make sense of this?
Thanks a lot!


text:
Q: Hosting Private Git repos on my own server? I am looking for a way to host private git repos on my own server.
I am using Github for Open source projects of mine, but I would prefer to use my own server for storing private git repos.
Can someone suggest me on which script should I be using for this purpose.
Trac is not what I am looking for, though. I want something that is, preferably PHP based solution (just optional) and esp. something that has an easier UI.
Any help is appreciated here.

A: Well, for non-gitosis/gitorious setup you have two options really:

*

*Give people linux accounts with full shells (passwords and/or ssh keys) to have access to the git repository.

*Give people access to a linux account via their ssh key being in /home/ac/.ssh/authorized_keys2 whose shell is set to /usr/bin/git-shell. This means they won't be able to log in as a linux user with a shell and so do anything except use git on your machine.

In both cases, the user in question needs (read|write|both) access to the git repository, according to your needs, either as a user or as part of a group.
It might make sense for you to have a directory /git/project and then have user repositories in there, as having multiple people pushing to the same repository is generally a bad idea (people break things too easily in my experience). For example, you might have /srv/git/proj/proj-ninefingers.git and have a "release" repo of '/srv/git/proj/project.git` That's probably what I'd do if running a team effort. Permissions, shells etc to be set as appropriate.
Note that if you want to allow exports via the read-only git protocol you need to ensure the configured git user has read access and that git-daemon-export-ok exists in your bare repository. git update-server-info must also be run before gitweb will pick up the repository, should you wish to use that.
As others have said, git gc optimises the repository and it is a good idea to do this regularly. Cron job?
Finally, a plethora of frameworks exist to simplify this (gitosis, gitorious, ...). I don't think it gets any simpler than providing access to a folder via various mechanisms but then that's me.
As an example of my setup, it being only me, I have:
$ cat /etc/passwd | grep git
git:x:1002:1002:Antony Vennard,,,:/home/git:/usr/bin/git-shell
gitdaemon:x:112:65534::/nonexistent:/bin/false
$ cat /etc/group | grep git
git:x:1002:
$ ls -l /srv/git
drwxr-xr-x 7 git  git 4096 2010-09-12 23:31 bsdnt.git
drwxr-xr-x 7 git  git 4096 2010-06-16 22:32 vforth.git
$ cat /home/git/.ssh/authorized_keys2
ssh-rsa somehex user1
ssh-rsa somehex user2

This means anyone with the private key user1 can log in and commit to either of those repositories.

A: Never tried it myself, but gitorious hosts the code their running on:

*

*http://gitorious.org/gitorious
Another option with gitosis:

*

*http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way

A: Gitorious is based on there own codebase.
On this page you can find the git-repo. of the project.
Gitalist is very easy to use git Webinterface.

A: If you want just the code repository and no web pages, just place the ".git" directory somewhere accessible, that is sufficient for cloning via HTTP (note that you will need ssh or similar to push to that repository).
For example, a project of mine is hosted this way at http://psi5.com/~geier/mutextrace.git .
It is a good idea to periodically run "git gc" on that repository in order to pack objects together, so clients don't have to make thousands of accesses.
If you want web pages, then gitorious is indeed the way to go.


text:
Q: Mongoose WHERE OR LIKE syntax on referenced schemas I have the following 2 schemas (Clinic and User):
const ClinicSchema = new Schema({
name: {
  type: String,
  unique: true,
  required: true
},
createdBy: {
  type: Schema.Types.ObjectId,
  ref: 'user'
},
createdAt: Date,
updatedBy: {
  type: Schema.Types.ObjectId,
  ref: 'user'
},
updatedAt: Date

});
And Here is the user Schema
const UserModelSchema = new Schema({
email: {
  type: String,
  required: true,
},
password: {
  type: String,
  required: true,
},
firstName: {
  type: String,
  required: true,
},
lastName: {
  type: String,
  required: true,
},
roles: {
  type: [String],
  required: true,
}

});
I want to write a query that will search a string that is contained in the clinic name OR createdBy(user) name OR createdBy(user) last name, and return all the clinics where either the clinic name matches part of the search string OR the created by name matches part of the search string OR the created by last name matches part of the search string here is the pseudo SQL alternative of what I am trying to explain:
SELECT * FROM clinics
JOIN users on clinics.createdBy = users.id
WHERE clinics.name LIKE '%STRING%'
OR users.firstname LIKE '%STRING%'
OR users.lastname LIKE '%STRING%'

I have been searching for this solution for the past 2 days and can't seem to be able to figure it out, more specifically I am trying to add the WHERE OR functionality to the following query:
const clinicsQuery = Clinic.find({
  name: new RegExp(req.query.searchTerm, 'i')
});

....

const clinicsList = await clinicsQuery
  .limit(limit)
  .skip(skip)
  .populate('createdBy', ['firstName', 'lastName']);

A: It can be performed with a $lookup
const clinicsQuery = Clinic.aggregate([{
   $lookup:
     {
       from: 'user',
       localField: 'createdBy',
       foreignField: '_id',
       as: 'user'
     }},
     { $unwind: "$user"}
     {
       $match: {
         $or: [
          {"user.firstname":  new RegExp(req.query.searchTerm, 'i')},
          {"user.lastname":  new RegExp(req.query.searchTerm, 'i')},
          { name:  new RegExp(req.query.searchTerm, 'i')}
        ]
       }
     },
     {$limit: limit}
]);

User will be in "user" field in the result. But you won't have a mongoose ready object :/


text:
Q: Why is bodymovin exporting PNG's and not SVG's? I'm trying to use lottie to animate an SVG animation created in After Effects. I use the bodymovin extension to export the JSON data file. But, I also noticed the export includes some PNG images. I'm also getting console errors that said PNG's can not be found.
Why is it exporting PNGs as I'm using SVG (an AI file) in AE. Below is my code, and the error.
index.ts
import * as lottie from 'lottie-web';
import * as header from './assets/header.json';

import './css/base.sss';

var animation = lottie.loadAnimation({
    container: document.getElementById('header'),
    animationData: header,
    renderer: 'svg/canvas/html',
    autoplay: true
});

But I'm getting the following errors that the images can't be found. Why is bodymovin exporting/looking for pngs? I require SVG's.
Chrome console errors (sorry can't embed until 10 rep)

A: I found the problem. I have to convert paths to shapes in AI as noted here.

A: In Adobe After effect, you can use Create Shapes from vector layer

A: Another way I found was to search the exported .json file for the .png extension and replace the found extensions with .svg. Making sure to add the .svg files to the same directory.
I used this bodymovin render option:

I did my search in the .json file in Dreamweaver like so:

I hope this helps someone!!!


text:
Q: How to freeze GridView header? As in a title, does anyone know how to freeze GridView header in ASP.NET ?

A: You can do it in the css
Freeze Header:
1. Define class .Freezing in Stylesheet:
.Freezing
{
   position:relative ;
   top:expression(this.offsetParent.scrollTop);
   z-index: 10;
}

2.Assign Datagrid Header's cssClass to Freezing

A: Option (a) buy into a UI package that includes a souped-up GridView with this functionality built-in.
Option (b) roll your own - it's not simple. Dino Esposito has one approach.
EDIT: Just noticed that the Dino article links to a subscriber-only area on the ASPnetPro magazine site.
Here's another approach using extenders.

A: Try this open-source project for ASP.NET. It extends GridView to provide fixed header, footer and pager and resizable column width. Works well in IE 6/7/8, Firefox 3.0/3.5, Chrome and Safari.
http://johnsobrepena.blogspot.com/2009/09/extending-aspnet-gridview-for-fixed.html

A: I too faced a similar issue while developing in the web applications in Asp.Net 2.0 / 3.5.
One fine day, I came across IdeaSparks ASP.NET CoolControls. It helps to display fix column headers, footer and pager.
I used them personally and I really loved it!
To check the control click here : IdeaSparks ASP.NET CoolControls
Hope this helps!

A: I think I have solution of this.
please see below javascript code

where .header is the css class of your Grid header.
Just add this script on the page and replace header with the css class name you have used for your header.

A: Give this  a try should solve the problem
http://www.codeproject.com/KB/webforms/FreezePaneDatagrid.aspx

A: You may try the following sample
Freeze GridView Columns

A:

Scrollable Gridview with fixed header in ASP.NET

                <%-- This GHead is added for Store Gridview Header  --%>

                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
                        CellPadding="5" HeaderStyle-BackColor="#f3f3f3">
                        <Columns>
                            <asp:BoundField HeaderText="ID" DataField="StateID" />
                            <asp:BoundField HeaderText="Country" DataField="Country" />
                            <asp:BoundField HeaderText="StateName" DataField="StateName" />
                        </Columns>
                    </asp:GridView>


text:
Q: Getting an error on Live USB boot: "(initramfs) Unable to find a medium containing a live file system" There are plenty of threads on this topic, I've tried every solution mentioned there:

*

*Different version of Ubuntu (Kubuntu 13.10, Kubuntu 12.04, Ubuntu 12.04)

*Using USB 2.0 and USB 3.0 ports

*Different Live USB creation software (Linux Live USB Creator, unetbootin, Universal USB Installer, Kubuntu Startup Disk Creator)

*Switching from IDE to ACHI

*UEFI and legacy boot

*Disabling secure boot.

*Replacing "quiet splash" with "nomodeset" in GRUB

*Plugging out hard disk

*Using different USB drives (regular USB stick, external USB HDD)

But I still get the same error every time. No difference.
My PC is a brand new computer, all systems are functioning well (I tried to install Windows 8, it works just fine).

*

*Motherboard: GA-970A-DS3P

*CPU: AMD Phenom II X4 970

*Graphic adaptor: AMD Radeon HD 5770 (Vapor-X)

What to try next?
Please help me prove to my husband that Ubuntu can be installed everywhere, I am out of ideas.

A: Having the same problem, on the same mobo, all I can suggest is contacting gigabyte support (which I've done, and am waiting for a response from). However, I'm not that hopeful of a useful answer, given that after submitting the ticket, they showed me a page highlighting the OS support being Windows only (though they also give some guidance on the same support list for using Linux, advising 3rd-party drivers).
Maybe we can hope for a BIOS upgrade. I didn't put an optical drive is the computer, so I'll have to burn the disk on my other computer, then take the drive out and transplant it, and so on... a real drag.
I'm also trying each non-USB3.0 (as I know there are reasons that wouldn't work) socket. So far I've tried the two front-panel ones that I have.
I'll update here if I either get anywhere with that, or get a useful response from support.
UPDATE: So, I managed to get it to boot from optical with working networking and USB! The same trick might work to get the USB stick to boot, given as it's probably the wonky USB that causes that problem. In BIOS Setup, make sure the IOMMU controller is set to off, and when GRUB comes up, edit the boot commands, and add the following to the kernel parameters: iommu=soft
I got this from the Ubuntu forums, at http://ubuntuforums.org/showthread.php?t=2114055&page=2

A: I solved this problem other way. However, thank you for your answer.
When installing Ubuntu I turned on emulation of USB as CD-Rom (I do not have CD-Rom). This solved the problem above. There was no any errors.
Because I have two OS (Windiws 8.1 and Xubuntu 13.10) another error appeared. It was: 'grub-efi-amd64.efi can't be installed on /target/' error as usual. Solution can be found here
For boot-repair I again turned on emulation of USB as CD-Rom, also I enabled IOMMU.


text:
Q: Selenium Grid - Webdriver - Whitescreens when running tests So typically I do these steps to run a test

*

*Start selenium grid (java -jar selenium-server-standalone-2.39.0.jar -role hub // java -jar selenium-server-standalone-2.39.0.jar -role node)

*Run a test script (node test.js // nightwatch test.js | node test.js)

*Webdriver kicks off browser and starts test

These scripts used to work and after revisiting them after a couple months I found they are now broken. I am unsure what the problem is  as I have not changed any code. Any help is greatly appreciated.
FYI
Selenium version: 2.39.0 |
OS: Mac Yosemite |
Browser: Firefox  |
Browser version: 34.0.5
After 'starting' the server and going to
http://localhost:4444/

i get
"You are using grid 2.39.0
Find help on the official selenium wiki : more help here
default monitoring page : console"
but when trying to run a night watch script or even 'nightwatch help' it fails and then gives me the error - 'Connection refused! Is selenium server started?'  (node scripts also give me a white screen)

A: Turns out this webdriver doesn't like the newer versions of firefox.
If you are experiencing issues go grab Firefox v 28.0 https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/28.0/mac/en-GB/


text:
Q: Compiler optimization when using const bool to remove debug information I have a class with a debug function named log(std::string s)
I am working on a small embedded system, therefore I want to remove unnecessary strings from the binary.
I could use #define to achieve what I want, but I think it is a bad practice. Using -Os optimization I though I could use a const bool like so:
#include <cstdio>
#include <string>
#include <iostream>

class test
{
    const bool enable_debug = false;
    void log(std::string s)
    {
        if (enable_debug) printf("%s",s.c_str());
    }

public:
    void doStuff(int i)
    {
        log("I don't want this string to appear in the binary output");
    }
};

int main()
{
    test instance;
    char input;
    std::cin>>input;
    instance.doStuff(input);
}

Please take a look at the output here: https://godbolt.org/z/qz7csf
. As you can see, the string is not removed from the assemby generated code, even though there is no way it can be used, because enable_debug is a const.

*

*So why is it still in the output?

*How can I create a toggle switch without using #define?

PS : in the end, I would like to have the bool variable external to the class, in order to switch all my classes at the same time.

A: You are using std::string. The compiler is not smart enough to see through all the std::string machinery, and I doubt it is even allowed to eliminate the std::string construction. Since the string literal is used to initialise the std::string, the literal cannot be eliminated either.
If you want to save a few bytes, perhaps consider using const char* instead.

A:

*

*So why is it still in the output?

Because the compiler didn't do deep enough analysis to find out that it is not used.

*How can I create a toggle switch without using #define?

Put debug functions, including their string literals into a separate translation unit, and don't link with that TU when you don't want them to show.

P.S.
The behaviour is undefined if debugging is enabled:

printf("%s",s);


text:
Q: Open website in Python standalone application without using browser I want to make an application which looks something like this image:

I need it to open a website on click of the button.
I used a Tkinter code which looks like this:
def openweb():
    webbrowser.open(url,new=new)
Btn = Button(root, text = "Check URL",command=openweb)

But it is opening in the default browser.
Is there some way to handle it?

A: Based on the little code you posted I guess you're using Tkinter – it doesn't come with an embeddable browser frame component, unfortunately.
You'll have to switch to something more complex like Qt (PyQt5 / PySide2) if you need an app that embeds a web browser view.


text:
Q: How do I make a div inside a grid stretch beyond the grid? I have a container, with a 12 column grid and 30px margin on left and right of the grid system

this is the change in grid layout at 768 px, see how the blue div which occupied 8 columns is now extending beyond the 8 columns, covering the margins too.

I need help with how to do this? I cannot remove the blue div out of the grid.
I have tried setting width of blue div to 100vw and left-margin to -30px, it worked but I face weird issues in different conditions in dev tools, nevertheless I want to avoid the use of vw. please help me out.

A: Use negative margins:
Eg:
margin-left: -30px;
margin-right: -30px;

Do not set WIDTH

A: I would refrain from using negative margins as they can create new problems.
I would rather use an absolute positioning.
.child-div {
    position:absolute;
    left:0;
    right:0;
}

A: use negative margins to your gird parent class. This margin should be same as your gutter space. like below snippet.

.row{
 margin-left: -30px;
 margin-right: -30px;
}
.row > .grid-8 {
 width: 60%;
 padding:0 30px;
}
.row > .grid-4 {
 width: 40%;
 padding:0 30px;
}


text:
Q: Why is the Euler characteristic of a torus with four identified points equal to -2? This does not any sense at all
If I take a torus, and take four points $x_1, x_2, y_1, y_2$ and identify $x_1$ with $y_1$ and $x_2$ with $y_2$, then I get a torus which two "singularities" you could say (or "connected holes")
A torus has one vertex, two edges and a surface. Such a torus with these four identified points has two vertices, two edges and one surface (NOT three vertices, as you can position the point of the original torus as one of those two connected points). So you should get 2 - 2 + 1 = 1
But that's wrong! And I don't know why
Apparently, you simply take here $\chi(T) - \chi(\text{two points}) = 0 - 2 = -2$
But why do we calculate it in this way? The only way I can interpret this equation above is because "you get 2 points out of 4, so 2 points get lost". But the exercise told us to construct a CW complex here!


text:
Q: Simple xamarin android application works in VS but fails on phone I have Samsung A8 phone. Android version - 7.1.1
Trying to create simple application using Xamarin on Visual Studio 2017. In the project properties -> Application I've set "Use Latest Paltform (Android 7.1 (Nougat))".
This is my source code.
Main.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:text="text1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textLizaMath" />
    <Button
        android:text="Click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnLizaMath" />
</LinearLayout>

BtnClick.cs:
namespace Core
{
    public static class BtnClick
    {
        public static string GenerateText(string text)
        {
            if (text.Equals("text1")) return "text2";
            return "text1";
        }

    }
}

MainActivity.cs
using Android.App;
using Android.Widget;
using Android.OS;

namespace Mobile
{
    [Activity(Label = "LizaN", MainLauncher = true)]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Main);
            var btn = FindViewById<Button>(Resource.Id.btnLizaMath);
            var lizaText = FindViewById<TextView>(Resource.Id.textLizaMath);
            btn.Click += (sender, e) =>
            {
                var tmpText = Core.BtnClick.GenerateText(lizaText.Text);

                lizaText.Text = tmpText;
            };

        }
    }
}

When I launch it in VS it works as expected. Then I go to bin/debug folder and copy both Mobile.Mobile.apk and Mobile.Mobile-Signed.apk to my phone. Mobile.Mobile.apk is not installing at all as saying that it is corrupted. I am able to install Mobile.Mobile-Signed.apk, but when I try to run it crashes without any meaningful error message.
What can I do?
UPDATE:
I've tried to do "archive" then it failed with the error message: "shared mono runtime is enabled", I went to project properties -> Android options and disabled "Use Shared Runtime". After that I was able to archive it. The size of the application increased 10x. I've copied all the files (not only .apk) but when I tried to install it said that the "package is corrupted" (I do not know exact English error message text but it is something like that)

A: Try to restore your nuget packages. Update xamarin.forms nuget also.


text:
Q: Interior, closure and frontier of sets I've tried to find the interior, closure and frontier of the following subsets of $\mathbb{IR}^2$:
1) A=$\{(x,y)| 1<x^2+y^2 \leq2\}$
2) B=$\ {\mathbb{IR}^2\setminus{K}}$ such that $K=\{(x,y)| x= 0\ $v$       y=0\}$
3) C=${\mathbb{IR}^2\setminus{K}}$ such that $K=\{(x,sin(\frac{1}{x}))| x > 0\}$
While I was able to solve 1) and 2), I have trouble with 3). My idea is that the interior of 3) is given by $C\setminus{L}$
such that L=$\{(0,y) | y \in [-1,1] \}$.
My idea was to show first that for each point p in L there is a sequence of elements in K with p as its limit. This would imply that each neighborhood of p contains elements from K, so p cannot be a point in the interior.
This works for p=(0,0) but I find it difficult to construct the sequence in cases where y is not zero. Is it possible to do this in an easy way or is there another, easier way?

A: Let $p=(0,y)\in L$. Since $y\in [-1,1]$, there exists a number $t>0$ such that $y=\sin t$. Then $\sin (t+2\pi n)= \sin t=y$ for each natural $n$, thus a sequence $\{(\frac 1{t+2\pi n},\sin (t+2\pi n))\}$ belongs to $K$ and converges to $p$.


text:
Q: PageView with horizontal, non-filled children It appears that PageView will always fill according to the axis of the scrolling. What would be the best approach to cater for "peeking" in a PageView?
I tried implementing a PageView.custom with the standard SliverChildListDelegate but I'm guessing that doesn't allow for arbitrary / custom sizing. I was going to start doing something custom but decided asking here is a good first start.
See the image below for an example of what I'm trying to achieve.

A: My understanding is that this is not possible with the current PageView, I've turned this into an issue: https://github.com/flutter/flutter/issues/8408

A: This feature is added in 3 Mar 2017. After @EricSeidel's request.
This can achieve by controller property of PageView.
controller: PageController(
  initialPage: 1,
  viewportFraction: 0.8,
),

PageController.viewportFraction to peek previous and next.
PageController.initialPage to display middle page when app is launched.
import 'package:flutter/material.dart';

void main() => runApp(LimeApp());

class LimeApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lime',
      home: MainPage(),
    );
  }
}

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.symmetric(
          vertical: 50.0,
        ),
        child: PageView(
          controller: PageController(
            initialPage: 1,
            viewportFraction: 0.8,
          ),
          children: [
            Container(margin: EdgeInsets.symmetric(horizontal: 10.0,), color: Colors.redAccent),
            Container(margin: EdgeInsets.symmetric(horizontal: 10.0,), color: Colors.purpleAccent),
            Container(margin: EdgeInsets.symmetric(horizontal: 10.0,), color: Colors.greenAccent)
          ],
        ),
      ),
    );
  }
}

I couldn't figure out a better way to add margin between pages and how to avoid space after last and start page.


text:
Q: Magento : get attribute value php i have tow attributes described in the image bellow :

i wanna know how to get value of it
________
_________
_________

Thanks !

A: First load the product model:
$product = Mage::getModel('catalog/product')->load(<product_id>);

then use:
$allowCustomPrice = $product->getAttributeText('allow_custom_price');

and
$minPrice = $product->getMinPrice();

Note:   I am asuming, that you will replace  with original product id, and attribute codes are "allow_custom_price" and "min_price" respectively.


text:
Q: Compile-Time MurmurHash Нашел такой код:
#pragma once

#ifndef CONSTEXPR_MURMUR3_HASH_CONSTEXPR_MURMUR3_H
#define CONSTEXPR_MURMUR3_HASH_CONSTEXPR_MURMUR3_H

#include <stdint.h>
#include <stdexcept>

namespace ce_mm3 {

    // Heavily based on sample code from
    // http://en.cppreference.com/w/cpp/concept/LiteralType
    class str_view {
    public:
        template <std::size_t N>
        constexpr str_view(const char(&a)[N])
            : p(a), sz(N - 1) {}

        constexpr char operator[](std::size_t n) const {
            return n < sz ? p[n] : throw std::out_of_range("");
        }

        constexpr uint32_t get_block(int idx) {
            int i = (block_size() + idx) * 4;
            uint32_t b0 = p[i];
            uint32_t b1 = p[i + 1];
            uint32_t b2 = p[i + 2];
            uint32_t b3 = p[i + 3];
            return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0;
        }

        constexpr std::size_t size() const { return sz; }

        constexpr std::size_t block_size() const { return sz / 4; }

        constexpr char tail(const int n) const {
            int tail_size = sz % 4;
            return p[sz - tail_size + n];
        }

    private:
        const char* p;
        std::size_t sz;
    };

    constexpr uint32_t mm3_x86_32(str_view key, uint32_t seed) {
        uint32_t h1 = seed;

        const uint32_t c1 = 0xcc9e2d51;
        const uint32_t c2 = 0x1b873593;

        const int nblocks = key.size() / 4;
        for (int i = -nblocks; i; i++) {
            uint32_t k1 = key.get_block(i);

            k1 *= c1;
            k1 = (k1 << 15) | (k1 >> (32 - 15));
            k1 *= c2;

            h1 ^= k1;
            h1 = (h1 << 13) | (h1 >> (32 - 13));
            h1 = h1 * 5 + 0xe6546b64;
        }

        uint32_t k1 = 0;

        switch (key.size() & 3) {
        case 3:
            k1 ^= key.tail(2) << 16;
        case 2:
            k1 ^= key.tail(1) << 8;
        case 1:
            k1 ^= key.tail(0);
            k1 *= c1;
            k1 = (k1 << 15) | (k1 >> (32 - 15));
            k1 *= c2;
            h1 ^= k1;
        };

        h1 ^= key.size();

        h1 ^= h1 >> 16;
        h1 *= 0x85ebca6b;
        h1 ^= h1 >> 13;
        h1 *= 0xc2b2ae35;
        h1 ^= h1 >> 16;

        return h1;
    }
}

#endif

Проблема заключается в том, что функция отрабатывает в рантайме если вызвать ее например так: printf("0x%08X", mm3_x86_32("hello", 0)) или так uint32_t hash = mm3_x86_32("hello", 0)
Нашел так же другой код:
// MurmurHash Template Metaprogramming Implementation
// https://github.com/dcoded/MurmurHash

/*
The MIT License (MIT)

Copyright (c) 2015 Denis Coady

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <cstdint>

/*

This implementation follows the following algorithm originally found at:
https://en.wikipedia.org/wiki/MurmurHash

Murmur3_32(key, len, seed)
    // Note: In this version, all integer arithmetic is performed with
    // unsigned 32 bit integers.
    // In the case of overflow, the result is constrained by the
    // application of modulo 2^{32} arithmetic.

    c1 ← 0xcc9e2d51
    c2 ← 0x1b873593
    r1 ← 15
    r2 ← 13
    m ← 5
    n ← 0xe6546b64

    hash ← seed

    for each fourByteChunk of key
        k ← fourByteChunk

        k ← k × c1
        k ← (k ROL r1)
        k ← k × c2

        hash ← hash XOR k
        hash ← (hash ROL r2)
        hash ← hash × m + n

    with any remainingBytesInKey
        remainingBytes ← SwapEndianOrderOf(remainingBytesInKey)
        // Note: Endian swapping is only necessary on big-endian machines.
        //       The purpose is to place the meaningful digits towards the low
        //       end of the value, so that these digits have the greatest
        //       potential to affect the low range digits in the subsequent
        //       multiplication.  Consider that locating the meaningful digits
        //       in the high range would produce a greater effect upon the high
        //       digits of the multiplication, and notably, that such high
        //       digits are likely to be discarded by the modulo arithmetic
        //       under overflow.  We don't want that.

        remainingBytes ← remainingBytes × c1
        remainingBytes ← (remainingBytes ROL r1)
        remainingBytes ← remainingBytes × c2

        hash ← hash XOR remainingBytes

    hash ← hash XOR len

    hash ← hash XOR (hash >> 16)
    hash ← hash × 0x85ebca6b
    hash ← hash XOR (hash >> 13)
    hash ← hash × 0xc2b2ae35
    hash ← hash XOR (hash >> 16)

*/

/* Define Magic Constants */
#define C1 0xcc9e2d51
#define C2 0x1b873593
#define R1 15
#define R2 13
#define M 5
#define N 0xe6546b64

// Forward declaration of implementation
template<std::uint32_t Hash, std::uint32_t Length, char... Args>
struct MurmurHash32Impl;

// Public interface function.
//
// Usage:
//      std::uint32_t x = MurmurHash<'H','i'>::value;
//
template<std::uint32_t Seed, char...Chars>
struct MurmurHash32 {
    enum { value = MurmurHash32Impl<Seed, 0, Chars...>::value };
};

// Covers final hash calculations, no more characters
template <std::uint32_t Hash, std::uint32_t Length>
struct MurmurHash32Impl<Hash, Length> {
    // hash ^= len;
    enum { Hash1 = Hash ^ Length };
    // hash ^= (hash >> 16);
    enum { Hash2 = Hash1 ^ (Hash1 >> 16) };
    // hash *= 0x85ebca6b;
    enum { Hash3 = Hash2 * 0x85ebca6b };
    // hash ^= (hash >> 13);
    enum { Hash4 = Hash3 ^ (Hash3 >> 13) };
    // hash *= 0xc2b2ae35;
    enum { Hash5 = Hash4 * 0xc2b2ae35 };
    // hash ^= (hash >> 16);
    enum { Hash6 = Hash5 ^ (Hash5 >> 16) };

    enum { value = Hash6 };
};

// Calculates 1 remaining byte
template <std::uint32_t Hash, std::uint32_t Length, char A>
struct MurmurHash32Impl<Hash, Length, A> {
    // remainingBytes ← remainingBytes × c1
    enum { K0 = 0x00000000 ^ A };
    // remainingBytes ← remainingBytes × c1
    enum { K1 = K0 * C1 };
    // remainingBytes ← (remainingBytes ROL r1)
    enum { K2 = (K1 << R1) | (K1 >> (32 - R1)) };
    // remainingBytes ← remainingBytes × c2
    enum { K3 = K2 * C2 };
    // hash ← hash XOR remainingBytes
    enum { Hash1 = Hash ^ K3 };
    // No more string, just final hash manipulations
    enum { value = MurmurHash32Impl<Hash1, Length + 1>::value };
};

// Calculates 2 remaining bytes
template <std::uint32_t Hash, std::uint32_t Length, char A, char B>
struct MurmurHash32Impl<Hash, Length, A, B> {
    enum { K0 = 0x00000000 ^ (B << 8) };
    enum { K1 = K0 ^ A };
    // remainingBytes ← remainingBytes × c1
    enum { K2 = K1 * C1 };
    // remainingBytes ← (remainingBytes ROL r1)
    enum { K3 = (K2 << R1) | (K2 >> (32 - R1)) };
    // remainingBytes ← remainingBytes × c2
    enum { K4 = K3 * C2 };
    // hash ← hash XOR remainingBytes
    enum { Hash1 = Hash ^ K4 };
    // No more string, just final hash manipulations
    enum { value = MurmurHash32Impl<Hash1, Length + 2>::value };
};

// Calculates 3 remaining bytes
template <std::uint32_t Hash, std::uint32_t Length, char A, char B, char C>
struct MurmurHash32Impl<Hash, Length, A, B, C> {
    enum { K0 = 0 ^ (C << 16) };
    enum { K1 = K0 ^ (B << 8) };
    enum { K2 = K1 ^ A };
    // remainingBytes ← remainingBytes × c1
    enum { K3 = K2 * C1 };
    // remainingBytes ← (remainingBytes ROL r1)
    enum { K4 = (K3 << R1) | (K3 >> (32 - R1)) };
    // remainingBytes ← remainingBytes × c2
    enum { K5 = K4 * C2 };
    // hash ← hash XOR remainingBytes
    enum { Hash1 = Hash ^ K5 };
    // No more string, just final hash manipulations
    enum { value = MurmurHash32Impl<Hash1, Length + 3>::value };
};

// Calculates a full block (4 bytes)
template <std::uint32_t Hash, std::uint32_t Length, char A, char B, char C, char D, char...Tail>
struct MurmurHash32Impl<Hash, Length, A, B, C, D, Tail...> {
    // k ← fourByteChunk
    enum { K0 = (D << 24) | (C << 16) | (B << 8) | A };
    // k ← k × c1
    enum { K1 = K0 * C1 };
    // k ← (k ROL r1)
    enum { K2 = (K1 << R1) | (K1 >> (32 - R1)) };
    // k ← k × c2
    enum { K3 = K2 * C2 };
    // hash ← hash XOR k
    enum { Hash1 = Hash ^ K3 };
    // hash ← (hash ROL r2)
    enum { Hash2 = (Hash1 << R2) | (Hash1 >> (32 - R2)) };
    // hash ← hash × m + n
    enum { Hash3 = Hash2 * M + N };
    // Calculate rest of string and final hash manipulations
    enum { value = MurmurHash32Impl<Hash3, Length + 4, Tail...>::value };
};

Можно ли второй код как-то изменить, чтобы его можно было использовать передавая его в  качестве аргумента для функции и не приходилось создавать отдельно constexpr переменную для значения хеша? Так как передавать по одному символу в темплейт MurmurHash32<0, 'h', 'e', 'l', 'l', 'o'> не очень удобно, если работать с большими строками и огромным их кол-вом.

A: #include  <type_traits>
// ...
printf("0x%08X",  std::integral_constant<uint32_t,mm3_x86_32("hello", 0)>());

См. описание std::integral_constant<>


text:
Q: Eclipse. Can not open with Android Layout Editor I wonder, everytime I try to open the main.xml file in the res/layout directory, eclipse stop responding. The problem does not occur if I open the file by right clicking it and select other method than Android Layout Editor.
I've searched through the net, and some say that by updatin the java version, the problem is gone. I've installed JDK 6u24, and set my Eclispe to use that editor (Window > Preferences > Java > Installed JREs). But still I could not open the main.xml with Android Layout Editor. I wonder why?
I'm using Eclipse Helios and ADT 8.0.1.
Thank you

A: Updating to the latest ADT should help.


text:
Q: GTA V Vehicle Storage How many vehicles can I store in Trevor's hangar? I know you can store 2 vehicles in each of the main character's safe houses, but for example if I stored 1 aircraft and a truck in trevor's hangar, will one of them disappear?

A: I found this on a GameFAQs thread.
The original post is a bit long winded, so here is a summary:
Land Vehicles
They're simply stored in your garages as you expect, regardless of whether you stole them or bought them.  If you take one out and crashes it, you'll have to get another.
Other Vehicles  (helipads, hangars, and boat docks)
You can store stolen vehicles as per land vehicle.  However, purchased vehicles can be spawned infinitely, but they immediately replace the existing vehicle inside the storage compartment.
e.g.)  If you stored a stolen jet in a hanger, but decide to summon one of your purchased planes, your jet gets replaced instantly.


text:
Q: Writing codes in local namespace is slower than in global in PyPy3 I tested the codes below with time function of bash.
# test_local.py
def main():
    n = 10 ** 7
    mod = 10 ** 9 + 7
    x = 0
    for i in range(n):
        x += i
        x %= mod

if __name__ == "__main__":
    main()

# test_global.py
n = 10 ** 7
mod = 10 ** 9 + 7
x = 0
for i in range(n):
    x += i
    x %= mod

Results:
python3 test_local.py  1.03s user 0.02s system 91% cpu 1.139 total
python3 test_global.py  1.92s user 0.01s system 98% cpu 1.956 total

pypy3 test_local.py  0.26s user 0.12s system 36% cpu 1.034 total
pypy3 test_global.py  0.13s user 0.03s system 97% cpu 0.161 total

Env:
CPython3 (3.8.2), PyPy3 (7.3.0)

Why is test_local.py slower than test_global.py in PyPy3, although the result is the opposite in CPython?

Update
Following the answer by Armin Rigo, I tried another code below.
It works faster while being kept most parts in main().
#  test_global_constant.py
MOD = 10 ** 9 + 7

def main():
    n = 10 ** 7
    x = 0
    for i in range(n):
        x += i
        x %= MOD

if __name__ == "__main__":
    main()

Results:
python3 test_global_constant.py  1.08s user 0.01s system 99% cpu 1.099 total

pypy3 test_global_constant.py  0.12s user 0.03s system 95% cpu 0.164 total

A: The answer is probably in the "%" operator.  PyPy has got a JIT that looks at one loop at a time (including all calls done by that loop, if any).  In the first version of the code, the loop is compiled using "x %= mod" where the value of "mod" is not known to be a constant---it's just a value that comes from earlier in the function.  It might look constant, but isn't completely: if you run the programs using, say, some debugging hooks, then you could conceivably have changed its value, before even entering the loop---i.e. before the JIT kicks in.  For this reason, the JIT doesn't optimize for local variables being constant; additionally, this is to some extent the rare case: local variables are commonly not constant.
On the other hand, in the second case, the "x %= mod" uses the global variable "mod".  Global variables are more commonly constants (for example, most global variables are actually functions or classes or numeric constants).  So the JIT in PyPy contains special code to support that.  Global variables are internally more complicated than local variables: they will remember if they have been changed, and as long as they haven't, then they will record which pieces of assembler have been generated assuming they are constant.  So, as long as you don't change "mod", then the "x %= mod" will be compiled by the JIT assuming "mod" is exactly the constant 1000000007.
Why does it make a difference?  Because division and modulo by a constant are replaced with clever code using a multiplication instead, using a well-known trick.  GCC or any good C compiler uses a similar trick too.  If you are interested in the details, the code replacing division by a constant with something based on multiplication is here (UINT_MUL_HIGH does "(x * y) >> 64" with unsigned 64-bit numbers x and y, which is a single assembler instruction):
https://foss.heptapod.net/pypy/pypy/blob/branch/default/rpython/jit/metainterp/optimizeopt/intdiv.py


text:
Q: How to handle unique cell action with mvvm I have unique cell in UITableView, which has two buttons. I need to bind these actions to viewModel of controller. I bind view with view model in this way:
func attach(wrapper: Attachable<ViewModel>) -> ViewModel {
    self.viewModel = wrapper
    loadViewIfNeeded()
    let viewModel = self.viewModel.bind(bindings: bindings)
    return bind(viewModel: viewModel)
}

So, when loadViewIfNeeded() method invokes, I still don't have any cells from data source. That's why I can't create bindings from cell's buttons.
I tried to use delegate and relate on this way, but I think I missed better solution:
protocol ProfileActionsViewCellDelegate {
     var addFriendButton: UIButton { get }
}

code inside cell
func bind(to viewModel: ProfileActionsViewModel) {
    addFriendButton.rx.tap
        .do(onNext: { [unowned self] _ in self.delegate?.addFriendButton.sendActions(for: .touchUpInside) })
        .debug()
        .subscribe()
        .disposed(by: disposeBag)
}

mvvm profile example


text:
Q: Typescript Generic type not assignable error Trying to create a generic but it's showing error: Type "User[]" is not assignable to type T[]
not able to understand what is wrong in doing this-
interface User {
    name: string,
    age: number
}

interface Movie {
    title: string,
    language: string
}

function getItems<T>(arg: number|string): T[] {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a: User[] = getItems<User>('user_list');

A: You should use function overloads for your case instead of generics.
Note that the signature of the function with the implementation will be hidden by the compiler.
function getItems(arg: string): User[];
function getItems(arg: number): Movie[];
function getItems(arg: number | string) {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a = getItems('user_list');

A: The problem is that your function is not really generic. When using a generic parameter, you can't return a specific type, you need to respect the generic parameter that was passed to you. A function signature that would do what you want would be one using overloads
function getItems(arg: string): User[]
function getItems(arg: number): Movie []
function getItems(arg: number|string): User[] | Movie []  {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
         return useList;
    } else {
         return movieList;
   }
}


text:
Q: How to run php code into .html file under Nginx? How can I allow nginx to parse php code into a file with .htm extension, at a specific directory?
I need this, because I migrated from apache, and changing all file extensions would be a big headache.
thanks.

A: This snippet from default nginx.conf, replace .php to .htm in location ... and enjoy.
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}


text:
Q: How to make each Div is a section that occupies the entire height of Body? How to implement the following:
I want a div spans the width and height of the body, and when you scroll down you see another Div occupy the same width and height of the body, as shown in the following page
https://www.lexcorp.io/#/home
How is this possible?

A: Use viewport units.

Viewport-percentage lengths defined a length relatively to the size of viewport, that is the visible portion of the document. Only Gecko-based browsers are updating the viewport values dynamically, when the size of the viewport is modified (by modifying the size of the window on a desktop computer or by turning the device on a phone or a tablet).

div {
height:100vh;
max-height:100vh;
}

CanIUse.com - Viewport Units

A: sorry my initial code was crap. I noticed that original website didn't even use a scrollbar. here's a modified version that uses transforms and mousewheel for extra smoothness.
https://jsfiddle.net/foreyez/f48j27f0/
var pageSize = $(window).height();
$( window ).resize(function() {
   pageSize = $(window).height();
});
$('div').bind('mousewheel', function(e) {
    if(e.originalEvent.wheelDelta / 120 > 0)
    {
    //up
     $('#container').css('transform','translateY(0px)');
    } else {
    //down
        $('#container').css('transform','translateY(-' + pageSize + 'px)');
    }
});

A: If browser support is an issue, you can also do:
html,
body {
  height: 100%;
}


text:
Q: Towers of Hanoi recursive/iterative hybrid I have to make a iterative solution to the Towers of Hanoi problem. I am trying to convert a tail recursive call to an iterative one. I am following an algorithm I found in my textbook to transform it. I followed this algorithm and even though my code is similar to the recursive variant my output doesn't match the designated form. Now from what the book tells me, having a recursive call with an iterative is strange, but valid.
public class DemoIterative
{
    public static void TowersOfHanoi(int numberOfDisks,
    String startPole, String tempPole, String endPole)
    {
        while (numberOfDisks > 0)
        {
            /** MUST GO 1, 3, 2, 1 */
            TowersOfHanoi(numberOfDisks - 1, startPole, endPole, tempPole);
            System.out.println(startPole + " -> " + endPole);
            numberOfDisks = numberOfDisks - 1;
            startPole = tempPole;
            tempPole = startPole;
        }
    }

    public static void main(String[] args)
    {
        DemoIterative demoIterative = new DemoIterative();
        System.out.println("Enter amount of discs: ");
        Scanner scanner = new Scanner(System.in);
        int discs = scanner.nextInt();
        demoIterative.TowersOfHanoi(discs, "A", "B", "C");
    } // end of main
} // end DemoIterative

Now the output I am getting from this is:
A to C,
A to B,
C to B,
A to C,
B to B,
B to C,
B to C
I should be getting this (tested from recursive original):
A to C,
A to B,
C to B,
A to C,
B to A,
B to C,
A to C
This is the algorithm I am using:
While numberOfDisks is greater than 0, move disk from startPole to endPole, numberOfDisks--, exchange the contents of tempPole and startPole.
Now is this possible? If so, is there a problem with my algorithm or am I printing it wrong?

A: You have a problem with your algorithm.  Most important for your own understanding of this, slap a print statement at the top of your routine and print out the arguments.  Also insert one at the bottom of the loop to help track that execution.
To summarize, I don't think you understand the call tree you've created, and I think you should trace it to see.  There are applications that will use such a tree, but I don't think that this what you want for this assignment.
There area couple of structural problems.  For one, when you get to the bottom of the loop, you set startPole = tempPole, and follow that with a useless assignment back -- this wipes out the old startPole value; it does not exchange them.
Next, your loop + recursion structure is strange.  First, you've used a while loop where the semantics clearly indicate a for -- you know how many times you'll iterate when you enter the loop.  When you first call this with, say, 5 disks, the numberOfDisks (I'll call it N) = 5 iteration will loop 5 times.  Each iteration recurs with N = 4, 3, 2, 1, respectively.
Now, the N=4 instance will do likewise: recurring with N=3, 2, 1.  This gives you two instances at N=3.  Continuing, you'll get three instances at N=2, and four at N=1, for a total of 11 calls to your function.  Since only four of these involve moving a one-disk stack (for a tower of 5 disks, you need several more), I think you've incorrectly implemented whatever you had in mind.


text: Q: What books should I refer to while preparing for mathematical Olympiads, specifically IMO? I am from India and will be preparing for RMO (Regional Mathematics Olympiad) and INMO (Indian National Mathematics Olympiad). I need the best books for being able to qualify these and appear for IMO.


text:
Q: Sentence from Seneca's Consolation to Helvia In Consolation to Helvia, a letter Seneca wrote to his mother while in exile, the English translation says:

I don't have doubt that I shall have more influence over you than your grief, than which nothing has more influence over the wretched.

(p. 40, On the Shortness of Life, Penguin, 2005)
I am not sure what he means exactly by adding that second part to the sentence. I understand the part before the comma: I will have more influence over you than your grief in my effort to console you. But the second part seems a bit odd. Does he mean it as a continuation of the first part, like he's saying that he will have more influence that anything might have over the wretched? Does he mean the wretched are easily influenced?


text:
Q: WPF routed event firing but not being handled by handler I have the following routed event:
public static readonly RoutedEvent ItemMouseDownEvent = EventManager.RegisterRoutedEvent(
    "ItemMouseDown", RoutingStrategy.Bubble, typeof(ItemMouseDownEventHandler), typeof(BindableGrid));

public delegate void ItemMouseDownEventHandler(object sender, ItemMouseDownEventArgs e);

public class ItemMouseDownEventArgs : RoutedEventArgs
{
    public object Item { get; set; }
}

public event ItemMouseDownEventHandler ItemMouseDown
{
    add { AddHandler(ItemMouseDownEvent, value); }
    remove { RemoveHandler(ItemMouseDownEvent, value); }
}

And I'm firing it like so (this code does get called, I set a breakpoint):
var args = new ItemMouseDownEventArgs
{
    Item = ((FrameworkElement)sender).DataContext,
    RoutedEvent = ItemMouseDownEvent
};
RaiseEvent(args);

I have a XAML page consuming the event:
<local:BindableGrid x:Name="starSystemMap" ArraySource="{Binding SpaceObjectArray}" CellSize="64" BackgroundImage="/Images/Starfield.png" ItemMouseDown="starSystemMap_ItemMouseDown">
...
</local:BindableGrid>

And the event handler (WIP):
private void starSystemMap_ItemMouseDown(object sender, BindableGrid.ItemMouseDownEventArgs e)
{
    switch (e.Item)
    {
        case null:
            MessageBox.Show("Space... the final frontier... is very, very empty...");
            break;
    }
}

Now even though the event is being raised, the event handler never gets called - why is this? How can I get the event handler to be called for my custom routed event?

A: I had additional BindableGrid overlays on top of the BindableGrid I was trying to click; I had to set IsHitTestVisible="False" on the overlays so the click would go "through" to the grid I wanted to click.


text:
Q: Printing sharepoint list libraries using Silver light and C sharp I am trying to print the files in the sharepoint document libraries. Can any one help me to print the files without opening the files.

A: you can use the solution provided in following post it is given for pdf but should work for others as well
Print existing PDF (or other files) in C#


text:
Q: Testing significant effect in 2 by 2 factor design on a binary outcome I have 4 groups each consisting of 1000 recent college graduates, and I am studying employment immediately after graduation. 2 groups took a business class in college, and 2 groups took a math course in college. Group 1 is a control that has taken neither a business class nor a math course in college. I want to conduct a statistical analysis to find if either class was significant in increasing the graduate in obtaining a job immediately after school. Here's the data:
Group 1: No Math, No Business
1000 subjects, 50 employed
Group 2: No Math, Yes Business
1000 subjects, 60 employed
Group 3: Yes Math, No Business
1000 subjects, 75 employed
Group 4: Yes Math, Yes Business
1000 subjects, 100 employed

A: This seems like a classic problem for logistic regression.  Rather than specifying these groups, turn math and business coursework into predictors for employment status.  This is easy to code up in pretty much whatever statistical software you have around, although you'll want to look into different contrasts (it sounds like you'd want to use treatment contrasts with "no class" set as the reference level).

A: Self-selection problem need to be addressed here. People who choose to take business classes might be more likely to get a job. So, the sample you have is not random, and the inferences you draw might be incorrect. Heckman procedure is used to correct to self-selection bias. I am not sure if it is applicable for discrete dependent variable though.

A: If @EEE's concern can be addressed and you proceed with an hypothesis test, then rather than logistic regression I'd recommend a chi-square test.  For a person fairly new to statistical testing, it'll be dramatically easier to conduct, interpret, and explain to an audience.  Plus I think it'll give you just about as much information.

A: One of the more basic approaches you could take is a two-way ANOVA (Page from U Delaware), using Math Class = {Y, N} and Business Class = {Y, N} as your two treatments. You would then perform an analysis of variance on the dependent variable (number of people employed) to determine whether taking a math/business class has an impact on how many people were able to get jobs.
One thing you may want to watch out for, however, are some of the assumptions of ANOVA, which may not be appropriate. You can find the assumptions on this wikipedia page. Normality of the residuals may be questionable if there was no random assignment, in which case, there are non-parametric methods.

A: you could use the Agresti-Caffo simultaneous confidence interval or (Simultaneous Score Intervals for Difference of Proportions) to compare differences in proportions (Agresti et al. 2008. Simultaneous confidence intervals for comparing binomial parameters, Biometrics 64, 1270-1275).
The corresponding R code is available in http://www.stat.ufl.edu/~aa/cda/software.html


text:
Q: matlab create histogram from the map I have a map in matlab :
containers.Map handle
Package: containers

Properties:
      Count: 3
    KeyType: 'char'
  ValueType: 'double'

for example:
keys(dict)
ans =
    'a'    'b'    'c'
values(dict)
ans =
    [1]    [1]    [2]

Is there an easy way to build a histogram plot from this map.
What I need is something like this:
I tried something like this: hist(keys(dict), values(dict)), but the problem is that keys(dict) and values(dict) is a cell and hist is only working with vectors.
Is there an easy way to create a histogram out of a map, or I should iterate through keys and values?

A: Just found the right answer:
bar( cell2mat( values(dict) ) )

Trying to find how to add a nice legend to the bar...

A: To add the keys as x labels use:
set(gca,'XTick',[1:length(keys(dict))])
set(gca,'xticklabel', keys(dict))


text:
Q: Version code 2 on first release permitted? While uploading my apk in play console i accidently included an incomplete version of my app. Since it had version code 1, google refused to accept my complete apk as it had the same version code. So i changed the code to 2 and rolled it out for production. Can this lead to the app being rejected?

A: No, the versionCode of the first APK can be anything.


text:
Q: Getting variables value for an object instance using Javascript I have this code snippet from MDN
I then added a bit of my own code to attach a jQuery click event to a paragraph.
Maybe it is best to show the example:

 function Person(first, last, age, gender, interests) {
      this.name = {
        'first': first,
        'last' : last
      };
      this.age = age;
      this.gen = gender;
      this.int = interests;
      this.nationality = "English";
      this.bio = function() {
        alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.int[0] + ' and ' + this.int[1] + '.');
      };
      this.greeting = function() {
        alert('Hi! I\'m ' + this.name.first + '.');
      };
      this.tt = function() {
        alert('Hi! I\'m ' + this.gen + '.');
      };

      this.init= function() {
        $("p").click(function(){
         alert('Hi!'); //works fine
          alert('Hi! I\'m ' + this.name.first + '.');//obj.html:34 Uncaught TypeError: Cannot read property 'first' of undefined
         });
      };

      this.init(); //Bind to the P tag using jQuery click event

    }
    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    console.log(Person);
    person1.bio();

My first paragraph.

So when I click on the P element I get the alert Hi! followed by the uncaught error message.
How do I get the second alert to read, "Hi! I'm Bob"

A: If you wish to retain the reference to the Person object, then you need to bind the jQuery callback function with the thisBinding.
this.init= function() {
     $("p").click(function(){
      alert('Hi!'); //works fine
      alert('Hi! I\'m ' + this.name.first + '.');
     }.bind(this));//binding this prevents the error
  };

A: There are a few ways to solve your problem. this keyword in JavaScript is tricky. The core of your problem is that the this is not what you think it is. See How does the "this" keyword work? for more details.
1) Cache the this into a variable in pervious scope.
this.init = function () {
  var self = this;
  $("p").click(function () {
    alert('Hi!');
    alert('Hi! I\'m ' + self.name.first + '.');
  });
};

2) bind this into the function that's being invoked
this.init = function () {
  var handleClick = function () {
    alert('Hi!');
    alert('Hi! I\'m ' + self.name.first + '.');
  };
  handleClick = handleClick.bind(this);
  $("p").click(handleClick);
};

A: You need to bind this to the anonymous function you passed in jquery click() function.

function Person(first, last, age, gender, interests) {
  this.name = {
    'first': first,
    'last' : last
  };
  this.age = age;
  this.gen = gender;
  this.int = interests;
  this.nationality = "English";
  this.bio = function() {
    alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.int[0] + ' and ' + this.int[1] + '.');
  };
  this.greeting = function() {
    alert('Hi! I\'m ' + this.name.first + '.');
  };
  this.tt = function() {
    alert('Hi! I\'m ' + this.gen + '.');
  };

  this.init= function() {
     $("p").click(function(){
      alert('Hi!'); //works fine
      alert('Hi! I\'m ' + this.name.first + '.');
     }.bind(this));
  };

  this.init(); //Bind to the P tag using jQuery click event

}
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
console.log(Person);
person1.bio();

My first paragraph.

A: Another way to do this is to just declare a variable name outside the jquery function and use it inside the function
this.init = function() {
    var name = this.name;
    $("p").click(function(){
        alert('Hi!');
        alert('Hi! I\'m ' + name.first + '.');
    });
};

A: Be careful when using this for variables. This, in your code refers to thePersoninstance. As soon as you create a new functionthisno longer references thePersonfunction, but thethis.initfunction, thusPerson` no longer exists in this context.
Rather user var name... when using variables, then you will be able to reference it in another context or function:

<!DOCTYPE html>

    <title>Page Title</title>

My first paragraph.


text:
Q: Ruby EXIFR can not find file I am trying to use the EXIF reader and I continue to get the error "Errno::ENOENT: No such file or directory"
I have checked and the file most certainly exists in the location I am directing it to:
<%= EXIFR::JPEG.new('/system/datas/5/original/IMG_0011.JPG').date_time %>

(This is where paperclip puts the files upon uploading)
Any ideas on why I continue to receive this error. I think the problem may not be finding the file but that error is masking the real issue.
I need to retrieve the EXIF data from picture files. Any other ideas are welcome. I am using paperclip to upload files.
Thanks!

A: Does this work for you
<%= EXIFR::JPEG.new(Rails.root.join('public/system/datas/5/original/IMG_0011.JPG')).date_time %>

A: The path you provided to EXIFR is a URL, not a path on the system. Try it:
$ ls /system/datas/5/original/IMG_0011.JPG

The file is stored in the public directory of your rails app, so do something like:
EXIFR::JPEG.new(Rails.root.join('public', '/system/datas/5/original/IMG_0011.JPG')).date_time

But paperclip also provides a method to access the path, and that is through the path method:
@model.data.path


text:
Q: If I want 2 css framework like bootstrapvue & vuetify use same project I want 2 CSS framework use my existing nuxtjs project - anyone questions why to use 2 CSS framework one vuejs project -
answer this question - I want, my website web version and mobile version, i use web version is boostrapvue its awsome for web version - or vuetfy is the better mobile version.
anyone plz help, it's possible

A: Why not, you can use both the frameworks easily. But the problems include clashing of css classes. Although both have different components, they can still lead to some unexpected design. I would recommend using a single css framework, but if you are adamant about using two CSS frameworks, it is not a heck. Just install both these libraries and include in main.js/app.js file.
For bootstrap vue,
npm install vue bootstrap-vue bootstrap

For vuetify,
vue add vuetify

Then include in your main.js/app.js using,
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'

Vue.use(Vuetify)
Vue.use(BootstrapVue)

Hope it helps!


text:
Q: .NET Modify file metadata such as File Version We all know how to get the File Version in C#:
var info = FileVersionInfo.GetVersionInfo(FilePath);
Console.WriteLine($"File Version: {info.FileVersion}");

How can you set/modify that information on any arbitrary file.
NOTE please don't refer to the assembly info, this is for any file, not the resulting exe/dll from compilation of the C# file. I.e. how do you open an arbitrary file and set/change the FileVersion/ProductVersion or any other metadata on it? (even if possible via C/unsafe code it is still acceptable).

A: First of all, this won't work with signed files.

Use a hex editor or Visual Studio, to open the file in a Binary editor.
Search for the phrase:

VS_VERSION_INFO

(note, in 16-bit, so it's shown as V.S._.V.  .. etc.)
Search and edit the metadata property you want to edit.

Windows itself also has a build in option to modify some metadata, referred as personal info:

Click the "remove prperties..."

Not sure about the file info though, it might be tougher since it's a bigger security risk when it's overwritten that easy.


text:
Q: C# Test specific internet connection availability when we have multiple internet connections I have a computer with a few different internet connections. LAN, WLAN, WiFi or 3G. All of these are active and the machine can use any of them.
Now I want to tell my application to use one of the available connections. For example I want to tell my application to use only WiFi while other software might use something else.
And before telling application we select a internet and want to check that selected internet is working fine or not. So how we can check selected internet is connected.

A: Check the answers here:
Choose one of many Internet connections for an application
However, is there any reason to specify network interface? If there are several network adapters, the WebClient or any other implementation will use interface with better metrics which you can retrieve by following code:
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
    Console.WriteLine(adapter.Speed);
}

Adapter with better speed will be used by default, so you don't have to be afraid that 3G will be used instead of Wi-Fi or Wi-Fi instead of the Ethernet.


text:
Q: Does Cassandra have a sleep cql query? I'm looking for the equivalent of SELECT pg_sleep(t) in PostgreSQL or waitfor in t-SQL. Does that exist in Cassandra cql?

A: Not with any builtin function. Its pretty hard to do that with a UDF as well with the whitelists and blacklists:
whitelistedPatterns
"com/datastax/driver/core/",
"com/google/common/reflect/TypeToken",
"java/io/IOException.class",
"java/io/Serializable.class",
"java/lang/",
"java/math/",
"java/net/InetAddress.class",
"java/net/Inet4Address.class",
"java/net/Inet6Address.class",
"java/net/UnknownHostException.class", // req'd by InetAddress
"java/net/NetworkInterface.class", // req'd by InetAddress
"java/net/SocketException.class", // req'd by InetAddress
"java/nio/Buffer.class",
"java/nio/ByteBuffer.class",
"java/text/",
"java/time/",
"java/util/",
"org/apache/cassandra/cql3/functions/JavaUDF.class",
"org/apache/cassandra/cql3/functions/UDFContext.class",
"org/apache/cassandra/exceptions/",
"org/apache/cassandra/transport/ProtocolVersion.class"

blacklistedPatterns
"com/datastax/driver/core/Cluster.class",
"com/datastax/driver/core/Metrics.class",
"com/datastax/driver/core/NettyOptions.class",
"com/datastax/driver/core/Session.class",
"com/datastax/driver/core/Statement.class",
"com/datastax/driver/core/TimestampGenerator.class", // indirectly covers ServerSideTimestampGenerator + ThreadLocalMonotonicTimestampGenerator
"java/lang/Compiler.class",
"java/lang/InheritableThreadLocal.class",
"java/lang/Package.class",
"java/lang/Process.class",
"java/lang/ProcessBuilder.class",
"java/lang/ProcessEnvironment.class",
"java/lang/ProcessImpl.class",
"java/lang/Runnable.class",
"java/lang/Runtime.class",
"java/lang/Shutdown.class",
"java/lang/Thread.class",
"java/lang/ThreadGroup.class",
"java/lang/ThreadLocal.class",
"java/lang/instrument/",
"java/lang/invoke/",
"java/lang/management/",
"java/lang/ref/",
"java/lang/reflect/",
"java/util/ServiceLoader.class",
"java/util/Timer.class",
"java/util/concurrent/",
"java/util/function/",
"java/util/jar/",
"java/util/logging/",
"java/util/prefs/",
"java/util/spi/",
"java/util/stream/",
"java/util/zip/"

If you REALLY need it and are willing to do terrible things something like:
CREATE OR REPLACE FUNCTION sleep (time int)
  CALLED ON NULL INPUT RETURNS int LANGUAGE java AS
  '
  long start = System.currentTimeMillis();
  while (System.currentTimeMillis() < start + time);
  return time;
  ';

but its a pretty horrible idea since its a tight loop. There may be something that you can do to introduce pause in loop but the blacklists are pretty restrictive from my cursory look over.


text:
Q: Best way to load images for OpenGL in NaCl What is the best way to load the actual image data from .png or .jpg files for use in OpenGL within Chromes NaCl??
Is there a PPAPI feature that can do this?  I didn't think there was.
I was thinking about using javaScript to load the Image data and pass it back to NaCl.  Is this possible?  If so what javaScript method do you use to pass the Image data to NaCl, cuz I don't think postMessage is what I want for that?
Frustrating how there must be an image loading backend to Chrome but no way to access it via NaCl.

A: There are 3 ways of doing it.

*

*You can use nacl-mounts library to load files from server and store it locally to use it within your app.

*You can also see GetUrl example in nacl sdk to load files from server and directly use it.

*There is also a new example in pepper_21 which loads texture and set it to a cube.

A: If you have the file in Javascript you can also create a blob url and then load that from NaCL using GetUrl as described.


text:
Q: 404 error handling through .htaccess not working im actually new to .htaccess concept, and i've read some articles about it. The thing is i wanna control a 404 document not found error.i have placed the .htaccess file on the root directory and also i have created a error_pages folder in which i have my 404.html file. And i have also checked my AllowOveride line and its set to All. I have the following line in the .htaccess file but its not working and its saying:

The requested URL /Add Friend/abc.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Now i've checked many similar questions but they went up through my head.
.htaccess file:
ErrorDocument 404 /error_pages/404.html