text:
Q: Name of code style When I develop my PHP code I always write it a certain way, I use the following to define my variables:
$sString
$aArray
$bBoolean
$oObject
$mMixed
$iInteger
$a_sString/aArray/bBoolean ect (for function argument)

Hence s, a, b, o, m, i ect.  I know there is a name to call this type of writing, but I have totally forgotten it.
My question: What is this called?

A: It's similar to "Hungarian", but it's actually PAHN.

A: It's called hungarian notation.
Note: There are many different "flavors" of Hungarian. "Hungarian" by itself describes the practice of prefixing variable names with a few characters that provide additional information about the contents of the variable. What kind of information is what defines the actual flavor in use.

A: Hungarian notation is an identifier naming convention in computer programming, in which the name of a variable or function indicates its type or intended use.

A: this is some kind of hungarian notation, but some kind (seems to be very close to pahn) of the missunderstood and useless one*. take a look at joels great article about hungarian notation and how to use it the correct way.
*just using a prefix to see what type a variable should be isn't very useful - it you be way better to prefix them with something that defines what kind of variable this is. an example:
lets assume you have some variables containing different currencys (euros and dollars, in cents for your case as you havnt given a prefix fpr floats, so i'll use integers) and a function to ververt one to another. in your case:
$iPriceAmerica = 500;

// would be the right way
$iPriceEurope = iEuroFromDollar($iPriceAmerica);

// looks right and is possible as both are integers
// but is wrong (correct executable code, but doesn't give the expected result)
$iPriceEurope = $iPriceAmerica;

with correct hungarian notation, using dol_ for dollars and eur_ for euros:
$dol_PriceAmerica = 500;

// would be the right way
$eur_PriceEurope = eur_from_dol($dol_PriceAmerica);

// looks wrong - eur isn't dol, there muste be some kind of conversion
$eur_PriceEurope = $dol_PriceAmerica;


text:
Q: Preload whole page I would like to preload everything before HTML even starts displaying.
The problem is with loading external fonts, images etc.
I was trying to make simple jquery function with:
CSS:
html { display:none; }

jQuery:
$(window).load(function() {
  $('html').css('display', 'block');
});

But that doesn't really work.
The main reason that I want to preload is that I have font animation on the page start and when the font isn't loaded and CSS animation is fired it looks a little buggy.

A: load() as a shortcut for on('load') is deprecated:
Try using
$(window).on('load', function() {
  $('html').css('display', 'block');
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert list into comma separate values inside multiline sql query for python I have a method like this:
def build_query(self, ids):
    return '''select
        d.name as degree,
        fs.student_id
        from form_status fs
        left join form_fills fc
        on fs.id = fc.form_fills_id
        ...
        where fs.student_id in (*ids);
    '''

and ids is a list that looks like this: [1,2,3,100,10000]
How do I do this properly? I like the triple quoted strings because they allow me to indent the sql string and not look weird. Can I maintain this?

A: Since tuples in Python happen to be enclosed in parentheses too, you can convert ids to a tuple in an f-string to make the code look aesthetically to your expectation:
def build_query(self, ids):
    return f'''select
        d.name as degree,
        fs.student_id
        from form_status fs
        left join form_fills fc
        on fs.id = fc.form_fills_id
        ...
        where fs.student_id in {(*ids,)};
    '''


text:
Q: Updatelinks in Powerpoint from identical workbook in different directory (through vba?) I am working on linking charts in powerpoint (ppt) slides to charts in Excel (xls) workbooks. This works fine without vba code, as I just use paste special to  create a link. The problem is however when I change the directoy of the ppt as well as the xls, as the ppt will still try to update the data from the xls in the old directory. My goal however would be to share these files, so everyone can just update their ppt with their xls.
So, to put it shortly, I want to update the ppt, but choose a different workbook (with a different directory). This workbook will be identical to the old one in terms of structure, just with diffeerent data.
I know there is the method updatelinks, but there doesn't seem to be any way to choose a different directory with this method. Does anyone have any tips?

A:
So, to put it shortly, I want to update the ppt, but choose a different workbook (with a different directory). This workbook will be identical to the old one in terms of structure, just with different data.

TRIED AND TESTED with MS-OFFICE 2010
I have commented the code so that you will not have a problem understanding it. If you still do then feel free to ask.
Option Explicit

Sub UpDateLinks()
    '~~> Powerpoint Variables/Objects
    Dim ofd As FileDialog
    Dim initDir As String
    Dim OldSourcePath As String, NewSourcePath As String

    '~~> Excel Objects
    Dim oXLApp As Object, oXLWb As Object

    '~~> Other Variables
    Dim sPath As String, OldPath As String, sFullFileOld As String
    Dim oldFileName As String, newFileName As String

    'Set the initial directory path of File Dialog
    initDir = "C:\"

    '~~> Get the SourceFullName of the chart. It will be something like
    '   C:\MyFile.xlsx!Sheet1![MyFile.xlsx]Sheet1 Chart 1
    OldSourcePath = ActivePresentation.Slides(1).Shapes(1).LinkFormat.SourceFullName

    Set ofd = Application.FileDialog(msoFileDialogFilePicker)

    With ofd
        .InitialFileName = initDir
        .AllowMultiSelect = False

        If .Show = -1 Then
            '~~> Get the path of the newly selected workbook. It will be something like
            '   C:\Book2.xlsx
            sPath = .SelectedItems(1)

            '~~> Launch Excel
            Set oXLApp = CreateObject("Excel.Application")
            oXLApp.Visible = True

            '~~> Open the Excel File. Required to update the chart's source
            Set oXLWb = oXLApp.Workbooks.Open(sPath)

            '~~> Get the path "C:\MyFile.xlsx" from
            '~~> say "C:\MyFile.xlsx!Sheet1![MyFile.xlsx]Sheet1 Chart 1"
            OldPath = Split(OldSourcePath, "!")(0)

            '~~> Get just the filename "MyFile.xlsx"
            oldFileName = GetFilenameFromPath(OldPath)
            '~~> Get just the filename "Book2.xlsx" from the newly
            '~~> Selected file
            newFileName = GetFilenameFromPath(.SelectedItems(1))

            '~~> Replace old file with the new file
            NewSourcePath = Replace(OldSourcePath, oldFileName, newFileName)

            'Debug.Print NewSourcePath

            '~~> Change the source and update
            ActivePresentation.Slides(1).Shapes(1).LinkFormat.SourceFullName = NewSourcePath
            ActivePresentation.Slides(1).Shapes(1).LinkFormat.Update
            DoEvents

            '~~> Close Excel and clean up
            oXLWb.Close (False)

            Set oXLWb = Nothing
            oXLApp.Quit
            Set oXLApp = Nothing
        End If
    End With

    Set ofd = Nothing
End Sub

Public Function GetFilenameFromPath(ByVal strPath As String) As String
    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        GetFilenameFromPath = _
        GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function


text:
Q: C# How To Sort Two Columns By Hierarchy I am comparing user groups to see what groups are members of other groups.  I then need order them from largest scope to smallest.  An example from any language would be fine.  I know a series of loops would accomplish this but haven't been able to successfully do it.  Here is my example.  I have two lists as follows:
 IT          Staff
 Teacher     Staff
 Engineer    IT
 Engineer    Staff

We can see that the IT department is a part of staff, Teachers are a part of staff, an engineer is a part of IT and and Engineer is a part of Staff.  I need to end up with something like:
 Staff
 IT Teacher
 Engineer

It doesn't matter here that Engineer is listed below Teacher and is not part of a teacher group.  I just need to get an order of largest scope to smallest.  Since I know that IT and Teacher are on the same level and Engineer is smaller than IT, IT must also be smaller than Teacher.
Any help is greatly appreciated.

A: 1.get unique item from both columns:

*

*IT

*Teacher

*Engineer

*Staff

2.give each item a starting weight, e.g: 100

*

*IT = 100

*Teacher = 100

*Engineer = 100

*Staff = 100

3.for each item, each time it is appeared in the first column (column[0]), minus its weight by 1

*

*IT = 100 - 1 = 99

*Teacher = 100 -1 = 99

*Engineer = 100 -1 -1 = 98

*Staff = 100

4.sort your items by weight:

*

*Staff (100)

*IT (99)|Teacher (99)

*Engineer (98)


text:
Q: High performance - converting Objects to Array while sorting keys I have the following object:
var myObj = {
              "4":{//The key is a number String.
                    id:4,name:aaaa
                  }
              "1":{
                    id:1,name:a
                  }
              "2":{
                    id:2,name:aa
                  }
              "3":{
                    id:3,name:aaa
                  }
            }

And i would like to convert it to the following array:
var myArr = [{id:1,name:a},{id:2,name:aa},{id:3,name:aaa},{id:4,name:aaaa}]

My question is more of a syntax question, can the following pseudo code be done with Javascript:
1. Create an array with the size of Object.keys(myObj).length.
2. For each key in myObj
    2.1 set myArr[key] = myObj[key]

What would be the fastest way to achieve that?
BTW, it is used in my node.js server and not a browser client.

A: I don't think any manipulation will do any real performance gain.
Also, since JavaScript works on "reference to-" approach, the real hit here is to create an array and sort it, since you don't really deep-copy the objects.
it shouldn't be real performance hit since the array is small in your example.
in this case, prefer clear code over psudo-performant code:
var arr = [];
for (var o in myObj){
   arr.push(myObj[o]);
}
arr.sort(function(a,b){
  return a.id-b.id;
});

A: First of all your JSON is not a valid JSON, Use , and "". To achieve your task use Array.prototype.map

var myObj = {
              "4":{//The key is a number String.
                    id:4,name:"aaaa"
                  },
              "1":{
                    id:1,name:"a"
                  },
              "2":{
                    id:2,name:"aa"
                  },
              "3":{
                    id:3,name:"aaa"
                  }
            };

var arr = Object.keys(myObj).sort(function(a,b){return +a - +b;}).map(function(x){ return myObj[x]; }); // ES6
document.write(JSON.stringify(arr));

For ECMAScript6 Use
var arr = Object.keys(myObj).sort().map( x => myObj[x]);

A: Just sort the keys:

var myObj = { "4": { id: 4, name: 'aaaa' }, "1": { id: 1, name: 'a' }, "2": { id: 2, name: 'aa' }, "3": { id: 3, name: 'aaa' } },
    result = Object.keys(myObj).map(Number).sort(function (a, b) {
        return a - b;
    }).map(function (k) {
        return myObj[k];
    });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

A: Using lodash:
var sortedById = _.sortBy(_.values(myObj), 'id');


text:
Q: Alexa Skill Flow Builder - how to dynamically update player count How do I player a player count in Alexa skill flow Builder?

*

*Select a number of players. and then

*Flow Builder updates with the number of players to

*Ask each player a question in the game.

where should I start going? is there a way for me to scale experience across multiple players based off of a slot?
can I change the flow of the experience dynamically based off of the number of players I received from a slot?

A: Of course! We have an amazing tool: the dialog.directives. You can manually trigger intents in your handlers. You can also fill the slots for the user (in case you need to). You need to simply trigger that intent n number of times, where n is the number of players you have.
You can achieve that by following different paths. Give it a try and let me know if you need any more help :)
Read more: https://developer.amazon.com/es-mx/docs/custom-skills/dialog-interface-reference.html#scenario-delegate


text:
Q: How to Delete App Service -> Web App -> Log Files from C# OR Microsoft.Azure.Management Presently log in via Kudo / Azure CLI / FTP and manually delete.
We have an existing dev-ops codebase that uses Microsoft.Azure.Management.  Looking for any way to delete files, specifically /LogFiles/*.log where older than x using C# vaguely.
Seemingly could enumerate WebApps and get FTP credentials and use FtpWebRequest but would like to know if there is a more direct way.
Did not see any methods here -> Web Apps:

A: I am afraid there is not a direct way. However,you can call Kudu Api to delete the log files. Below is an example of powershell script:
$ResGroupName = ""
$WebAppName = ""
$LogFolder = ""
$DaysToKeepLogsAround=""

# Get publishing profile for web application

$WebApp = Get-AzWebApp -Name $WebAppName -ResourceGroupName $ResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $WebApp

# Create Base64 authorization header

$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

$apiBaseUrl = "https://$($WebApp.Name).scm.azurewebsites.net/api/command"

# delete log files

 $apiCommand = @{
        command = 'powershell.exe -command "Get-ChildItem -Path $LogFolder -Recurse -File | Where LastWriteTime  -lt  (Get-Date).AddDays(-$DaysToKeepLogsAround) | Remove-Item -Force"'
        dir=$LogFolder
    }

Invoke-RestMethod -Uri $apiBaseUrl -Headers @{"Authorization"="Basic $base64AuthInfo";"If-Match"="*"} -Method POST -ContentType "application/json" -Body (ConvertTo-Json $apiCommand)

You can also refer to another example in this thread.
You can aslo create a azure web job and upload a powershell script to delete the old log files. Please check here for detailed steps.


text:
Q: Проблема с перегрузкой оператора Проблема с перегрузкой оператора - для данного класса
class mvector
{
public:
    mvector();
    mvector(int a);
    mvector(const mvector &a);

    void PrintByCount(int a);
    int GetLength();
    int* GetStart();

    friend mvector& operator-(mvector a,mvector b);
private:
    int length;
    int* begin;
};

Определение оператора
mvector& operator-(mvector a,mvector b)
{
    mvector ans(min(a.length, b.length));
    cout <<"Длинна"<< ans.length <<endl;
    for (int i = 0; i < min(a.length, b.length); i++)
        ans.begin[i] = min(a.begin[i], b.begin[i]);
    cout << "ANS" << endl;
    ans.PrintByCount(5);
    cout << "ENDANS" << endl;
    return ans;
}

int main()
{
    setlocale(LC_ALL, "Russian");
    mvector a(CheckedInput("Введите длину первого вектора",1,LLONG_MAX));
    mvector b(CheckedInput("Введите длину первого вектора", 1, LLONG_MAX));
    (a - b).PrintByCount(5);
    return 0;
}

В теле оператора вывод верный. А в main нет

A: Ну кто же возвращает ссылку на локальную переменную! Это же ссылка в никуда: ведь локальной переменной после выхода из функции просто нет. Вообще.
Попробуйте
mvector& operator-(mvector a,mvector b)

заменить на
mvector operator-(mvector a,mvector b)

P.S. Да, вдогонку - а еще аргументы как раз вполне можно передавать по ссылке:
mvector operator-(const mvector& a, const mvector& b)

A: семантика перегрузки операторов тут https://stackoverflow.com/questions/4421706/operator-overloading
class mvector
{
  mvector(); // not implemented

public:
  ~mvector() { delete[] vals; }

  mvector(int a);
  mvector(const mvector &rhs)
    : vals(NULL)
  { *this = rhs; }

  int size(void) const { return len; }

  int* begin(void) const { return vals; }
  int* end(void) const   { return vals+len; }

  mvector& operator-(const mvector& rhs);
  mvector& operator=(const mvector& rhs);

private:
  int len; //length;
  int* vals; // begin

};

mvector::mvector(int a)
  : len(a)
{
  vals = new int[len];
  for(int i = 0; i<len; ++i)
  {
    vals[i] = 0;
  }
}

mvector& mvector::operator=(const mvector& rhs)
{
  delete[] vals;
  len = rhs.len;

  vals = new int[len];
  for(int i = 0; i < len; ++i)
  {
    vals[i] = rhs.vals[i];
  }
}

mvector& mvector::operator-(const mvector& rhs)
{
  int new_len = (len > rhs.len)?rhs.len:len;

  mvector res(new_len);
  int* res_it  = res.begin();
  const int* rhs_it  = rhs.begin();
  const int* this_it = begin();

  for (int i = 0; i < new_len; ++i)
  {
    *res_it = ((*this_it) < (*rhs_it))?(*this_it) : (*rhs_it);
    ++res_it; ++this_it; ++rhs_it;
  }

  *this = res;

  return *this;
}

mvector subst(const mvector& a, const mvector& b)
{
  mvector c(a);
  c = c-b ;
  return c;
}

// --------------------------------------------------------------------------------
void Print(const mvector& val)
{
  std::cout << "mvector.size is " << val.size() << std::endl;

  for(int* i = val.begin(); i != val.end(); ++i)
  {
    std::cout << "i=" << *i << std::endl;
  }
}

int main()
{
  mvector a(10);
  for(int* i = a.begin(); i != a.end(); ++i)
  {
    *i = 10;
  }

  mvector b(20);
  for(int* i = b.begin(); i != b.end(); ++i)
  {
    *i = 12;
  }

  Print(b-a);

  mvector e = subst(c,a);
  Print(e);

  return 0;
}

A: Данный оператор
mvector& operator-(mvector a,mvector b)
^^^^^^^^
{
    mvector ans(min(a.length, b.length));
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    cout <<"Длинна"<< ans.length <<endl;
    for (int i = 0; i < min(a.length, b.length); i++)
        ans.begin[i] = min(a.begin[i], b.begin[i]);
    cout << "ANS" << endl;
    ans.PrintByCount(5);
    cout << "ENDANS" << endl;
    return ans;
    ^^^^^^^^^^^
}

некорректен, так как он возвращает ссылку на локальную переменную функции, время жизни которой заканчивается после выхода из функции. В результате программа имеет неопределенное поведение.
Правильно было бы определить оператор следующим образом
class mvector
{
public:
    mvector();
    mvector(int a);
    mvector(const mvector &a);

    void PrintByCount(int a);
    int GetLength() const;
                    ^^^^^^
    int* GetStart();
    const int* GetStart() const;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    // Убрать из класса friend mvector operator -( const mvector &a, const mvector &b);
private:
    int length;
    int* begin;
};

mvector operator -( const mvector &a, const mvector &b )
{
    mvector ans( std::min( a.GetLength(), b.GetLength() ) );

    std::cout <<"Длинна"<< ans.GetLength() <<endl;
    for (int i = 0; i < ans.GetLength(); i++ )
        ans.GetStart()[i] = std::min( a.GetStart()[i], b.GetStart()[i]);

    std::cout << "ANS" << std::endl;
    ans.PrintByCount(5);
    std::cout << "ENDANS" << std::endl;

    return ans;
}

То есть нет необходимости делать этот оператор дружественным классу, так как есть все необходимые функции-члены класса для доступа к данным класса.
Также имейте в виду, что так как, похоже, у вас память выделяется динамически внутри объектов класса, то вам необходимо также объявить копирующий оператор присваивания и деструктор.


text:
Q: Can I get Windows Explorer to open to a location of my choosing? I'd like to have Windows Explorer open at my C:\ drive when I press Windows + E, rather than at some to-me useless location; every single time I open Explorer (which I do a lot), I have to scroll down to C:\, etc. - a waste of time and an unwanted trip to Aggravation Station.

A: You need to change your explorer shortcut to: %windir%\explorer.exe c:\

A: A normal Explorer shortcut can be modified as mentioned by Bryan (explorer.exe <path>).
To modify Win+E's default behaviour however, you'd need an AutoHotKey script like the following:
#e:: Run explorer.exe C:\

A: What I normally do is Win+R to bring up the run dialog. You can enter any path here and Explorer will open at that path. I prefer this over Win+E because I have a number of network drives mapped that I will use as often as anything local.


text:
Q: How to count the number of bytes of a character EDIT: Ooooops.
console.log (Buffer.byteLength ("", "utf8")); //--> 3

I want to count the number of bytes of a character. This is what I have:
var charBytesLength = function (c){
    var n = 0;
    c = c.charCodeAt (0);
    do{
        c = c >>> 8;
        n++;
    }while (c);
    return n;
};

If the character is encoded using UTF8, for characters with more than 2 bytes the function always returns 2 because in Javascript a character is a 16-bit value and charCodeAt() only returns the value between 0 and 65535.
For example:
"".charCodeAt (0)

returns 65533, when the real hexadecimal value is 0x24065 (147557 in decimal)
Do you know how to count the real number of bytes?

A: console.log (Buffer.byteLength ("", "utf8")); //--> 3


text:
Q: Unless Otherwise Noted I have a question about the phrase "unless otherwise noted":

The game starts at 7:00pm unless otherwise noted.

Is the part "unless otherwise noted" missing an "it is" between "unless" and "otherwise noted":

The game starts at 7:00pm unless it is otherwise noted.

Or, is "unless otherwise noted" a set phrase and I should stop losing sleep over it?

A: It is a set phrase. The "it is" is understood/implied. However, there is nothing wrong with adding "it is" in the middle like you have.


text: Q: Accessing Sandboxes of Google APIs from PHP Client Library Just wondering if there's any means to allow for the PHP Client Library's services to access their API's sandbox environment, instead of just their real ones. (I'm doing this for dfareporting, myself)


text:
Q: Converting a Scala Session Object to a Java Session Object in Play Framework Is there a way to convert the session object in scala to the session object in java in Play?
I have a Model method written in java like :
public void DoSomething(Request request, Session session)
{
       String fancyValue = request.getQueryString("userInput");
       session.put("Some Fancy Stuff",fancyValue);
}

and a Controller method written in scala like:
def showHomePage = Action { implicit request =>

     val JRequest = play.core.j.JavaHelpers.createJavaRequest(request)
     val JSession // conversion needed from request.session to play.mvc.Http.Session

     new SomeModel().DoSomething(JRequest,JSession)

     // would this include the updates done to the session in the java model?
     Ok("Testing Stuff").withSession(session)
}

A: If you look at the docs of the JavaHelpers package, you'll find a function createJavaContext there. You can use that to obtain a play.mvc.Http.Context, from which you can extract a play.mvc.Http.Request and play.mvc.Http.Session.
val java_ctx = play.core.j.JavaHelpers.createJavaContext(request)
val java_request = java_ctx.request()
val java_session = java_ctx.session()


text:
Q: Determining standard deviations and standard errors for non-Gaussian distributions I have several questions about constructing error bars and using them as weights in the context of fitting, or indeed any kind of weighted statistic -- especially with regards to error and noise sources which are non-Gaussian.
Usually one might make a measurement, repeat it many times, and if the underlying source of error or noise on the measurement is Gaussian, then defining error bars and weights is relatively simple -- either some multiple of the standard deviation e.g. $\delta x = \pm \sigma$ encompasses $68\%$ of the data, OR a standard error like $\sigma/ \sqrt{n}$.
For example, I have constructed an arbitrary function and generated some random data with a Gaussian distribution:

The red plot markers indicate the mean, and the error bar is simply one standard deviation. I have plotted the corresponding PDF for each set of data and mapped these distributions to the plot. This is how I visualise the error and distribution of data, and what the mean data points (red markers) "really look like".
In the case of the Gaussian distribution the mode and the mean (expected value) are the same, but what about for other distributions, especially those that are asymmetrical. For example the Rayleigh distribution
$$R(x) = \frac{x}{\sigma_{R}^{2}} e^{-x^{2}/(2 \sigma_{R}^{2})}$$
which has the shape parameter $\sigma_{R}$ which also defines its mode. Its mean is easily calculated via $$E(x) = \int_{0}^{+\infty} x R(x) \ \ dx$$
which gives the mean $$E(x) = \mu = \sigma_{R}\sqrt{\pi/2}$$ for the Rayleigh distribution. I show a plot of the Rayleigh distributions anatomy below where $\sigma_{R} = 1$:

First question:
As I understand it the variance, $\sigma^{2}$, may be calculated by
$$V(x) = \sigma^{2} = \int_{-\infty}^{+\infty} (x - \mu)^{2} f(x)\ \ dx$$
where $\mu = E(x)$ as defined above. Does this mean the standard deviation for any distribution, $f(x)$, is simply $\sqrt{V(x)}$?
This to me is somewhat counter intuitive as for an asymmetric distribution I would expect an asymmetric standard deviation or error bar. If I repeat my example as above but this time using a Rayleigh distribution instead of a Gaussian:

I should stress this is a cartoon for how I am visualising the data
Second question:
Should the standard deviation or error bars not reflect the shape of the distribution from which they are calculated? If one calculates the standard deviation using
$$V(x) = \sigma^{2} = \int_{-\infty}^{+\infty} (x - \mu)^{2} f(x)\ \ dx$$
, it is clear that any error bar would be symmetric.
Third Question:
Regardless of the answers to my first two questions, I would be curious to know how one would go about constructing a weight from an asymmetric error bar i.e. normally a weight is defined as $$W = 1/\sigma^{2}$$ where $\sigma$ can be the error or standard deviation in some quantity $x\pm \sigma$ where $\sigma$ could also be $\sigma = \delta x$ the error in some quantity. But what about if one has something like $$x^{+\delta x_{+}}_ {-\delta x_{-}}$$ where $\delta x_{-} < \delta x_{+}$. How would one construct a weight from this?

A: First question:
The "standard deviation" is defined mathematically, there is no other way to calculate it.   It isn't meant to capture all the information about the shape of the distribution; no one numeric value could hope to do so except in the case of one-parameter distributions.   Note that your expression for the variance:
$$V(x) = \sigma^{2} = \int_{-\infty}^{+\infty} (x - \mu)^{2} f(x)\ \ dx$$
does not specify the functional form of $f$; this means that the variance, and the standard deviation $\sigma$ (which is nothing more than $\sqrt{\sigma^2}$), are defined the same way regardless of $f$.
Second question:
The standard deviation does reflect one aspect of the shape of the distribution, namely, how spread out it is, writing loosely.  Even then, it doesn't capture all aspects of what might be referred to as "spread out", e.g., those captured by kurtosis.  It does not reflect skewness - the standard deviation of a random variable $x$ is the same as that of $-x$, although the skewness has switched signs, for example.   If you want asymmetric error bars, which is in many cases a good thing to want, you'll have to construct them using either your knowledge of the distribution's functional form or other techniques such as bootstrapping; as you have realized, you can't get there from the standard deviation alone.
However, in many cases the Central Limit Theorem plus enough data and some assumptions means that even with non-normal errors, confidence intervals for individual parameters, e.g., regression coefficients, are well-approximated by a Normal distribution, for which symmetric confidence intervals are appropriate (unless you have an unusual criterion for your interval.)
Your Rayleigh distribution example above can be used to illustrate this; if I have a fair amount of data, my estimate of the Rayleigh parameter $\sigma_R$ will be approximately Normal (or $t$, with less data.)  The random variate I'm observing will have a Rayleigh distribution, but the parameter estimate will not:
sr_hat <- rep(0,10000)

for (i in 1:10000) {
   x <- sqrt(-2*log(runif(100)))  # Rayleigh with parameter = 1
   sr_hat[i] <- mean(x*x)/2       # MLE of Rayleigh parameter
}

hist(sr_hat, xlab="MLE of Rayleigh(1) parameter", main="Histogram of ML Estimates")

which generates the following plot:

Not far from a Gaussian distribution, and further analysis (done at your leisure) will confirm this.
On the other hand, if you are trying to construct a predictive confidence interval, then you'd want to take the asymmetry of the Rayleigh distribution into account.   There are lots of ways to do that; Bootstrap prediction interval, How to: Prediction intervals for linear regression via bootstrapping, and other questions may get you started on bootstrap methods.  You can also generate pointwise confidence intervals for a curve, or for observations centered around a curve, as in your third plot above, through bootstrapping.
Here's a simple bootstrap for a predictive interval given a parameter estimate from 100 observations from a Rayleigh(1) distribution:
z <- rep(0,100000)

# Generate initial parameter estimate
x <- sqrt(-2*log(runif(100)))  # Rayleigh with parameter = 1
sr_est <- mean(x*x)/2          # MLE of Rayleigh parameter

# Bootstrap
for (i in 1:100000) {
   x <- sr_est * sqrt(-2*log(runif(100)))  # Rayleigh with parameter = sr_est
   sr_hat <- mean(x*x)/2                   # MLE of Rayleigh parameter
   z[i] <- sr_hat*sqrt(-2*log(runif(1)))
}

plot(density(z, bw="SJ", adjust=2),
     xlab="Predictive distribution of Rayleigh(1) observations",
     main = "Smoothed predictive density distribution", lwd=2)

which generates:

Third question:
If you are using squared-error loss, then generating weights using the variance is appropriate regardless of considerations of skew.  To see this intuitively, consider the fact that squared error itself doesn't take skew into account, so one might suspect that optimal weighting of observations from a squared error perspective wouldn't either.  How to estimate those weights when you don't  know them a priori is a bigger issue; see the second answer to  How do you find weights for weighted least squares regression? for an example of a situation where an optimal weighting scheme isn't dependent upon a variance estimate at all!
If, on the other hand, you aren't using squared-error loss, then $w_i = 1/\sigma^2_i$ may not be the appropriate weighting scheme, as you suspect.  What would be an appropriate weighting scheme is going to be problem-specific, and, without further information, far beyond the scope of this answer.


text:
Q: Testing Auto-Complete Combo box in Selenium Has anyone a good solution on how to test auto-complete combo box in Selenium?
Thanks for the help,
Manjide

A: Take a look at my other answer Selenium - verify the list of suggestions is displayed

A: Using TestPlan with the Selenium back-end this code grabs the suggestions from Google -- which is an example of a auto-complete combo box.
GotoURL http://www.google.com/webhp?hl=en
ClickReplaceType //input[@name='q'] what is my

# This is where the suggestions appear
set %ResultsXPath% //table[@class='gac_m']//td[@class='gac_c']

# Check that they are there (that is, wiat for them, since they are dynamic)
Check %ResultsXPath%

# Then iterate over the suggestions
foreach %Cell% in (response %ResultsXPath%)
    Notice %Cell%
end

This produces the results:
00000000-00 GOTOURL http://www.google.com/webhp?hl=en
00000001-00 NOTICE Starting a new browser (0:0:0:0:1) com.thoughtworks.selenium.DefaultSelenium@332611a7
00000002-00 NOTICE what is my ip
00000003-00 NOTICE what is my ip address
00000004-00 NOTICE what is my bmi
00000005-00 NOTICE what is my house worth
00000006-00 NOTICE what is my

Usually such tests work in both the Selenium and HTMLUnit backend in TestPlan, but Google currently works with Selenium.


text:
Q: Angular HTTP Interceptor does not execute Observable I am trying to implement a sliding expiry session in Angular, where the session should be extended with every interaction with the API.
The HTTP interceptor is responsible for renewing the token after every response. The problem here is that authService.renewToken() call never really executes the request to the API. I do see begin renew token and renewToken log messages in the console but the token request to the API never fires.
Any ideas what might be the problem here?
AuthenticationService

  public renewToken(token: string): Observable<Token> {

    console.log('renewToken');

    return this.api
      .createSession(token)
      .pipe(tap((newToken) => {
          console.log(token === newToken.token);

          this.saveToken(newToken);
        }));
  }

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  private refreshingToken = false;
  private tokenSubject = new Subject<any>();

  constructor(private injector: Injector) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(tap(event => {

      if (this.shouldIntercept(event)) {
        this.tokenSubject.next(null);
        this.refreshingToken = true;

        const authService = this.injector.get(AuthenticationService);

        const currentToken = authService.getToken();

        console.log('begin renew token');

        return authService.renewToken(currentToken).pipe(
          switchMap((newToken: Token) => {
            console.log("newToken Recieved:", newToken.token);
            this.tokenSubject.next(newToken);
            return next.handle(req);
          }),
          finalize(() => { this.refreshingToken = false; })
        )
      }

      return next.handle(req);
    }), catchError(errorResponse => {
      this.refreshingToken = false;

      if (errorResponse.status === 401) {
        console.log('Unauthorised response received.');
        this.injector.get(Router).navigate(['error']);
      }
      return throwError(errorResponse);
    }));
  }

A: Assuming your saveToken function returns an observable, the reason you might not be seeing any API response is that tap won't subscribe to this.saveToken. Try using switchMap/exhaustMap/concatMap (IMO switchMap makes the most sense as it will cancel an in-flight request if a new one arrives). These operators will automatically subscribe to inner observables.


text:
Q: UITableView scroll to a specific point when scrollViewDidEndDragging I have a UITableView which is scrollable. When the user scrolls the UITableView a certain amount and then releases their finger, instead of scrolling back to the top, I want it to scroll 50 points from the top, effectively leaving a gap of 50 points between the top of the screen and the top most cell.
At the moment I have implemented scrollViewDidEndDragging, but I don't know how to set where the view will scroll back to.
I've tried the following, but it doesn't work as desired.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // If scrolled over 100 points
    if(-100 > (double)self.tableView.contentOffset.y) {
        [self.tableView setContentOffset:CGPointMake(0, -50) animated:YES];
    }
}

The code above causes a weird flicker, like the animations are both running concurrently, but I'm unsure.
Any help would be appreciated.
UPDATE with more information
I'm implementing "Pull down to refresh" functionality based upon this post:
https://stackoverflow.com/a/6392145/120615
I've added an extra UIView to the top of the UITableView and when you scroll the UITableView, the UIView moves down into view. When you release your finger from the screen, the UITableView scrolls back to the top hiding the new UIView I've added.
What I would like to happen is that when you release your finger the UITableView scrolls back to top but stops 100 points from the top (so I can show an activity indicator to the user) and then after 2/3 seconds scrolls completely to the top.

A: I think you are right, the animations are running concurrently because scrollviews have the deceleration feature.
instead of using the DidEndDraging callback function try this one:

*

*(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

This will only be called once the user triggered animation is complete.


text:
Q: How to select all URLs in a web site excluding those of a given class? I would like to select all the URLs from my Twitter followers page using regex. If I use https://twitter\.com/.* it will select all the URLs matching this pattern in the website, but I'd like to exclude users on the Who To Follow section. This URLs are within the WhoToFollow class. So, my question is: can I use XPath, regex or a combination of both to select all URLs matching the previous pattern but excluding the URLs within the WhoToFollow class in Python?
Thanks!
Dani

A: if i correctly understood, you can use such xpath, taking a tag not with class WhoToFollow and having url beginning with https://twitter.com/. Then it takes content of href
//a[not(@class="WhoToFollow") and starts-with(@href, "https://twitter.com/")]/@href


text:
Q: creating an event handler on object initialization I have an object model like this:
public class MyObject{

  public int Prop1{get;set;}
  public int Prop2{get;set;}

  public void MyObjectInit()
  {
    this.Prop1 = 0;
    this.Prop2 = 0;
  }

}

How do I create an event handler for MyObject that triggers when the object is initialized and runs MyObjectInit.
Thanks

A: Why use an event handler.  Just use the object constructor.
public void MyObject()
{
   MyObjectInit();
}

Or better yet, move the code of MyObjectInit into the constructor.


text:
Q: Deallocate a Ubuntu VM from itself I am using a Ubuntu 16.04 VM in Azure to run some GPU computation. Typically, I run my experiments at night and I would like to deallocate the VM when the computation is over (to save some money). Is there any command that I can run from the VM I want to deallocate to actually deallocate it? Shall I just use the Azure CLI? Thanks in advance.

A: Yes, it is possible.
When your script works successful, you could judge the return value. Then, execute Azure CLI to deallocate your VM.
##your script
if [$? -eq 0];then
 az vm deallocate --resource-group myResourceGroup --name myVM
fi

Notes: If you don't use static IP, it will change IP when you deallocate your VM. Also, if you want to start your VM automatically, you could use Azure automation runbook.

A: Yeah, you would want to use Azure Cli or Azure Cli 2.0
az vm deallocate --resource-group myResourceGroup --name myVM

or with the cli
azure vm deallocate -g myResourceGroup -n myVM


text:
Q: Delete git merge commit from local history My commit history looks like this:

Yellow is the master branch, blue and purple are feature branches. Commits 0-5 have been pushed, commits 6-10 are only local.
I want to undo the effect of merge commit 6, I mean delete it entirely, and reroute C7 to be the merge of C1 and C2.
Any ideas on how to achieve this?

A: This won't be very easy, and since you will need some trial and error, better take a (local) copy of you git repo before doing this. Then try something like this:
git branch temp <sha-2>
git merge <sha-1>
git merge <sha-5>
git checkout master
git rebase temp
git branch -d temp


text:
Q: Gradient Doesn't work without using " background-attachment: fixed !important; " ? What is the alternative? Being new to web development I tried making a nice login. I couldn't get the positions of the elements right and I was forced to use " background-attachment: fixed !important; ".
Is there any other way of achieving the same results {picture given below} without using ``` background-attachment: fixed !important;
Here is my code:

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  height: 100%;
  background: linear-gradient( red, green);
  background-attachment: fixed !important;
}

.box {
  width: 300px;
  padding: 40px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #191919;
  text-align: center;
}

.box h1 {
  color: white;
  text-transform: uppercase;
  font-weight: 500;
}

.box input[type="text"],
.box input[type="password"] {
  border: 0;
  background: none;
  display: block;
  margin: 20px auto;
  text-align: center;
  border: 2px solid #3498db;
  padding: 14px 10px;
  width: 200px;
  outline: none;
  color: white;
  border-radius: 24px;
  transition: 0.25s;
}

.box input[type="text"]:focus,
.box input[type="password"]:focus {
  width: 280px;
  border-color: #2ecc71;
}

.box input[type="submit"] {
  border: 0;
  background: none;
  display: block;
  margin: 20px auto;
  text-align: center;
  border: 2px solid #3498db;
  padding: 14px 40px;
  width: 200px;
  outline: none;
  color: white;
  border-radius: 24px;
  transition: 0.25s;
  cursor: pointer;
}

.box input[type="submit"]:hover {
  background: #2ecc71;
}
<form class="box" action="index.html" method="POST">

Login

  <input type="text" name="" placeholder="Username">
  <input type="password" name="" placeholder="password">
  <input type="submit" name="" value="Login">
</form>

My Desired Result

I googled a lot to find a good solution for this simple problem, but got more confused, so I want some experience person's advice on this, and do's and don't as a beginner.
{ For the Ans, I would be grateful if you could put the whole code and explain why you chose a particular style and how it resolves the general problem ( I read that using "background-attachment: fixed !important; " might cause trouble) } Thankyou.
----------------------- After Edits ----------------------------------
The Problem here is, without " background-attachment: fixed !important; " the background gradient doesn't work.
and if I put position as relative for the "box" element, the result is different than what I want.
So, I want the positions correct {as per the Image }, with Background gradient, and without background-attachment: fixed !important;

A: You could use javascript to set the backgrounds height equals your scrolling.


text:
Q: Integer into textview I'm not too experienced with java programming in Android Studio yet, but I couldn't find a solution for this problem:
I want to be able to get 2 integers and convert them into text to put them into a line of text.
So for example:
int counterT = 0;
TextView showValueT;

public void CountIncT (View view) {
showValueT = (TextView) findViewById(R.id.countT);

counterT++;
showValueT.setText(Integer.toString(counterT));

Together with the other counter, say CountIncU / showValueU / countU / counterU, I want to get a textline that gets the 2 scores and put them together to a textline like:
(counterT + " - " + counterU) or 5 - 3 for example, after pressing a button.
I think that I'm just missing a single piece, but I couldn't find it anywhere so I hope that you can help me out here, thanks!


text:
Q: COBOL: remove certain characters from string I would like to remove certain characters from a string in COBOL.
For example, '****This is*a test** string.' will become 'This isa test string.', '"Second one"' will become 'Second one'.

A: Try the following code snippet.
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO-WORLD.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STR PIC X(20) VALUE '****This is*a test**'.
01 WS-CNT PIC 99 VALUE 0.
01 WS-I PIC 99 VALUE 0.
01 WS-J PIC 99 VALUE 1.
01 WS-CHAR.
   05 WS-LETTER OCCURS 1 TO 20 TIMES DEPENDING ON WS-CNT PIC X.
PROCEDURE DIVISION.
PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I > FUNCTION LENGTH(WS-STR)
IF WS-STR(WS-I:1) = '*' THEN
CONTINUE
ELSE
MOVE WS-STR(WS-I:1) TO WS-LETTER(WS-J)
ADD 1 TO WS-J
ADD 1 TO WS-CNT
END-IF
END-PERFORM
DISPLAY WS-CHAR
STOP RUN.

Output:
This isa test

Note: I used Tutorial Point's COBOL Coding ground to run the above snippet. COBOL Code doesn't need to be indented there.

A: While INSPECT ... REPLACING cannot change the position of characters within a data item, INSPECT ... CONVERTING may be used to prepare the data item for subsequent operations.
In the following, the procedure strip-string first converts all characters, to be replaced, to a single common character, in this case, LOW-VALUES. This fragments the string so that the common character maybe be used to easily delimit the fragments. The PERFORM loops over the fragmented string. The UNSTRING statement moves one fragment to the output and provides a COUNT of the number of characters moved. The ADD augments the output starting position so that the fragments are positioned in sequence.

Code:
   data division.
   working-storage section.
   1 binary.
    2 p pic 9(4).
    2 o pic 9(4).
    2 o-count pic 9(4).
   1 i-string pic x(40).
     88 test-1 value '****This is*a test** string.'.
     88 test-2 value '"Second one"'.
   1 o-string pic x(40).
   1 r-chars pic x(2) value '*"'. *> characters to be removed
   procedure division.
   begin.
       set test-1 to true
       perform test-prep
       set test-2 to true
       perform test-prep
       stop run
       .

   test-prep.
       display i-string
       perform strip-string
       display o-string
       display space
       .

   strip-string.
       inspect i-string converting r-chars to low-values
       move 1 to p o
       perform until p > function length (i-string)
           unstring i-string
               delimited all low-values
               into o-string (o:)
               count in o-count
               with pointer p
           add o-count to o
       end-perform
       .

Output:
****This is*a test** string.
This isa test string.

"Second one"
Second one


text:
Q: php preg_match regex for multiple directories and files I'm trying to write a regex expression in PHP that will load content in all locations specified, or every location except those specified.
#load content everywhere EXCEPT locations expressed
<?php if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI']) === 0): ?>

Bonjour

<?php endif; ?>

#load content on locations expressed
<?php if (preg_match('/\/(contact\/|news\/|index\.html)/', $_SERVER['REQUEST_URI']) === 1): ?>

Konichiwa

<?php endif; ?>

The problem I'm having is that I can't get the root of my website /index.html(specifically http://example.com/index.html, nowhere else) to work alongside the wildcards for any page in /contact/ or /news/.
To summarize again:
/contact/* (any page in contact), /news/* (any page in /news/), /index.html (root of website)
I've tried a few different ways of adding the slash before index.html, but it either didn't work or returned a PHP error.

A: Make sure you use anchor ^ (line start) make sure you match URI from root:
if (preg_match('#^/(contact/|news/|index\.html|$)#', $_SERVER['REQUEST_URI']))

I also changed regex delimiter to # so that you can avoid escaping / in your regex.


text:
Q: why doesn't with-open force evaluation Just wondering why with-open doesn't force evaluation of a LazySeq and yet prn does?
with-open is specifically for doing side effects, isn't it a bad idea to be doing something inside with-open that produces something lazy for possible consumption later on?  In what situation would you do this?

A: The two serve completely different purposes. prn is a function designed specifically to print things in a way that can be read by the reader. If the thing being printed happens to be a lazy sequence, the only thing to do is force evaluation of the lazy sequence in order to print its contents.
with-open, on the other hand, is a general-purpose macro designed to execute any arbitrary code in its body in a context where resources are closed on completion of the code. It's essentially syntactic sugar. The macro knows nothing about what the code in its body is doing, or what sort of result it's going to produce.
You are correct that returning lazy sequences from a with-open that try to read from an already-closed resource is a common source of bugs in Clojure programs. However, it's not feasible for the with-open macro to reliably detect when its body causes a lazy sequence to be produced and automatically force it. You have to be aware of this situation and handle it in your own code when it arises.


text:
Q: Update a column after joining two tables with where clause I have two tables
threads table
_id   recipient_id    type
 1     1
 2     1
 3     2

and addresses table
_id    address
1      HELLO
2      BYE

recipient_id is mapped to addresses table's _id
I need to update type to a specific value if address is HELLO. How do i do it? I have already tried
UPDATE   threads SET threads.type = 106 FROM threads
   INNER JOIN
   addresses  ON addresses._id = threads.recipient_ids
    AND
   addresses.address LIKE '%HELLO%';

But i am getting an error near ".": syntax error .
What is the correct syntax to update a column?

A: You can use the IN operator:
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE threads (_id integer primary key, recipient_id integer, type text);
INSERT INTO "threads" VALUES(1,1,NULL);
INSERT INTO "threads" VALUES(2,1,NULL);
INSERT INTO "threads" VALUES(3,2,NULL);
CREATE TABLE addresses (_id integer primary key, address text);
INSERT INTO "addresses" VALUES(1,'HELLO');
INSERT INTO "addresses" VALUES(2,'BYE');
COMMIT;
sqlite> update threads set type = 106 where _id in
   ...> (select t._id from threads t, addresses  a
   ...>  where t.recipient_id = a._id and a.address like '%HELLO%');
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE threads (_id integer primary key, recipient_id integer, type text);
INSERT INTO "threads" VALUES(1,1,'106');
INSERT INTO "threads" VALUES(2,1,'106');
INSERT INTO "threads" VALUES(3,2,NULL);
CREATE TABLE addresses (_id integer primary key, address text);
INSERT INTO "addresses" VALUES(1,'HELLO');
INSERT INTO "addresses" VALUES(2,'BYE');
COMMIT;


text:
Q: Flink SQL table backed by CSV with header I have been searching on google for the last 20 minutes. I have gone through the Apache Flink documentation too specifically the CSV format but haven't found a way to skip the first header row.
The CSV looks like this:
AccountKey,InstrumentCode,Quantity,BuySell,Price
SB11,MSFT,100,Buy,250.57
SB11,AMZN,125,Sell,309

I really am looking for a property to set which will make the CSV reader skip the header row. The following table definition does not work:
CREATE TABLE trades (
    AccountNo varchar(10),
    Symbol varchar(10),
    Quantity integer,
    BuySell varchar(4),
    Price decimal
) WITH (
    'connector' = 'filesystem',
    'path' = '/mnt/d/Work/Github/Flink-Samples/data/trade-data.csv',
    'format' = 'csv'
);

The error I see on sql-client.sh is:
[ERROR] Could not execute SQL statement. Reason:
java.lang.NumberFormatException: For input string: "Quantity"

I expect the CSV reader reads the rows when I execute a
select * from trades

So far, the only way I have found is to put a # character to make the header appear as a comment and use the following table definition:
CREATE TABLE trades (
    AccountNo varchar(10),
    Symbol varchar(10),
    Quantity integer,
    BuySell varchar(4),
    Price decimal
) WITH (
    'connector' = 'filesystem',
    'path' = '/mnt/d/Work/Github/Flink-Samples/data/trade-data.csv',
    'format' = 'csv',
    'csv.allow-comments' = 'true'
);

A: Flink's connectors are designed for big amounts of data. Usually, CSV files are split into multiple files for efficient parallel processing.
In this case, a header would not make much sense because it would not be clear if the header is only located in the first file (which one is the first file?) and or in every file.
If there are headers in your file, you have the following options:

*

*Remove the header beforehand with a different tool.

*Pre-process the CSV file using a CSV format configured with a single STRING column and use OFFSET / LIMIT to skip first row before writing into a CSV file again. This is mostly useful for batch processing.

*Enable ignoring parse errors and use OFFSET / LIMIT to definitely skip the first row.

A: when you make csv-backed tables , you are just saying to read data from csv file , so you can't have headers in the file .
if you want to import csv file to an already existed table , you need ETL ,It's almost the case in any sql engine.
this blog is helpful how to transfer csv file into flink :
From Streams to Tables and Back Again

A: What eshirvana said, plus this workaround:
Use the csv.ignore-parse-errors option so that NumberFormatException fails silently.

A: This may be treading into hack territory, but one option to stay in the SQL context is to create a view that excludes the header row.
For example, the view below excludes the header row since column AccountNo would (likely) only equal AccountKey on the header row in the CSV.
CREATE VIEW trades_no_header AS SELECT * FROM trades WHERE AccountNo <> 'AccountKey';


text:
Q: Resize em imagem com PHP Necessito dar resize em todas as imagens quando for efetuado o compartilhamento no Facebook.
Existem várias imagens de diversos tamanhos na listagem de produtos, porém quando compartilho o link no Facebook, dependendo do tamanho da imagem, o Facebook colocar no box maior de imagem ou no box menor, dependendo do tamanho.
O que necessito fazer, é jogar para a meta OG a imagem com o tamanho alterado.
Encontrei uma função que dá resize, porém ela dá em porcentagem e eu necessito que a imagem seja reajustada para o tamanho exato de 600x315px.
Segue o código:
<?php
// Imagem e novo tamanho (em porcentagem)
$filename = '1.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagejpeg($thumb);

?>
<meta property="og:image" content=""/>

Após isto, necessito jogar a imagem reajustada na meta og.

A: Ao invés de usar:
$newwidth = $width * $percent;
$newheight = $height * $percent;

Mude para:
$newwidth = 600;
$newheight = 315;

Mas as imagens irão ficar esticadas.
Para pôr na sua meta do facebook:
<meta property="og:image" content="http://www.urldoseusite.com.br/pasta/onde/ficam/suas/imagens/<?php echo $filename; ?>"/>


text:
Q: Perl: Sort Array after a Hash-value Is there a "Perl-ish" way to sort a array of hashes after a hash-val?
my @l = ({k1 => "1", k2 => "one"}, {k1 => "2", k2 => "two"},
     {k1 => "3", k2 => "three"});

foreach (@l)
{
  print "\n" . $_->{k1} . ", " . $_->{k2};
}

The order I get is the order I inserted (what else...). But I'd like to sort it after a hash-value.
I can imagine the algorithmic-way. But I am asking about a maybe already existing function or something.
Thanks!

A: To sort by the value behind the k1 key, you can do as follows.
my @sorted = sort { $a->{k1} <=> $b->{k1} } @l;

The variables $a and $b are reserved special vars for sort. If your list-items are references, you can just use them as such.
Output with Data::Printer:
[
    [0] {
        k1   1,
        k2   "one"
    },
    [1] {
        k1   2,
        k2   "two"
    },
    [2] {
        k1   3,
        k2   "three"
    }
]

A: @list = sort { $a->{'k1'} <=> $b->{'k1'} } @l;


text:
Q: Autodesk Forge .NET SDK GetObject function and downloading files from BIM 360 Docs hub I am having trouble using the GetObject function from the Forge .NET SDK to download a file from a BIM 360 Docs hub.
Here is my jQuery ajax call (client side) :
function downloadFile(storageUrl, displayName) {
jQuery.ajax({
    url: '/api/forge/datamanagement/download?' + $.param({ storageUrl: storageUrl }),
    success: function (res) {
        // create a blob url representing the data
        var blob = new Blob([res]);
        var url = window.URL.createObjectURL(blob);
        // attach blob url to anchor element with download attribute
        var anchor = document.createElement('a');
        anchor.setAttribute('href', url);
        anchor.setAttribute('download', displayName);
        anchor.click();
        window.URL.revokeObjectURL(url);
    }
});

And here is my .NET C# corresponding controller function (server side) :
    [HttpGet]
    [Route("api/forge/datamanagement/download")]
    public async Task<dynamic> GetObject(string storageUrl)
    {
        Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);
        if (Credentials == null) { return null; }

        ObjectsApi objectsApi = new ObjectsApi();
        objectsApi.Configuration.AccessToken = Credentials.TokenInternal;

        string[] idParams = storageUrl.Split('/');
        string bucketKey = idParams[6];
        string objectName = idParams[8];
        if (objectName.Contains("?"))
            objectName = objectName.Split("?")[0];

        dynamic obj = await objectsApi.GetObjectAsync(bucketKey, objectName);

        if (obj is FileStream)
            return File(obj, "application/octet-stream");

        if (obj is MemoryStream ms)
        {
            FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), objectName), FileMode.Create, FileAccess.ReadWrite);
            ms.CopyTo(fs);
            ms.Position = 0;
            fs.Position = 0;
            return File(fs, "application/octet-stream");
        }

        return null;
    }

The trouble is after getting the result from GetObjectAsync call :

*

*If it returns a FileStream (like for .txt files), there is no problem, downloaded files are correct.

*If it returns a MemoryStream (like for .json and .rvt files), I write it in a FileStream then returns it. But it works only for .json files. For .rvt files, the downloaded files are corrupt and cannot be opened by Revit.

What is strange is that :

*

*the corrupt files are approximately 2 times bigger than the "real"/"correct" ones.

*when copying the MemoryStream into a FileStream the temporary created Revit files in my server temp folder are correct.

What am I missing here ?
Thanks for your help.
Maxime

A: There is probably an encoding issue here, as you mentioned the file is 2x bigger.
Anyway, I would suggest you use a "proxy" approach instead. Let me explain: the GetObjectAsync will download the entire file to your server, which can be big and allocate a lot of memory. Even if you save it locally before sending to the client, still allocating disk resources...
A proxy approach would just get chunks of data from Forge and stream each chunk to the client. There are different ways of implementing it, probably this other answer is a start.


text:
Q: how do i place DIVS side by side on Dreamweaver design view i have a rather annoying DIV problem, im working on dreamweaver CS5, and i have 2 DIVS inside of another container DIV. But they cant seem to stay next to each other on the design view of Dreamweaver, but when i preview them in a browser they are okay, they are only distorted in the design view, its kind of annoying working with them on top of each other.I have tried decreasing the size of the divs, but they just cant seem to stay side by side.! how do i solve this?

A: There is no substitute for a browser, or browsers as you need to test your site in all the latest browsers. I would switch off design view and have a browser open on the side or on your second monitor if you have one. You can setup scripts / browser add-ons that continuously refresh your browser so you can see your changes reflected.
Having said that, In Dreamweaver I suggest using live view instead of design view.
See that and other useful tips here: http://www.hongkiat.com/blog/10-useful-dreamweaver-tips-for-beginners/


text:
Q: Loop through all check boxes, weather it is checked or unchecked in PHP My problem is that the below code changes the value of the checked ones, but the index i is assigned to the checked ones only. I want it to pass through all check boxes. For examples if the first and last check boxes were checked, I am getting job[0] is "yes" and job[1] is "yes" and the rest are "no" while I should get "yes" for job[0] and job[4].
Code below:
if(!empty($_POST['job'])){

        $i = 0;
        $jobArray = array("no","no","no","no","no");

        // Loop to store and display values of individual checked checkbox.
        foreach($_POST['job'] as $selected){
            $jobArray[$i] = "yes";
            $i++;
        }
    } //$_POST['job']

A: The thing is that checkboxes values exist in your request only if they are checked. You should keep it in mind.
So, you can change your application logic to work with that. But if you really need to have an array with 'yes', 'no' values, just create it.
Let's say you create your checkboxes like so:
    <?php for ($i = 0; $i < 10; $i++): ?>
        <input type="checkbox" name="job[<?= $i ?>]" value="yes">
    <?php endfor; ?>

Then, in your code:
    $jobs = [];
    for ($i = 0; $i < 10; $i++) {
        $jobs[$i] = $_POST['job'][$i] ?? 'no';
    }


text:
Q: Differences between llvm and g++ on OSX 10.7 I upgraded to OSX 10.7 Lion this weekend, and now I'm trying to get all my unit and regression tests to pass... but there are quite a few problems. Several of my regression tests are now producing numerical results which differ (e.g. in the 3rd decimal place). This is a surprise because I get consistent results between OSX 10.6 and Linux, and for various compilers (because we already apply some tricks to keep the numerics stable enough to be comparable)... But it seems that OSX 10.7 is producing significantly different results. We could raise the threshold of course to get all these tests to pass, but I'd rather not because that weakens the test.
By default "g++" is now aliased to "llvm-g++-4.2". Can somebody explain to me what kinds of differences to expect in my results for g++ vs llvm? If I want to preserve my regression results, do I basically have to choose between llvm and -ffast-math?

A: Basic floating-point computation shouldn't be substantially different between llvm-gcc-4.2 and gcc-4.2 in the normal case; a basic floating-point operation will generate a functionally identical code sequence with llvm-gcc and gcc-4.2 (assuming default compiler flags).
You're mentioning -ffast-math; LLVM generally does relatively few additional optimizations when -ffast-math is used.  That could cause substantial differences if you're depending on the compiler to do certain transformations, I guess.
Beyond that, it's really hard to say without an actual testcase.


text:
Q: Canceled WCF REST downloads I have a REST service that returns large files via a Stream as the return type.  However I need a way to know how much of the file was transferred even if the download is canceled by the client.  What would be the best way to accomplish something like this?
So far I've come up with the following:
        public Message GetFile(string path)
    {
        UsageLog log = new UsageLog();

        return WebOperationContext.Current.CreateStreamResponse((stream) =>
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[_BufferSize];
                int bytesRead = 0;
                long totalBytesRead = 0;

                while (true)
                {
                    bytesRead = fs.Read(buffer, 0, _BufferSize);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    try
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                    catch (CommunicationException ex)
                    {
                        break;
                    }

                    totalBytesRead += bytesRead;
                }

                log.TransferCompletedUtc = DateTime.UtcNow;
                log.BytesTransferred = totalBytesRead;
            }
        },
        "application/octet-stream");
    }

I'm interested in hearing any other solutions to accomplishing something like this.


text:
Q: Counting appearance of (a,b) as a pair in a table. (SQL) I want to count the appearance of 2 attributes as a pair. For example count the number of times A=10 and B=5 but I do not specifically know what A and B are, just any instance where they match, find how often they match. In a table that has many A values, many B values, and many values of A=10, B=5.
Essentially I want to code something that works as if COUNT((a,b)) would work. How would I go about doing this? Thanks

A: Put that in a where and do a count(*) of matching rows. Something like
select count(*)
from your_table
where a = 10 and b = 5;

A: Assuming you want to count the number of instances of each permutation of A, B use an aggregated query:
select a, b , count(*)
from your_table
group by a, b
order by a, b


text:
Q: TYPO3 6.2 - 404 error page with realurl I've a TYPO3 CMS 6.2.15 running with realurl and the following LocalConfiguration.php:
'FE' => array(
    'pageNotFound_handling' => '/404/',
    'pageNotFound_handling_statheader' => "HTTP/1.0 404 Not Found",
    ...
), ...

I've created a page called "404" and tested if I can call that page like page.ending/404/. It works. But now I try a non-existing page like page.ending/asdfasdf/ and get the default Apache Unauthorized page. Why is that?
At least I get the correct 404 header information but why does it not redirect to the 404 page?

A: You have to change the corresponding line to:
'pageNotFound_handling' => 'REDIRECT:<your-404-url>',

A: First check php function curl is enable or not in your php.ini file. if curl is disable then first enable this function.
Then use below code in your LocalConfiguration.php file.
'FE' => [
    'pageNotFound_handling' => '/your-page-name/',
],


text:
Q: saving and retreiving variables I am a little new to c#. I was wondering, is there a simple way to save and retrieve a variable. I have written a program that when it closes, needs to save the variable so when I starts up again that the program stays in the same state from the last time it was executed. The program controls a fan, so if the fan was set to high for the last state, when the program starts again, I need the fan to run at high speed instead of starting at a different speed. Didn't know if simple enough to save to an excel file or is there something simpler.

A: Use json or xml to store your settings data. OnWindowloaded retrieve your settings from the respective file and update to it.
or
You can also define a custom configuration section and then put the settings in a separate config file if you didn't want to clutter up your app.config. A custom configuration module allows you to define a structure for your own complex settings and store them in a standard config file. If you have used Entity Framework, Enterprise Library or the like, then you have probably seen them defined at the top of the file. A quick search on Google turned up another StackOverflow post on the subject.
How to create custom config section in app.config


text:
Q: integrate : $\displaystyle\int \frac{x^2}{(3+4x-4x^2)^\frac{3}{2}}dx$ could somebody give me a hint on how to integrate this :  $$\displaystyle\int \frac{x^2}{(3+4x-4x^2)^\frac{3}{2}}dx$$
I have the impression that I must do some polynomial division but i have no idea to be honest.

A: Rewrite the integral as
$$=\int\frac{x^2\,\mathrm d\mkern1mux}{\bigl(4-(2x-1)^2\bigr)^{\tfrac32}}=\frac18\underbrace{\int\frac{x^2\,\mathrm d\mkern1mux}{\Bigl(1-\bigl(x-\frac12\bigr)^2\Bigr)^{\tfrac32}}}_I$$
and use substitution: $\; x=\sin t+\frac12$. You get:
\begin{align*}
I&=\int\frac{(\sin^2t+\sin t+\frac14)\cos t\,\mathrm d\mkern1mut}{\cos^3t}=\int\tan^2t\,\mathrm d\mkern1mut+\int\frac{\sin t\,\mathrm d\mkern1mut}{\cos^2t}+\frac14\int\frac{\mathrm d\mkern1mut}{\cos^2t}\\[1ex]
&=\tan t-t+\frac1{\cos t} +\frac14\tan t=\frac{5\sin t+4}{4\cos t}-t\\[1ex]
&=\frac{10x+3}{\sqrt{3+4x-4x^2}}-\arcsin\Bigl(x-\frac12\Bigr)
\end{align*}


text:
Q: Re-doing the same programming work as done on the job I am a co-op at a company and I was tasked with patching Roumen Petrov's OpenSSH w/ x509 certificates patch (http://www.roumenpetrov.info/openssh/) to include one of the features in his wanted list: wildcards in Distinguished Names. On his site he says that he will gladly accept patches.
After finishing, I asked my manager to implore the higher-ups if it was possible to release the patch to the public. Unfortunately, nothing ever came from it, the higher-ups forgot about the request.
The OpenSSH & the w/ x509 patch code is under a BSD license, so we are no legal requirement to release our changes.  However, as an avid user of open-source and finally able to contribute, I want to help Mr. Petrov in his efforts.  There is also a benefit to my company: the patch goes upstream and we do not have to maintain it between upstream-patch-versions.
I am an employee of the company (not a contractor), and thus my work at work is property of the company, and so I cannot release it without their approval (not that I would think of it).
I am wondering if I reproduce my changes on my own time, without looking or referencing the code generated at work, whether I could then release that patch.
Note: I could not find a copy of my employment contract anywhere, so I'm going to try to get a copy of it, but until then I cannot answer any specific questions about it.
Note 2: I realize you people are not lawyers. (Who are you callin' "you people?"!)

A:
the higher-ups forgot about the
  request

I would probably send a request. Something along the lines of

Dear whoever is responsible
  We're
  using open source software xyz for
  free in our company. In the course of
  my current work I have added feature
  which is used by our company but would
  be beneficial to public and I would
  like to submit it to open source
  community for inclusion in xyz. The
  pros of doing this are here summarize
  benefits that you outlined above. Let
  me know who is the best person to
  approve this. The sooner it can be submitted the sooner we don't have to maintain it.

Then keep pushing and asking until you get the approval.

A: First, you're right: people here probably aren't lawyers, and those that claim to be may be difficult to confirm.  It's very unsafe to trust any legal advice from Stack Overflow.
You should find yourself a lawyer who understands IP law and contract law (At the very least).  You'll need the lawyer to look at your employment contract (everything you signed, pre and post hiring) to determine if you've entered into an enforceable non-compete agreement.
This stuff is pretty serious.  I can't find the reference, but I've read of companies employing multiple teams who were mostly forbidden to communicate, and completely forbidden to read each others' code, in order to avoid tainting the company's proprietary software with software for which the company did not own the copyright.

A: You must be careful. I'm not sure how draconian the labor laws are in Indiana, but in Massachusetts, you'd be out of luck. The problem is that you have seen the IP and could be liable for derivative works. At this point, it's nearly impossible for you to build a "clean room" patch. It's not something I'd suggest doing without a paper trail of authorization.
I've worked with massively modified forks of MIT & BSD licensed code. I'm aware of ways to make these projects 100's of times faster, but these techniques and improvements are what give some companies their edge. They often have no interest in contributing and aren't required to, even if it makes sense.
The devil in me says do it anyway. Do what my former colleague does and release it under somebody else's name. Another colleague liked to say, asking for forgiveness is better than asking for permission. What's life worth without the risk of utter ruination?
On second thought, talk to your employer and really play up the benefits.

A: The tricky thing is it might be hard to prove the new work wasn't based on the work you did for your company; what an old teacher of mine called the "love boat defense" ("watch the love boat before doing your own work; anything that you write after watching such mind-draining pap is yours") won't work here. Even if the implementation is completely different but there are similarities in design, it could be considered a derivative work. If you could think of a completely new and unrelated design, you could mount a good defense in case it came to court, but it wouldn't prevent it from going to court (which is the real goal).
Of course, if your company brought you to court, they'd lose a valuable employee, so they might be hesitant to do so. Still, stefanB's advice is the safest route and keeps you on good terms with your employer.


text:
Q: do_shortcode() within Admin Page I'm using a few plugins that have shortcodes ... however, instead of creating a public page for the content, I've created some new pages within the admin using add_menu_page and I need to know how to utilize do_shortcode() within this context.
As it stands, all the function does it spit out the string. I'm assuming it's because the shortcode API isn't available within an admin page.
How do I get around this? There is no documentation that I can find that explains how to utilize shortcodes within the WP Admin... or if it's even possible.

Specifically I'm trying to utilize WooCommerce shortcodes within the WP Admin. I hate the fact that plugins don't utilize the WP Backend for account/user management.

A: It seems the shortcode API is available in the admin, but its output will depend on the shortcode tag in question.
The built-in [caption] works as expected, whereas [embed] doesn't (this is due to how the embed API "lazy-loads" it's shortcode, and depends on the_content filter to run, so technically not the shortcode API's fault).
Conclusion: It's entirely dependent on how & when the tag is registered, and what it does/assumes when executed.
@dcolumbus Which tag are we talking about in your case?

A: Instead of calling do_shortcode() just call the function associated with the shortcode.
Example
There is a shortcode named [example] and a function registered as shortcode handler:
function example_shortcode( $atts = array(), $content = '' )
{
    extract(
            shortcode_atts(
            array (
            'before' => '',
            'after' => '',
            ),
            $atts
       )
   );

    return $before . $content . $after;
}
add_shortcode( 'example', 'example_shortcode' );

In your admin page you just call the function:
echo example_shortcode(
    array ( 'before' => 'This ', 'after' => '!' ),
    'works'
);

Output: This works!.
Faster and more reliable than do_shortcode().


text:
Q: Using a TVS diode instead of, or in addition to a MOV for AC line protection? For 220 V AC mains voltage, is it good practice to replace a 300 V MOV with a 300 V bidirectional TVS diode (like in here http://www.littelfuse.com/products/tvs-diodes.aspx), or connect both in parallel? Are there any points that need to be considered?

A: The overvoltage protection circuit subject is complex and there simply isn't a one size fits all remedy.  Things to consider are: where will the circuit be located in relation to the service entrance, are you attempting to protect for short and/or long duration surges, and what type of surge are you planning on protecting against?  From my research, the best attempt at a one size fits all overvoltage protection scheme would include line conditioning filtering (inductors/capacitors), (MOV) Metal Oxide Varistors with integral thermal disconnect fuses and Silicon Avalanche Suppressor Diodes.  I would talk to the engineers at Littlefuse for advice.  They have a large library of downloadable PDF's pertaining to Overvoltage Suppression.

A: It comes downto what are you trying to protect against
There are four main types of transient suppression devices
Gas Tube

*

*Protection time: > 1us

*Protection Voltage: 60 - 100V

*PowerDissipation: Nil

*Reliable Performance:  No

*Expected Life: Limited

*Other:  Only 50-2500 surges, can short powerlines

MOV

*

*Protection time: 10 - 20ns

*Protection Voltage: > 300V

*PowerDissipation: Nil

*Reliable Performance:  No

*Expected Life: Degrades

*Other:  Fusing required. Degrades

Avalanche TVS

*

*Protection time: 50ps

*Protection Voltage: 3-400V

*PowerDissipation: low

*Reliable Performance:  yes

*Expected Life: long

*Other:  Low power dissipation. Bidirectional requires dual

Thyristor TVS

*

*Protection time: <3ns

*Protection Voltage: 30-400V

*PowerDissipation: Nil

*Reliable Performance:  yes

*Expected Life: long

*Other:  High Capacitance

http://www.onsemi.com/pub_link/Collateral/HBD854-D.PDF
( http://web.archive.org/web/20051001082352/http://www.onsemi.com/pub/Collateral/HBD854-D.PDF  )
http://www.vishay.com/docs/88440/failurem.pdf


text:
Q: Get internal application directory in Cordova + android I would like to know how to get the path where the app is installed on Android using Cordova. I want to use file API to get this information.
I have tried the solution implemented in this question, namely:
function gotFS(fileSystem) {
    console.log("got filesystem");
    // save the file system for later access
    console.log(fileSystem.root.fullPath);
    window.rootFS = fileSystem.root;
}

document.addEventListener('deviceready', function() {
    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}, false);

However, this gives me some path to external storage: file:///storage/emulated/0/.
I think requestFileSystem gives you external storage path if there is one available. How can I force requestFileSystem to give me internal path? (/data/data/appname)

A: from cordova file 3.0.0, the default LocalFileSystem.PERSISTENT is the /data/data/app.package
on previous versions you can get it using
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory, success, fail);

A: You will find the application folder at:
/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.


text:
Q: Removing entity with cascade Code:
@Entity
class Teacher implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column(nullable = false)
    @NotNull
    String name;
    @OneToMany(mappedBy = "teacher",cascade = CascadeType.REMOVE)
    List<Course> courses;
}

@Entity
public class Course implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column(nullable = false)
    @NotNull
    String name;
    @ManyToOne(cascade = CascadeType.REMOVE)
    Teacher teacher;
}

Three questions:

*

*Must I put CascadeType.REMOVE in both entities? I want it to work so that if I delete the teacher the course will be deleted automatically.

*In my database my id doesn't work normally. I want it so that the id increments by one each time, but it currently increases by some random number. Why?

*I have 2 more @Entity Classes but with @ManyToMany relationship. What must I to do when I want to persist a new object in the database?

A: *

*Probably a duplicate of one of these:
JPA: Cascade remove does not delete child
JPA 2.0 orphanRemoval=true VS on delete Cascade
https://stackoverflow.com/questions/22237631/jpa-does-not-cascade-delete-operation-from-parent-entity-to-child-entity
Have you checked those references?

*Need more intel

*You can persist each of them alone or an instance of Class A with an instance of Classe B attached or vice versa (assuming that you are using the proper CascadeType and @ManyToMany relationship and persistence framework that understands those two)


text:
Q: Point zero on an elliptic curve I am working on a library that allows me to work with elliptic curves. It is still at embryonic state, and so far it only consists of two classes, EllipticCurve and Point.
Right now I'm implementing the basic operations of existence, belonging, sum, reflection, etc.
Unfortunately, I'm stuck now that I have to implement the concept of zero, i.e., the point of the elliptic curve E crossing the line through P and -P, where P = (x,y) and -P = (x,-y). So, my question could be rephrased as "how do I implement a point at infinity?"
Here's part of the Point class so far:
public class Point implements Comparable<Point> {
    private static final BigDecimal MINUSONE = new BigDecimal(-1);

    private BigDecimal x;
    private BigDecimal y;
    private EllipticCurve e;

    public Point(BigDecimal x, BigDecimal y, EllipticCurve e) {
        if(x != null && y != null && e != null) {
            if(liesOn(x,y,e)) {
                this.x = x;
                this.y = y;
                this.e = e;
            }
        }
    }

    public Point reflect() {
        return new Point(x,y.multiply(MINUSONE),e);
    }

    public Point add(Point o) {
        if(this.e == o.getE()) {
            if(this == o) {
                return this.multiply(2);
            }
            if(o == this.reflect()) {
                return /*THE INFAMOUS ZERO POINT*/;
            }

            BigDecimal a;
            BigDecimal b;

            /*
             * computation I still haven't implemented
             */

            return new Point(a,b,e);
        }
    }
    /*
     * other methods
     */
}

P.S.: I am aware of the existence of java.security.spec.EllipticCurve, but since I'm going to use this class mostly for mathematical purposes, I felt the need to create my personal library ex novo.

A: There is no way to represent infinity per se using BigDecimal. The only way in Java I know is:
Double.POSITIVE_INFINITY;

or Integer, Float etc. You also can't take valueOf from the above, since it will throw a NumberFormatException.
You can use a workaround, i. e. a very large value that you know will always be larger than any other.


text:
Q: Faster way to transform text vector to numeric matrix/data.frame in R? I'm using R to parse out some server logs that produce lists that look like this:
myLog <- c("[1,2,3]","[4,5,6]","[7,8,9]")

What I want to produce from them is a matrix that looks like this:
myMatrix <- matrix(c(c(1,2,3),c(4,5,6),c(7,8,9)),nrow=3,byrow=T)

They come from querying a database field of type varchar so I don't think I can use any file-reading tricks.
I tend to have lots of these, millions of rows at a time.
What I've been doing is the following, it's quite slow:
splitDat <- sapply(inputVector,function(y){
  y1 <- gsub("\\[","",y)
  y2 <- gsub("\\]","",y1)
  y3 <- strsplit(y2,split=", ")
  y4 <- unlist(y3)
})

Is there a more efficient way? A one-liner regex?

A: You could try to vectorize this using the stringi package
library(stringi)
matrix(as.numeric(unlist(stri_extract_all_regex(myLog, pattern = "\\d"))),
                  nrow = 3, byrow = TRUE)

#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6
# [3,]    7    8    9

Benchmarks
library(stringi)
library(gsubfn)
library(microbenchmark)

set.seed(123)
myLog <- c("[1,2,3]","[4,5,6]","[7,8,9]")
myLog <- sample(myLog, 1e4, replace = TRUE)

Res <- microbenchmark(
               David = matrix(as.numeric(unlist(stri_extract_all_regex(myLog, pattern = "\\d"))), nrow = 3, byrow = TRUE),
               Thela = matrix(as.numeric(unlist(strsplit(myLog,"\\[|\\]|,"))),nrow=length(myLog),byrow=TRUE)[,-1],
               BD1 =  matrix(as.numeric(scan(text=gsub("\\D"," ",myLog),what="")), nrow=length(myLog),byrow=T),
               BD2 = matrix(as.numeric(scan(text=gsub("[],[]"," ",myLog), what="")),nrow=length(myLog), byrow=T),
               GG1 = read.table(text = gsub("\\D", " ", myLog)),
               GG2 = read.pattern(text = myLog, pat = "\\d")
)

Res
# Unit: milliseconds
# expr       min        lq      mean    median        uq       max neval
# David  12.01351  12.90111  16.41127  13.98826  15.62786 101.65117   100
# Thela  25.49944  27.09937  29.83234  28.32153  30.24141  80.79836   100
#   BD1  92.39541  94.81445 101.20524  98.07333 102.41877 172.60835   100
#   BD2  91.91578  94.66958 104.02773  96.94019 103.99383 206.37865   100
#   GG1  91.28813  94.29219  98.63825  96.57544 100.57172 140.97998   100
#   GG2 470.43382 514.58552 551.94922 540.86479 570.88711 815.75789   100

boxplot(Res)

A: 1) I haven't checked how fast this is but the code is very short:
library(gsubfn)
read.pattern(text = myLog, pat = "\\d")

where myLog is as in the question.
2) Here is a base solution:
read.table(text = gsub("\\D", " ", myLog))

A: This seems pretty quick (~2 secs on a million cases), though not as quick as the stringi solution by David:
matrix(as.numeric(unlist(strsplit(myLog,"\\[|\\]|,"))),nrow=length(myLog),
       byrow=TRUE)[,-1]

#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    4    5    6
#[3,]    7    8    9

Benchmarking on 30K cases (All but the first two actually caused my R session to become non-responsive when testing on 1 million cases):
myLog <- c("[1,2,3]","[4,5,6]","[7,8,9]")
myLog <- sample(myLog, 30000,replace=TRUE)

Fastest two:
library(stringi)
system.time(
matrix(as.numeric(unlist(stri_extract_all_regex(myLog, pattern = "\\d"))),
                  nrow = 3, byrow = TRUE)
)

#   user  system elapsed
#   0.03    0.00    0.03

system.time(
matrix(as.numeric(unlist(strsplit(myLog,"\\[|\\]|,"))),nrow=length(myLog),
       byrow=TRUE)[,-1]
)

#   user  system elapsed
#   0.05    0.00    0.04

Middling:
system.time(
matrix(as.numeric(scan(text=gsub("\\D"," ",myLog),what="")),
       nrow=length(myLog),byrow=T)
)

#Read 90000 items
#   user  system elapsed
#   0.57    0.00    0.58

system.time(
matrix(as.numeric(scan(text=gsub("[],[]"," ",myLog), what="")),
       nrow=length(myLog), byrow=T)
)

#Read 90000 items
#   user  system elapsed
#   0.59    0.00    0.59

system.time(
read.table(text = gsub("\\D", " ", myLog))
)

#   user  system elapsed
#   0.59    0.00    0.60

Slower:
library(gsubfn)
system.time(
read.pattern(text = myLog, pat = "\\d")
)

#   user  system elapsed
#   1.79    0.00    1.79

A:  myMatrix <- matrix(as.numeric(scan(text=gsub("[],[]"," ",myLog),
                                    what="")),
                    nrow=length(myLog), byrow=T)
#Read 9 items
myMatrix

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

Seeing G_G's pattern made me realize the negation of digit could be used in the gsub call:
> myMatrix <- matrix(as.numeric(scan(text=gsub("\\D"," ",myLog),what="")),nrow=length(myLog),byrow=T)


text:
Q: Error when computing mode of a DataFrameGroupBy object I have a dataframe with a Date column, I group the data by year and I can compute mean and median. But how to compute the mode? Here is the error I get:
>>> np.random.seed(0)
>>> rng = pd.date_range('2010-01-01', periods=10, freq='2M')
>>> df = pd.DataFrame({ 'Date': rng, 'Val': np.random.random_integers(0,100,size=10) })
>>> df
        Date  Val
0 2010-01-31   44
1 2010-03-31   47
2 2010-05-31   64
3 2010-07-31   67
4 2010-09-30   67
5 2010-11-30    9
6 2011-01-31   83
7 2011-03-31   21
8 2011-05-31   36
9 2011-07-31   87
>>> df.groupby(pd.Grouper(key='Date',freq='A')).mean()
                  Val
Date
2010-12-31  49.666667
2011-12-31  56.750000
>>> df.groupby(pd.Grouper(key='Date',freq='A')).median()
             Val
Date
2010-12-31  55.5
2011-12-31  59.5
>>> df.groupby(pd.Grouper(key='Date',freq='A')).mode()

Traceback (most recent call last):
  File "<pyshell#109>", line 1, in <module>
    df.groupby(pd.Grouper(key='Date',freq='A')).mode()
  File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 554, in __getattr__
    return self._make_wrapper(attr)
  File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 571, in _make_wrapper
    raise AttributeError(msg)
AttributeError: Cannot access callable attribute 'mode' of 'DataFrameGroupBy' objects, try using the 'apply' method

A: *

*use np.unique with the return_counts parameter.

*use the argmax on the counts array to get value from unique array.

*use np.apply_along_axis for a custom function mode

def mode(a):
    u, c = np.unique(a, return_counts=True)
    return u[c.argmax()]

df.groupby(pd.Grouper(key='Date',freq='A')).Val.apply(mode)

Date
2010-12-31    67
2011-12-31    21
Freq: A-DEC, Name: Val, dtype: int64

A: mode isn't a built in function that's automatically compatible with pandas groupby objects. You could use the scipy.stats module. This feels a little clunky, though.
from scipy import stats

df.groupby(pd.Grouper(key='Date',freq='A')).apply(stats.mode)

Alternatively, you could use the value_counts() function and take the first index value returned. This is the route I would go.
df.groupby(pd.Grouper(key='Date', freq='A')).value_counts()[0].index.values[0]

A: mode is problematic as others have mentioned, however a DataFrameGroupby object can be applied a trivial lambda function, just as the AttributeError suggests using (and contains no ugly slicing or anything else):
df.groupby(grouping_column)[[i for i in pivotable_columns]].apply(lambda x: x.mode())]


text:
Q: ERROR Error: Uncaught (in promise): invalid link: LoginPage I have started with ionic 3 ("@ionic/app-scripts": "3.1.6") and getting this error. I checked this link and many others but none of them is helpful in my case.

ERROR Error: Uncaught (in promise): invalid link: LoginPage

app.component.ts:
const unsubscribe = firebase.auth().onAuthStateChanged( user => {
  if (!user) {
    this.rootPage = 'LoginPage';
    unsubscribe();
  } else {
    this.rootPage = HomePage;
    unsubscribe();
  }
});

login.ts:
@IonicPage({
  name: 'login'
})
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
    // ......
}

It worked initially but now it's not working and showing the same error.
Please let me know if I'm missing any other configurations.
EDIT: package.json:
{
  "name": "my-places",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "5.0.3",
    "@angular/compiler": "5.0.3",
    "@angular/compiler-cli": "5.0.3",
    "@angular/core": "5.0.3",
    "@angular/forms": "5.0.3",
    "@angular/http": "5.0.3",
    "@angular/platform-browser": "5.0.3",
    "@angular/platform-browser-dynamic": "5.0.3",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic/pro": "1.0.16",
    "@ionic/storage": "2.1.3",
    "ionic-angular": "3.9.2",
    "ionicons": "3.0.0",
    "rxjs": "5.5.2",
    "firebase": "4.8.0",
    "angularfire2": "^5.0.0-rc.4",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.6",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project",
  "config": {
    "ionic_source_map": "source-map"
  }
}

A: You're using lazy-load, but you're also changing the name of the page:
@IonicPage({
  name: 'login' // <---- here!
})
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
    // ......
}

As you can see in the IonicPage docs:

As mentioned previously, the name property will be set to the class
  name if it isn't provided. Changing the name of the link is extremely
  simple. To change the name used to link to the component, simply pass
  it in the decorator like so:
@IonicPage({
  name: 'my-page'
})

This will create a link to the MyPage component using the name
  'my-page'. Similar to the previous example, the page can be navigated
  to by using the name:
goToMyPage() {
  // go to the MyPage component
  this.navCtrl.push('my-page');
}

So if you choose the name 'login' in the @IonicPage decorator, use the same name when trying to use that page: this.rootPage = 'login';

A: It seems you're using Angularfire2. So you can do it very easily like so,
app.component.ts
import { AngularFireAuth } from 'angularfire2/auth';

constructor(private afAuth: AngularFireAuth) {
     this.afAuth.authState.subscribe(user => {
      if (user) {
          this.rootPage = 'HomePage';
      } else {
          this.rootPage = 'LoginPage';
      }
    });
 }


text:
Q: How to calculate precision and recall for two nested arrays I have two arrays like:
correct = [['*','*'],['*','PER','*','GPE','ORG'],['GPE','*','*','*','ORG']]
predicted = [['PER','*'],['*','ORG','*','GPE','ORG'],['PER','*','*','*','MISC']]

Length of correct and predicted is same(10K+) also the length of each positional element in two arrays have the same length.
I want to calculate the precision, recall, and f1 score for such two arrays using python.
I Have following 6 classes:
  'PER','ORG','MISC','LOC','*','GPE'
want to calculate precision and recall for 5 of the classes (Except '*') also to find f1 score.
what can be the efficient way to perform this using python?

A: You have to flatten your lists as shown here, and then use classification_report from scikit-learn:
correct = [['*','*'],['*','PER','*','GPE','ORG'],['GPE','*','*','*','ORG']]
predicted = [['PER','*'],['*','ORG','*','GPE','ORG'],['PER','*','*','*','MISC']]
target_names = ['PER','ORG','MISC','LOC','GPE'] # leave out '*'

correct_flat = [item for sublist in correct for item in sublist]
predicted_flat = [item for sublist in predicted for item in sublist]

from sklearn.metrics import classification_report
print(classification_report(correct_flat, predicted_flat, target_names=target_names))

Result:
             precision    recall  f1-score   support

        PER       1.00      0.86      0.92         7
        ORG       1.00      0.50      0.67         2
       MISC       0.00      0.00      0.00         0
        LOC       0.50      0.50      0.50         2
        GPE       0.00      0.00      0.00         1

avg / total       0.83      0.67      0.73        12

In this particular example, you will also get a warning:
UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in labels with no true samples.

which is due to 'MISC' not being present in the true labels here (correct), but arguably this should not happen in your real data.


text:
Q: How to reset/reload/restart a Google Form I would like to display a feedback google form in kiosk mode on a tablet. After form completion, it should show a "thank you" message and restart the form for the next visitor.
I noticed a "Show link to submit another response" in the form settings menu, but no way to accomplish a auto refresh.
Fortunately there is the google's script manager. As the script runs in a sandboxed iframe, I cant even access the window object. I know that I can access the FormApp.getActiveForm() method, but there seem to be no way to reset/reload the form.
I can't think of another way doing it.