text:
Q: Very Strange MySQL Results Can someone explain this... before I have myself committed? The first result set should have two results, same as the second, no?
mysql> SELECT * FROM kuru_footwear_2.customer_address_entity_varchar
    -> WHERE attribute_id=31 AND entity_id=324134;

+----------+----------------+--------------+-----------+-------+
| value_id | entity_type_id | attribute_id | entity_id | value |
+----------+----------------+--------------+-----------+-------+
|   885263 |              2 |           31 |    324134 | NULL  |
+----------+----------------+--------------+-----------+-------+
1 row in set (0.00 sec)

mysql> SELECT * FROM kuru_footwear_2.customer_address_entity_varchar
    -> WHERE value_id=885263 OR value_id=950181;
+----------+----------------+--------------+-----------+-------+
| value_id | entity_type_id | attribute_id | entity_id | value |
+----------+----------------+--------------+-----------+-------+
|   885263 |              2 |           31 |    324134 | NULL  |
|   950181 |              2 |           31 |    324134 | NULL  |
+----------+----------------+--------------+-----------+-------+
2 rows in set (0.00 sec)

attribute_id is a SMALLINT(5)
entity_id is a INT(10)

A: The problem is that you have a unique index on (entity_id,attribute_id). The query optimizer notices this when you write a query whose WHERE clause is covered by the index, and only returns 1 row since the uniqueness of the index implies that there's at most one matching row.
I'm not sure how you can have those duplicates in the first place, it seems like there's something corrupted in the table. Adding a unique index to a table will normally remove any duplicates. In fact, this is often suggested as a way to get rid of duplicates in a table, see How do I delete all the duplicate records in a MySQL table without temp tables.

A: In the first statement's selection (the 'WHERE' clause), you are using AND; in the second statement, you are using OR. This boils down to the definition of these logical operators. MySQL's official documentation doesn't say much about these other than that AND and OR are their own natural logical operators. If this is confusing, you may want to read up on basic Boolean Algebra.


text:
Q: Excel VBA Random color stored as variable I have the following code which generates a random color and colors "Heading" rows in my worksheet. How can I store this as a variable, and then use it to color the row? (My goal is also to use this variable to color associated column cells with the same color). Also, I'm pretty sure there is a way to clean up this code so it doesnt waste time searching empty rows?

Sub ColorSuperProjectHeadings()
Dim r As Byte, g As Byte, b As Byte
Dim r2 As Byte, g2 As Byte, b2 As Byte
Dim spcolor As Integer
    Dim vR(), n As Integer
    'Cells.Clear
    n = 3000
    ReDim vR(1 To n)
    For i = 1 To n
        r = WorksheetFunction.RandBetween(0, 127)
        g = WorksheetFunction.RandBetween(0, 127)
        b = WorksheetFunction.RandBetween(0, 127)
        r2 = r + 127
        g2 = g + 127
        b2 = b + 127
        'vR(i) = RGB(r, g, b)
        vR(i) = RGB(r2, g2, b2)
    Next i

    Application.ScreenUpdating = False
        With ActiveSheet

    For Each cell In .Range("Y5:" & .Range("Y1500").End(xlDown).Address)
        If .Cells(cell.Row, 25).value = "Super Project" Then
            cell.EntireRow.Interior.Color = vR(WorksheetFunction.RandBetween(1, n))
        End If
    Next
End With
    Application.ScreenUpdating = True
End Sub

A: This code will color the column to the left of the heading for every heading except for the last one.  So you can play around with it to get the last bit to work but the basic functionality is there.
Sub ColorSuperProjectHeadings()

    Dim r As Byte, g As Byte, b As Byte
    Dim r2 As Byte, g2 As Byte, b2 As Byte
    Dim spcolor As Integer
    Dim vR() As Long
    Dim n As Integer
    Dim currentCell As Range
    Dim lastHeader As Range
    Dim lCurrentHeaderColor As Long
    Dim lLastHeaderColor As Long

    'Cells.Clear
    n = 3000
    ReDim vR(1 To n)
    For i = 1 To n
        r = WorksheetFunction.RandBetween(0, 127)
        g = WorksheetFunction.RandBetween(0, 127)
        b = WorksheetFunction.RandBetween(0, 127)
        r2 = r + 127
        g2 = g + 127
        b2 = b + 127
        'vR(i) = RGB(r, g, b)
        vR(i) = RGB(r2, g2, b2)
    Next i

    Application.ScreenUpdating = False
        With ActiveSheet
            For Each cell In .Range("Y5:" & .Range("Y1500").End(xlDown).Address)

                Set currentCell = .Cells(cell.Row, 25)

                If currentCell.Value = "Super Project" Then
                    lCurrentHeaderColor = vR(WorksheetFunction.RandBetween(1, n))
                    cell.EntireRow.Interior.Color = lCurrentHeaderColor

                    If Not lastHeader Is Nothing Then
                        For i = (lastHeader.Row + 1) To (currentCell.Row - 1)
                            'Stop
                            .Cells(i, lastHeader.Column - 1).Interior.Color = lLastHeaderColor
                        Next i
                    End If

                    Set lastHeader = currentCell
                    lLastHeaderColor = lCurrentHeaderColor
                End If
            Next
        End With
    Application.ScreenUpdating = True
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Piping Data with f_open I have a piece of code, the issue is the file "data" is over 8GB. This is very memory intensive. I want to reduce the usage of RAM and saw the f_load would be ideal, however, how could i explode this data?
This is my current code:
$data = file_get_contents("data");
$data = explode("|", $data);
foreach ($data as $d) { // rest of code

theoretically, i need to open a pipe, stream and close a pipe How would i go about this?
I've tried using f_open rather than file_get_contents but  errors started popping up so i'm doing something wrong and would really like to learn.

A: You can use stream_get_line to read your data block per block (with | as the delimiter character) : PHP stream_get_line()
$fh = fopen('data', 'r'); // open the file in read-only mode

while( $d = stream_get_line($fh, 1000, '|') ) // read the file until the next |
{
    echo $d . PHP_EOL ; // display one block of data
}

fclose($fh); // close the file


text:
Q: Finding the infinite limit using definitions I would really need help proving the following limit using the definitions. My textbook gives me a solution but with very minimal explanation and I'm completely lost.
This is the limit I have to find.

$$\lim_{x\to1^+} \frac{x}{x-1}$$

A: Fix $C>0$ and set $\delta := \frac{1}{C} > 0 $. For $x \in (1,1+\delta)$ we have that ${\frac{x}{x-1}} \geq \frac{1}{\delta} = C$. Thus by definition $ \lim_{x \rightarrow 1^+} \frac{x}{x-1} = \infty $.

A: Firstly, we guess that $$\lim_{x \to 1^+} \frac{x}{x - 1} = +\infty$$
By definition, we need to show $\forall M > 0$ $\exists \delta > 0$ such that $\forall x \in (1, 1 + \delta)$ $$\frac{x}{x - 1} > M$$
Now we work backwards, observe $$\frac{x}{x - 1} = \frac{x - 1 + 1}{x - 1} = 1 + \frac{1}{x - 1}$$
So we need to find $\delta > 0$ such that $$\frac{1}{x - 1} > M - 1$$
Without loss of generality we may assume $M > 1$, since if the $\delta$ works for a larger $M$, it will also works for a smaller $M$.
Using $x > 1$, we have $x - 1 > 0$, so
$$x < \frac{1}{M - 1} + 1$$
Since $\frac{1}{M - 1} < \frac{1}{M}$,
$$x < \frac{1}{M} + 1$$
Recall that $x$ satisfies the assumption that $x < 1 + \delta$.
So taking $\delta = \frac{1}{M}$ and we are done.


text:
Q: How to write an indexed loop over a list in Python? I have the following code that takes a string biology_score and after splitting it, converts it into a string ('b'). The desired output is to produce what I have constructed manually below (a list of users with their corresponding scores)
I would be interested in the most efficient way to construct a for loop to achieve this with a list. Note: I am aware that the best way to approach this would be a dictionary, but these purposes I want to use a list.
Code:
biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
print(b) #prints lists
print(b[2]) #prints element in index 2 in the list

#desired output
print(b[0],"scored",b[1])
print(b[2],"scored",b[3])
print(b[4],"scored",b[5])

#create a for loop to do the above

Required answer

*

*The most elegant solution (for loop to produce the above by looping through the list)

*The easiest/quickest method to convert the string to a dictionary, using the least number of steps, and then achieving the same output (user: score)

A: I'm not sure if this is what you're looking for:
biology_score="user1,30,user2,60,user3,99"
print(biology_score[1]) #for testing purposes
b=biology_score.split(",")
biology_dict = {}

for i in range(0, len(b), 2):  #looks only at even indices
    print(b[i],"scored",b[i+1])
    biology_dict[b[i]] = b[i+1]

A: If this is what you need.
#create a for loop to do the above
for i in range(0,len(b)-1,2):
  print(b[i],"scored",b[i+1])

Note: Python versions <3.6 does not support element orders. So, when you go with dict, the order might not be retained.

A: One of the options is to use dictionary
If the iterables are of uneven length, missing values are filled-in with fillvalue
import itertools
d = dict(itertools.zip_longest(*[iter(biology_score.split(","))] * 2,
fillvalue=""))

for k, v in d.items():
    print(k,'scored', v)

A: You can use the grouper recipe from the itertools module:
import itertools
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

Then:
for user, score in grouper(b, 2):
    print(user, 'scored', score)

To make a dictionary:
dictionary = dict(grouper(b, 2))
for user, score in dictionary.items():
    print(user, 'scored', score)

Or use an OrderedDict if the original order of the items should be preserverd.

A: Mostly a rewrite of @chngzm's answer, and it's probably unsuitable for your teaching purposes, but using a generator is quite nice:
def user_scores(scores):
  s = scores.split(",")
  for idx in range(0, len(s), 2):
    yield s[idx], s[idx+1]

biology_score="user1,30,user2,60,user3,99"

for user, score in user_scores(biology_score):
  print("{0} scored {1}".format(user, score))

biology_dict = dict(s for s in user_scores(biology_score))
for user in biology_dict:
  print("{0} scored {1}".format(user, biology_dict[user]))

A: One Pythonic way to get the desired result is to use zip:
biology_score = "user1,30,user2,60,user3,99"
values = biology_score.split(',')
print(dict(zip(values[::2], values[1::2])))
# {'user2': '60', 'user3': '99', 'user1': '30'}

If you want integer scores, you can use map:
print(dict(zip(values[::2], map(int, values[1::2]))))
# {'user2': 60, 'user3': 99, 'user1': 30}


text:
Q: latex error: environment proof undefined hi i am using latex... wanted to use the following:
       \begin{proof}
       ...
       \end{proof}

it gives me the following error:
!Latex error: Environment proof undefined. can you help me to solve this problem? thanks

A: The proof environment is part of AMS-LaΤεχ, not plain LaΤεχ, so you need to:
\usepackage{amsthm}

See this AMS-LaTeX page for details. If you don't already have the packages installed, grab them at http://www.ams.org/tex/amslatex.html

A: The proof environment requires the amsthm package.
amsthm is contained in amsmath which you can get from the AMS-LaTeX package here.


text:
Q: AddComment on multiple sheets vba Excel The AddComment syntax works on first selected sheet in workbook, but for the next one gives me this error: Error 1004 "Application-defined or Object-defined error". I do not know why crashes if multiple sheets were selected and works only for the first selected one. Does anyone have some idea?
 If selectedSheet.Cells(7, columnIndex).value <> 100 Then
           selectedSheet.Cells(7, columnIndex).Interior.ColorIndex = 3

           If standardReportFilePath <> "" Then 'not using the Standard Report Evalution algorithm
                        If VerifyStandardReportFile(selectedSheet.Name, selectedSheet.Cells(1, columnIndex).value, wbk, amplitude, missingCrashes) = True Then
                                selectedSheet.Cells(1, columnIndex).Interior.ColorIndex = 36 ' color the crash cell with yellow
                                Set rng = selectedSheet.Cells(1, columnIndex)
                                If rng.Comment Is Nothing Then
                                    **rng.AddComment "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"**
                                Else
                                    rng.Comment.Text "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"
                                End If
                            End If
                        End If
                    End If
                End If

An alternate set of code that shows the problem.  (Run this with three blank worksheets in a new workbook.):
Sub test()
    Dim ws As Worksheet
    Dim Rng As Range

    'Running code with a single sheet selected
    Worksheets("Sheet1").Select

    'Code that shows issue - this will work
    Set ws = Worksheets("Sheet2")
    Set Rng = ws.Cells(1, 1)
    If Rng.Comment Is Nothing Then
        Rng.AddComment "xxx"
    End If

    'Get rid of comment again
    Rng.Comment.Delete

    'Running code with multiple sheets selected
    Worksheets(Array("Sheet1", "Sheet2", "Sheet3")).Select

    'Code that shows issue - will crash on the "AddComment"
    Set ws = Worksheets("Sheet2")
    Set Rng = ws.Cells(1, 1)
    If Rng.Comment Is Nothing Then
        Rng.AddComment "xxx"
    End If

End Sub

A: I found a workaround, but still don't know why this problem even happens. For some reason error occurs when you have more then one worksheet selected. The solution is... To select one sheet before adding comments with someSheet.Select. At the end of macro you can try to select all previously selected sheets again if needed.

A: What I do understand - thanks to Yoweks comment - is:
You are looping through all the selected sheets, check something, set comments (giving you the problems, because it does'nt work with more than one selected sheet) and want the previosly selected sheets to be selected afterwards.
You can save the previosly selected sheet in a variable, select one of them, run your code and then select all previosly selected sheets again. PLease try the following code:
Sub Comments()
Dim WsArr As Sheets, WS As Worksheet, ColIdx As Long
ColIdx = 7
Set WsArr = ActiveWorkbook.Windows(1).SelectedSheets
    WsArr(1).Select
    For Each WS In WsArr
        '*** your logic
        Set Rng = WS.Cells(1, ColIdx)
        If Rng.Comment Is Nothing Then
            Rng.AddComment "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude"
        Else
            Rng.Comment.Text "Changed T"
        End If
    Next WS
    WsArr.Select
End Sub

A: From the Excel documentation

You can add notes to individual cells by using comments

You can see in the 'Review' tab within Excel that, when you select multiple sheets, you cannot create a comment. I assume this is to do with Excel's internals determining which cell should have a comment assigned to it.

Here is a function which you can call to assign a comment to a given cell, even if you have multiple sheets selected.
This sub also removes the need to test if a comment already exists, simply pass a new comment to a cell which already has one.
Sub UpdateComment(Rng As Range, Cmnt As String)
    Application.ScreenUpdating = False
    ' Get currently selected sheets
    Dim mySheets As Sheets: Set mySheets = ThisWorkbook.Windows(1).SelectedSheets
    ' Set current selection to just one sheet: this is where error is avoided
    ThisWorkbook.Sheets(1).Select
    ' Set Comment, new if doesn't exist or changed if it does
    If Rng.Comment Is Nothing Then
        Rng.AddComment Cmnt
    Else
        Rng.Comment.Text Cmnt
    End If
    ' Tidy up: re-select sheets & enable screen updating
    mySheets.Select
    Application.ScreenUpdating = True
End Sub

Use it like so in your code:
' ... your previous code
Set rng = selectedSheet.Cells(1, columnIndex)
UpdateComment rng, "In standard report this crash starts to deploy from ..."

To loop over all selected sheets
Dim sh As Worksheet
For Each sh In ThisWorkbook.Windows(1).SelectedSheets
    Set rng = sh.Cells(1, columnIndex)
    UpdateComment rng, "In standard report this crash starts to deploy from ..."
Next sh

A: I had the same problem while trying to get a comments function to work so instead of trying to figure it out per scenario, I decided to do a general one; call as needed.
Sub General_Functions_Comments(InCell As Range, TxtComment As String, Optional IsMergedAnalyzed As Boolean)
Dim IsComment As Comment
Dim RangeFixedMerged As Range
    If InCell.MergeCells = False Or IsMergedAnalyzed = True Then ' 3. If InCell.MergeCells = False
    With InCell
    Set IsComment = .Comment
    If IsComment Is Nothing Then ' 1. If Iscomment Is Nothing
    .AddComment.Text Text:=TxtComment
    .Comment.Shape.TextFrame.AutoSize = True
    .Comment.Visible = False
    Else ' 1. If Iscomment Is Nothing
    If InStr(.Comment.Text, TxtComment) Then ' 2. If InStr(.Comment.Text, TxtComment)
    Else ' 2. If InStr(.Comment.Text, TxtComment)
    .Comment.Text .Comment.Text & Chr(10) & TxtComment
    .Comment.Shape.TextFrame.AutoSize = True
    .Comment.Visible = False
    End If ' 2. If InStr(.Comment.Text, TxtComment)
    End If ' 1. If Iscomment Is Nothing
    End With
    Else ' 3. If InCell.MergeCells = False
    Set RangeFixedMerged = InCell.Cells(1, 1)
    Call General_Functions_Comments(RangeFixedMerged, TxtComment, True)
    Set RangeFixedMerged = Nothing
    End If ' 3. If InCell.MergeCells = False
End Sub

In your code
If standardReportFilePath <> "" Then 'not using the Standard Report Evalution algorithm
                        If VerifyStandardReportFile(selectedSheet.Name, selectedSheet.Cells(1, columnIndex).Value, wbk, amplitude, missingCrashes) = True Then
                                selectedSheet.Cells(1, columnIndex).Interior.ColorIndex = 36 ' color the crash cell with yellow
                                Set Rng = selectedSheet.Cells(1, columnIndex)
                                If Rng.Comment Is Nothing Then
                                Call General_Functions_Comments(Rng, "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude", True)
                                Else: Call General_Functions_Comments(Rng, "In Standard Report this crash starts to deploy from " & CStr(amplitude) & " amplitude", True)
                                End If
                            End If
                        End If
                    End If
                End If

*Aside question, why to set an if, else statement if both will do the same?

A: I remember generally similar case (I could not do something from code), trying hard to solve it and finally I found that...
Note that if you have multiple sheets selected, "New comment" button on the ribbon is inactive, so you just can't do it from code if you cannot do it manually.
Why? - don't ask me. I see a nice workaround above, which seems to be the only way to achieve what you need.


text:
Q: ssh bash script No such file or directory I am trying to run a script from /var/www/backups/scripts and when i try tell it to zip up a file i get the below error,
I can confirm that /var/www is the home dir and that the scripts work when ran manually though putty but just not though a script.
I'm using the below code to run the zip
#!/bin/bash
unset PATH

#USER VARS

HOMEDIR=~/
BACKUP_TARG_DIR=~/sites/backups/auto
BACKUP_TEMP_NAME=tempBackupFile.tar
BACKUP_TARG_FILE=/var/www/back
DATE=`/bin/date '+%Y-%m-%d'`

echo  `/bin/pwd`;

tar -zcvf test.rar /var/www/backups/scripts/tryThis

#cd /var/www
#scp "tempBackupFile.tar" 217.41.51.14:~/testfile.rar;
#tar -zcvf $BACKUP_TEMP_NAME $BACKUP_TARG_FILE;
echo "SITE-"$DATE;

below is the output i get
/var/www/backups/scripts
./autoBackup.bash: line 18: tar: No such file or directory
SITE-2011-09-05

Any one have any ideas as this is killing me, all I can think of is its something to do with where the bash script is being run from.

A: Why do you unset PATH ?? No wonder bash cannot execute tar.

A: Check your /etc/ssh/sshd_config to make sure that you don't have a chroot directory set.  If you do, you will need to either create a bin directory in the chroot directory and either copy or link the necessary binaries into that directory.
Or you could always comment that line out in the config.
Either way, restart sshd and test.


text:
Q: user.save() is not a function when i am trying to save the model   const user = User.findOne({email:req.body.email});

      if(!user){
        return next(new ErrorHander("User not found",404));

      }
 const resetToken = user.getResetPasswordToken

  await user.save({ validateBeforeSave: false });

I dont know why user.save is not working in mern mongodb i have same peice of code working for other person but not for me
What i did is that i get the user by fireing the query in the line one after having that user i should be able to use user.save() function here but sadly it is giving error
//here is my model schema
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const crypto = require("crypto")

const jwt = require("jsonwebtoken");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "please Ente the your name"],
  },
  email: {
    type: String,
    required: [true, "Please Enter the email"],
    unique: [true],
    validate: [validator.isEmail, "Please Enter a valid email"],
  },
  password: {
    type: String,
    required: true,
    minlength: [8, "Passwaord must be more that 8 characters"],
    select: false,
  },
  avatar: {
    public_id: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
  },
  role: {
    type: String,
    default: "user",
  },
  resetPasswordToken: String,
  resetPasswordTokenExpire: Date,

  createdAt: {
    type: Date,
    default: Date.now,
  },
});

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

  this.password = await bcrypt.hash(this.password, 10);
});

userSchema.methods.comparePassword = async function (password) {
  return await bcrypt.compare(password, this.password);
};

userSchema.methods.getJWTToken = function () {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE,
  });
};

// compare password

// userSchema.methods.comparePassword = async function(enterPass){
//     return await bcyrypt.compare(enterPass,this.password)
// }

// Reset Password

userSchema.methods.getResetPasswordToken = function(){
  const resetToken = crypto.randomBytes(20).toString("hex");
  this.resetPasswordToken = crypto.createHash("sha256").update(resetToken).digest("hex");
  this.resetPasswordTokenExpire = Date.now +15*60*1000;

  return resetToken;
}

module.exports = mongoose.model("User", userSchema);

A: User.findOne will return a Promise. So you need to add await keyword.
const user = await User.findOne({email:req.body.email});

      if(!user){
        return next(new ErrorHander("User not found",404));

      }
 const resetToken = user.getResetPasswordToken

  await user.save({ validateBeforeSave: false });


text:
Q: OpenCV 3.0 SVM Assertion Error using Python I'm using the Python OpenCV wrapper and I want to implement a simple classifier using a SVM. At first I create an matrix filled with zeros which has a shape of:
np.zeros( (len(positives)+len(negatives), samples_height*samples_width), dtype = np.float32)

After that I load all positive and negative samples as a row into the matrix:
for i, file in enumerate(os.listdir("svm_data/positives")):
    image = cv2.imread("svm_data/positives/"+file, 0)
    traindata[i,:] = np.ravel(image)
    labels.append(0)

for i, file in enumerate(os.listdir("svm_data/negatives")):
    image = cv2.imread("svm_data/negatives/"+file, 0)
    traindata[positives+i,:] = np.ravel(image)
    labels.append(1)

Finally I setup the SVM:
self.svm = cv2.ml.SVM_create()
self.svm.setType(cv2.ml.SVM_C_SVC)
self.svm.setGamma(0.5)
self.svm.setC(30)
self.svm.setKernel(cv2.ml.SVM_LINEAR)
self.svm.train(traindata, cv2.ml.ROW_SAMPLE, np.array(labels, dtype = np.int32))
self.svm.save('svm.dat')

Btw. it seems that svm.load ist not implemented yet.
But now if I want to test my trained SVM with an image from my positives folder (or any other image) by calling:
image = np.float32(cv2.imread("svm_data/positives/158_233_486.png", 0))
print self.svm.predict(np.ravel(image))

The program will terminate and throw

OpenCV Error: Assertion failed (samples.cols == var_count && samples.type() == CV_32F) in predict

I read a few posts which answers "The error means, that the input image does not have the same size or type like the samples" but the output of:
    print traindata[i,:].shape
    print traindata[i,:].dtype

    print np.ravel(image).shape
    print np.ravel(image).dtype

is
(1681,)
float32
(1681,)
float32

and now I'm very confused and I hope anyone can help me.
Thanks
---------------- UPDATE ----------------
It seems that there is a problem with the shape of my sample matrix.
I added a few prints above the line 1930 in svm.cpp
printf("samples.cols: %d\n", samples.cols);
printf("var_count: %d\n", var_count);
printf("samples.type(): %d\n", samples.type());
printf("CV_32F: %d\n", CV_32F);

CV_Assert( samples.cols == var_count && samples.type() == CV_32F );

After a OpenCV rebuild my output was:
samples.cols: 1
var_count: 1681
samples.type(): 5
CV_32F: 5

OpenCV Error: Assertion failed (samples.cols == var_count && samples.type() == CV_32F) in predict, file opencv/modules/ml/src/svm.cpp, line 1938

---------------- UPDATE ----------------
Ok I've got it!
image = np.float32(cv2.imread("svm_data/positives/158_233_486.png", 0))
print self.svm.predict(np.ravel(image))

The loaded image is a 1xn matrix but svm predict expect in my case a nx1 array,  so this fixes for me :)
print self.svm.predict(np.ravel(image)[None, :])


text:
Q: Android device monitor don't launch in Ubuntu I'm trying to launch Android device monitor and i keep getting a window with these informations :
JVM terminated. Exit code=1
/usr/bin/java
-XX:MaxPermSize=256m
-Xms512m
-Xmx1024m
-jar /home/ak/Android/Sdk/tools/lib/monitor-x86_64//plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/ak/Android/Sdk/tools/lib/monitor-x86_64/monitor
-name Monitor
--launcher.library /home/ak/Android/Sdk/tools/lib/monitor-x86_64//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807/eclipse_1502.so
-startup /home/ak/Android/Sdk/tools/lib/monitor-x86_64//plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.overrideVmargs
-exitdata 5c7f000d
-data @noDefault
-vm /usr/bin/java
-vmargs
-XX:MaxPermSize=256m
-Xms512m
-Xmx1024m
-jar /home/ak/Android/Sdk/tools/lib/monitor-x86_64//plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar

and when i tried launching it in emulator i got this error message :
Unrecognized VM option 'MaxPermSize=256m'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

PS : i've encountered the same problem with other programs , i got the same window of error ...Any help !

A: Maybe Android Device Monitor requires another version of java. I had the same problem in Ubuntu 16.04 LTS. In my OS there were java8 and java9. Java9 was current. Switching to java8 solved the problem. To select necessary version use command:
sudo update-alternatives --config java


text:
Q: .NET Maui with Amplify CLI and AppSync I'm looking for a way to make my app multi-platform, and I'm looking into Microsoft .NET Maui.
Is there a way to use AWS Amplify and AppSync with it?
AWS Amplify says it works with iOS, Android, and web. I see java and javascript supported, but no C#.
Is there a way to use .NET Maui with AWS Amplify?


text:
Q: Best way to combine spatial data I have a question regarding spatial data and u-sql. I have a input with polygons and input with points and i want to combine these so that I know in what polygon the point belongs to.
In T sql I would do a left outer join with something like polygon.STintersect(point)= 1
But I suppose that won't work in u sql. So how can I combine these two inputs?

A: You can use the SQL Server type assembly (Microsoft.SqlServer.Types.dll) which provides the implementation of geometry type and its methods.
See details on how to use this assembly within blog: https://blogs.msdn.microsoft.com/azuredatalake/2016/08/26/how-to-register-u-sql-assemblies-in-your-u-sql-catalog/#s4

A: To summarize the discussion on maya's answer: You currently need to do the join in a combiner or with a CROSS JOIN/WHERE.
You may also want to file a feature request for native Spatial support at http://aka.ms/adlfeedback.


text:
Q: Javascript - How to pull a WooCommerce variable in PHP? I'm trying to execute some PHP code that is using the WooCommerce variable to get the order ID.
add_action('add_meta_boxes', 'gen_order_meta_boxes');
function gen_order_meta_boxes()
{
    add_meta_box(
        'woocommerce-order-gen',
        __( 'TESTNG' ),
        'order_meta_box_gen',
        'shop_order',
        'side',
        'default'
    );
}

function order_meta_box_gen()
{
  echo '<button class="button save_order button-primary alert-mass">Generate</button>';
}

add_action('admin_footer', 'lolcats');
function lolcats()
{

    $order = new WC_Order($post_id);

    ?>
        <script type="text/javascript" >
            jQuery(document).ready(function($)
            {
                $(".alert-mass").click(function(e)
                {
                    e.preventDefault();
                    alert('<?php echo $order->get_order_number; ?>');
                });
            });
        </script>
    <?php
}

I can't seem to get it to return anything besides either null or 0.
Using something like this obviously works perfectly: window.location="dhlgen.php?order=1234"; because I'm trying to pass it through the URL to a PHP function which uses it later.
This also seems to fail, but it returns 'false':
function lolcats($post_id)
{
    $order = new WC_Order($post_id);

    ?>
        <script type="text/javascript" >
        jQuery(document).ready(function($)
        {
            $(".alert-mass").click(function(e)
            {
                e.preventDefault();
                var data = <?php echo json_encode($order->shipping_first_name); ?>;
                alert(data);
            });
        });
        </script>
    <?php
}

Thank you.

A: Okay, I solved it.
function lolcats()
{
    global $post;
    $order_id = $post->ID;

    ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($)
    {
        $(".alert-mass").click(function(e)
        {
            e.preventDefault();
            alert('<?php echo $order_id; ?>');
        });
    });
    </script>
    <?php
}


text:
Q: Datepicker validation and AdornedElement.IsKeyboardFocused I have a DatePicker on my form. When an invalid date is typed in by the user, the control gets a red border. However, I'd also like to display the error itself next to it.

<Style TargetType="{x:Type DatePicker}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <StackPanel Orientation="Horizontal">
                    <Border BorderThickness="1" BorderBrush="#FFdc000c" VerticalAlignment="Top">
                        <Grid>
                            <AdornedElementPlaceholder x:Name="adorner" Margin="-1"/>
                        </Grid>
                    </Border>
                    <Border x:Name="errorBorder" Background="#FFdc000c" Margin="8,0,0,0"
                            Opacity="0" CornerRadius="0"
                            IsHitTestVisible="False"
                            MinHeight="24" >
                        <TextBlock Text="{Binding ElementName=adorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                                   Foreground="White" Margin="8,2,8,3" TextWrapping="Wrap" VerticalAlignment="Center"/>
                    </Border>
                </StackPanel>
                <ControlTemplate.Triggers>
                    <DataTrigger Value="True">
                        <DataTrigger.Binding>
                            <Binding ElementName="adorner" Path="AdornedElement.IsKeyboardFocused" />
                        </DataTrigger.Binding>
                        <DataTrigger.EnterActions>
                            <BeginStoryboard x:Name="fadeInStoryboard">
                                <Storyboard>
                                    <DoubleAnimation Duration="00:00:00.15"
                                                     Storyboard.TargetName="errorBorder"
                                                     Storyboard.TargetProperty="Opacity"
                                                     To="1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </DataTrigger.EnterActions>
                        <DataTrigger.ExitActions>
                            <StopStoryboard BeginStoryboardName="fadeInStoryboard"/>
                            <BeginStoryboard x:Name="fadeOutStoryBoard">
                                <Storyboard>
                                    <DoubleAnimation Duration="00:00:00"
                                                     Storyboard.TargetName="errorBorder"
                                                     Storyboard.TargetProperty="Opacity"
                                                     To="0"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </DataTrigger.ExitActions>
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    </Style>

In my app.xaml, I have this included:
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/<assembly>.App;component/Styles/DatePicker.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

No validation text is shown next to the datepicker. What am I doing wrong?
Update:
It appers this issue has to do with using AdornedElement.IsKeyboardFocused in the animation. If I remove the animation and set the Opacity to 1, the validation is displayed, but that's obviously not what I'm trying to achieve here. This code works however with the other controls like textboxes, checkboxes,..
Is there any alternative way to get this to work?

A: DatePicker is a control where IsKeyboardFocused does not populate property (Try WPF Inspector to check for yourself). Possibly because could be its not a typical input control and the Keyboard focus could be either at the calendar button or the actual textbox.
The resolution is use to IsKeyboarFocusWithin.
<DataTrigger.Binding>
  <Binding ElementName="adorner" Path="AdornedElement.(DatePicker.IsKeyboardFocusWithin)" />
</DataTrigger.Binding>

A: Use a popup for you're template and you can use the placement property to position it around your control.
<Popup x:Name="Popup"
               Placement="Right"
               PlacementTarget="{Binding ElementName=adorner}">
    <Grid>
        <Border Background="{DynamicResource UI.ErrorBrush}" Padding="5 4">
                        <TextBlock Text="{Binding Path=AdornedElement.(Validation.Errors)[0].ErrorContent,
                                                  RelativeSource={RelativeSource Mode=FindAncestor,
                                                                                AncestorType={x:Type Adorner}},
                                                  FallbackValue=null, Mode=OneTime}"/>
        </Border>
    </Grid>
</Popup>

To add behaviour to your popup you need to apply data triggers to do what you want when you want it.
include this at the top
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

and within the popup create your triggers
<i:Interaction.Triggers>
<!--  Shows Popup when TextBox has focus  -->
<ei:DataTrigger Binding="{Binding ElementName=ErrorAdorner, Path=AdornedElement.IsFocused, FallbackValue=False}" Value="True">
    <ei:ChangePropertyAction PropertyName="IsOpen"
                                         TargetObject="{Binding ElementName=Popup,
                                                                FallbackValue=null}"
                                         Value="True" />
    <ei:DataTrigger Binding="{Binding ElementName=ErrorAdorner, Path=AdornedElement.IsFocused, FallbackValue=False}" Value="False">
        <ei:ChangePropertyAction PropertyName="IsOpen"
                                         TargetObject="{Binding ElementName=Popup,
                                                                FallbackValue=null}"
                                         Value="False" />
    </ei:DataTrigger>

you will also want triggers to hide the popup when the errors are null because if it has an animation (fade for instance) the text in the popup will display null as it fades away. this can just be a single trigger on the error count equalling 0 and setting animation to none/hiding.


text:
Q: The $3×3$ representation of weak $SU(2)$ I'm reading chapter 11.2 of the Cheng and Li textbook 'Gauge theory of elementary particle physics'. It  says that $T_+$, $T_-$ and $Q$ do not form a closed algebra. In order to fix this problem the theory is extended to contain extra fermions.
As Georgi and Glashow did, a heavy lepton $E$ is added to form a triplet together with a electron neutrino and electron. My question is about the commutator relation of $T_+$ with $T_-$. Can someone explain how they get to this commutator relation? In the book they say this relation is straighforward but I  can't see how they get it. See the pictures for clarity.

A: If you are reading this text and have advanced to that section, especially past its (11.20,21,22), you must be proficient in the standard QFT current algebra application of the Jordan map for fermions, and whence appreciate how
$$
J_{ +}=\sqrt{2} \begin{pmatrix} 0&1&0\\ 0& 0& 1\\ 0&0&0&\end{pmatrix} ,\qquad J_+^\dagger =J_-, \quad J_3=\operatorname{diag} (1,0,1),\\
[J_+,J_-]=2J_3.
$$
Your Jordan map fermion sandwich (11.23) then follows directly for each of your $P_L$ and $P_R$ fermion isotriplet of (ii); note using the fermion anticommutation law between (11.20) & (11.21)  keeps the triplets apart, as cross terms die off by the orthogonal projection operators $P_L \& P_R$.
You then have inside the obvious respective integrals,
$$
[T_+, T_+^\dagger]\mapsto  2\left ( (E,N\sin\alpha+\nu \cos\alpha  ,e))^\dagger J_3 P_L(E,N\sin\alpha+\nu \cos\alpha  ,e)^T + (E,N,e)^\dagger J_3 P_R(E,N,e)^T
\right) = 2 (E^\dagger (P_L+P_R)E - e^\dagger (P_L+P_R)e)=
2 (E^\dagger E - e^\dagger  e) \mapsto 2Q.
$$
Note how the difference in the middle entry of the two isotriplets drops out by being multiplied by the vanishing eigenvalue of $J_3$!
Neat, huh?


text:
Q: Is the following assert syntax correct? I have the following assert statement;
assertTrue(xyz.getTotalRecords() == 50);

I am getting an error
java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:92)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.junit.Assert.assertTrue(Assert.java:54)

Am I doing something wrong OR is it an issue with what is actually being asserted ?

A: You get an assertion error because xyz.getTotalRecords() is not 50 but your assertion is otherwise correct, although you might want to use assertEquals instead

A: Good style is using assertEquals(xyz.getTotalRecords(), 50).

A: Since it compiled, the syntax is correct. You get this exception because the condition is not true.

A:
Am I doing something wrong OR is it an issue with what is actually
  being asserted ?

The syntax is fine. The problem is with assertion. Your expected value is not same as actual one.
Try providing a message for when assertion fails: JUnit
assertTrue("Expected size: 50, Actual size: " + xyz.getTotalRecords(), xyz.getTotalRecords() == 50);

or assertEquals("Expected size: 50, Actual size: " + xyz.getTotalRecords(), xyz.getTotalRecords(), 50);

A: You are doing all right. You just get failed assertion. BTW, good practice is to use Hamcrest that way:
import static org.hamcrest.CoreMatchers.*;
...
assertThat(xyz.getTotalRecords(), is(50));


text:
Q: Random fields in physics - how do they work? I'm trying to get an intuitive understanding of what random fields are. Wikipedia's article gives a formal definition (which is in very mathematical language), but also says various much more intuitive ways to picture the random field, such as:

[A random field] is a function ${\displaystyle f(x)}$ that takes on a random value at each point ${\displaystyle x\in \mathbb {R} ^{n}}$ (or some other domain).

However, if each point indeed takes on a random value, then there's no guarantee the random field is continuous. If $f(x) = k$ where $x$ is a position vector, there's no guarantee that $f(x+\epsilon) \neq \exp(k^3)+100000-\mathrm{Sin}(3\pi)$. But if $f(x)$ can fluctuate so wildly with position, then it surely
wouldn't relate to the universe at all - physical quantities don't vary by much over very small displacements.
Wikipedia touches on this:

When used in the natural sciences, values in a random field are often spatially correlated. For example, adjacent values (i.e. values with adjacent indices) do not differ as much as values that are further apart. This is an example of a covariance structure, many different types of which may be modeled in a random field.

However I do not understand this: if there is some kind of structure in the field, then it is (by definition) not random.
It seems to me there must be more to a random field than just random numbers at every point, in particular some guarantee that the field is at least continuous, even if it's not differentiable (although that seems like a reasonable assumption to make for physical fields too). Am I understanding this right? If so, where is the continuity condition imposed in the definition? If not, why do we not need continuity?


text:
Q: Android ListView not detecting selection I'm stumped. This one IS simple and I'm missing something simple but I'm just not getting anywhere.
I have a ListView that contains pretty simple items - TextView's that contain text of the form "N. name", where N is the position in the list and name is the name of the associated objects. I've created a ListAdapter that presents that information into the ListView.
The presentation stuff seems to work fine. It's the part where when I tap on a row that's not working. I just don't get a notification. If I set a onClickListener on the item (when it's generated in the Adapter) I do get a notification, but it's convoluted to make that work the way I'd like it to. I've tried a bunch of stuff - changing descendent focusability, enabling, disabling, setting itemsCanFocus to false, ... - but no luck on any of them.
I've included relevant code for configuring the view and the elements in the ListView.
In particular, what I'm trying to do is get that OnItemClickLister.onItemClick() to get invoked when I tap on a row. Any thoughts on what I'm doing wrong?
Activity:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    model = FZMModel.getInstance(this);
    setContentView(R.layout.activity_deploy);

    TextView viewTitle = (TextView) findViewById(R.id.deploy_header);

    if (model.getProfiles().size() == 0) {
        viewTitle.setText(R.string.deploy_header_create);
    } else {
        viewTitle.setText(R.string.deploy_header_choose);
    }

    profileListView = (ListView) findViewById(R.id.profileListView);
    profileListAdapter = new ProfileListAdapter(this, model);
    profileListView.setAdapter(profileListAdapter);

    profileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Log.d(TAG, String.format("Item %d selected (with id=0x%x)", position, id));
        }
    });
}

Adapter:
... relevant code from getView():
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Profile profile = model.getProfileAtIndex(position);
    final int rowNum = position;

    if (convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.profile_list_layout, parent, false);
    }

    TextView profileIndexView;
    TextView profileNameView;

    profileIndexView = (TextView) convertView.findViewById(R.id.profileIndexLabel);
    profileNameView = (TextView) convertView.findViewById(R.id.profileNameLabel);

    profileIndexView.setText(String.format("%d.", position));
    profileNameView.setText(profile.getName());

//     convertView.setOnClickListener(new View.OnClickListener() {
//         @Override
//         public void onClick(View view) {
//             Toast.makeText(context, String.format("Did select row #%d (index=%d)",rowNum, profile.getPosition()), Toast.LENGTH_SHORT).show();
//         }
//     });
    return convertView;
}

activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nsn.flexizonemobile.FZMConcreteActionDeploy"
    tools:ignore="MergeRootFrame" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/deploy_header_choose"
        android:id="@+id/deploy_header"
        android:layout_margin="10dp"
        android:layout_centerHorizontal="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/profileListView"
        android:layout_gravity="left|top"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="0dp"
        android:choiceMode="none"
        android:layout_below="@+id/deploy_header"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="2dp"
        android:clickable="true"
        android:descendantFocusability="beforeDescendants" />

</RelativeLayout>

profile_list_layout layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="@dimen/profile_index_width"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="A.         "
        android:id="@+id/profileIndexLabel"
        android:gravity="center_vertical|right"
        android:layout_centerVertical="true"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:textSize="24sp"
        android:textIsSelectable="true"
        android:layout_alignParentStart="false"
        android:layout_alignParentTop="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Profile Name"
        android:id="@+id/profileNameLabel"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="false"
        android:gravity="center_vertical"
        android:layout_toRightOf="@+id/profileIndexLabel"
        android:layout_marginLeft="10dp"
        android:layout_centerVertical="true"
        android:textSize="24sp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" />
</RelativeLayout>

A: remove following attributes from your ListView:
android:choiceMode="none"
android:clickable="true"
android:descendantFocusability="beforeDescendants"

also
android:layout_width="wrap_content"
android:layout_height="wrap_content"

makes no sense in this context (especially height)

A: in the textview of your inflator layout just add:
android:focusable="false"
android:focusableInTouchMode="false"

and in parent layout of your inflator i.e in relative layout of inflator add:
android:descendantFocusability="blocksDescendants"

remove :
android:descendantFocusability="beforeDescendants"

from your listview. and set height of your listview to match_parent will solve your issue.


text:
Q: how to set monitor timeout to "never" using powershell I want to write a script that will change the power settings for "turn off the display" and "put the computer to sleep" to "never" (see attached screenshot).
I know how to set times for the above using:
powercfg -change -monitor-timeout-ac [time]
powercfg -change -monitor-timeout-dc [time]
powercfg -change -standby-timeout-ac [time]
powercfg -change -standby-timeout-dc [time]

but I can't find how to set it to "never".
what is the syntax I need to use?
thank you!

A: Try this:
powercfg -change -monitor-timeout-ac 0
Per this, my favorite reference for missing help switch/parameter information:
http://ss64.com/nt/powercfg.html

Setting any value to 0 will set the timeout=Never

Thanks to Cristian, official documentation with additional parameters is currently available here


text:
Q: How comment can execute? In my code i wrote this code for popup
but the commented line
// mywindow.document.write('<title>my div</title>');
automatically executed.Why?
and if i deleted this line my page don't show any error.
if it is present as comment it shows an error that duplicate title tag.
 function Popup(data) {
            var mywindow = window.open('', 'mydiv', 'height=400,width=600');
           // mywindow.document.write('<title>my div</title>');
            /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            mywindow.document.write('');
            mywindow.document.write(data);
            mywindow.document.write('');
            mywindow.document.close();
            mywindow.print();
            return true;
        }

A: If you executed it on the server and then commented it, the server might have cached your old js file... try to pass a parameter (any) to the js file in the  tag:


text:
Q: Delphi 2009 OnKeyDown does not trap as Delphi 2007 does I have this code
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
begin
  if not (Key in [Ord('0')..Ord('9')]) then
    Key := 0;
end;

and it worked fine with Delphi 2007. When I upgraded to Delphi 2009 and I try to press any letter it is accepted and the Key := 0 does not trap the input?
Anyone encountered the same behavior?

A: OnKeyDown gives you a scancode.  OnKeyPress gives you the character.  Been that way in every version of Delphi I can remember.

A: Are you sure that this worked in Delphi 2007? I just tried the code in Delphi 2007 and 2009. And both behave the same (No key stroke is eaten) If you want to accept only digits you should use the OnKeyPress event and set the Key parameter to #0.

A: to send Key:=0; on KeyDown Event use:
Key:=HiWord(GetKeyState(0));

//do something


text:
Q: How to create a kml map overlay? I am trying to understand a KML Ground Overlay Tutorial, which has the following code as an example:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Folder>
    <name>Ground Overlays</name>
    <description>Examples of ground overlays</description>
    <GroundOverlay>
      <name>Large-scale overlay on terrain</name>
      <description>Overlay shows Mount Etna erupting
          on July 13th, 2001.</description>
      <Icon>
        <href>https://developers.google.com/kml/documentation/images/etna.jpg</href>
      </Icon>
      <LatLonBox>
        <north>37.91904192681665</north>
        <south>37.46543388598137</south>
        <east>15.35832653742206</east>
        <west>14.60128369746704</west>
        <rotation>-0.1556640799496235</rotation>
      </LatLonBox>
    </GroundOverlay>
  </Folder>
</kml>

There is no API key number, so I assume this KML is intended to be combined with a map of some sort.
I saved the kml to a publicly accessable file:
https://drive.google.com/file/d/0Bx17tEcqrzavTlc4ZHVmNFgyM1k/view?usp=sharing
Surely I must make an embedded map with some reference to this kml file.
https://developers.google.com/maps/documentation/embed/guide
The first example here uses iframe, it uses Place Mode, which I don't want.
<iframe
  width="600"
  height="450"
  frameborder="0" style="border:0"
  src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY
    &q=Space+Needle,Seattle+WA" allowfullscreen>
</iframe>

View mode seems most appropriate of the above link options.
https://www.google.com/maps/embed/v1/view
  ?key=YOUR_API_KEY
  &center=-33.8569,151.2152
  &zoom=18
  &maptype=satellite

Oviously this needs to be recentered to Mt Etna,and my API key:
ttps://www.google.com/maps/embed/v1/view
  ?key=AIzaSyCrzeJMzJcHGCZj26Y9tHhmkSQ1zzJi8o0
  &center=37.91904192681665,15.35832653742206
  &zoom=14
  &maptype=satellite

Does it need to be put in iframe?
How can I combine these two chunks of code to create a kml map overlay embedded in my website?
Is there a way of doing this without using Java?

A: A KML file will not render directly on the web... it needs to be rendered on some map.  The easiest way to view a KML file yourself is to open it with Google Earth. If you want to put it on the web, one easy way is to use the Google Maps JavaScript API to embed a map on your site, and then use the KmlLayer function to add the KML file to the map.  Details and sample code are in the documentation here:
https://developers.google.com/maps/documentation/javascript/kml
Note that the copy of the KML file which you have on Google Drive will not open directly in Earth or anywhere else with the URL you provided, since it takes you to the Google Drive page for that file. Instead, you want to generate the direct download URL for that file on Drive, or put it online somewhere else.


text:
Q: Variable as Tar file name in SunOs 5.10 I am trying to get the following result in the
1.files archived as tar with current date as a part of the tar name.
2.files removed once archived.

/usr/sap/ST1/POC/backtest/*.txt has 2 txt files.

(find /usr/sap/ST1/POC/backtest/*.txt )| xargs -I % sh -c 'tar cvf arc_2017-02-28.tar % ; rm -f %'

This works fine as the file name is mentioned as arc_2017-02-28.tar.
But when I tried this:
arc_name="arc_"`date +%F`".tar"
(find /usr/sap/ST1/POC/backtest/*.txt )| xargs -I % sh -c 'tar cvf "$arc_name" % ; rm -f %'

The output is an error:

tar: : No such file or directory

Please help me proceed with this.

A: this would work normally :
(find /usr/sap/ST1/POC/backtest/*.txt) | xargs -I {} sh -c 'arc_name="arc_"`date +%F`".tar"; tar cvf "$arc_name" {} ; rm -f {}'

so the issue with your command was that sh -c seems that can't read your variable , if we can call that is variable scope so to speak ,
so moving the variable arc_name="arc_"date +%F".tar" into the sh makes sense .
but you will have to change the % in xargs because this will produce an issue with your % symbol in date +%F function


text:
Q: Class type property breaks wired event I have struggled with this for almost a day now, and have boiled it down to the following:
I have a UserControl called MyUserControl:
public partial class MyUserControl : UserControl
{
…

This UserControl has one property called Property1:
public MySubClass Property1 {get; set;}

As you see the property is of type MySubClass which is a class defined as seen here:
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MySubClass : INotifyPropertyChanged
{
    //Declare event fired when a property has changed
    public event PropertyChangedEventHandler PropertyChanged;

    private double _subClassProperty1;

    public double SubClassProperty1
    {
        get
        {
            return _subClassProperty1;
        }
        set
        {
            _subClassProperty1 = value;
            OnPropertyChanged(); //Call method to raise event
        }
    }

    //Raises the PropertyChanged event
    protected void OnPropertyChanged()
    {
        PropertyChangedEventHandler handler = PropertyChanged; //Copy event handler to temporary variable to make it thread safe
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(""));
        }
    }
}

Note that this class contains an event that is fired when a property has been changed inside the class (in this case only one property exists: SubClassProperty1).
In the constructor of the UserControl I subscribe to the event from the sub class to get notified when a property has been changed. The constructor looks like this:
public MyUserControl()
{
    InitializeComponent();

    Property1 = new MySubClass();

    //Wire event fired when a property has been changed in sub class
    Property1.PropertyChanged += MySubClass_PropertyChanged;
}

The method (located in the user control class) called when the event is fired looks like this:
//Fired when a property has been changed in the sub class
private void MySubClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    MessageBox.Show("Property changed");
}

The problem is the following:
When dragging the user control to a form and changing the property of the subclass (SubClassProperty1) the event is fired and the MessageBox shown (the change of the property value is done at design-time in the properties window of Visual Studio).
If I now rebuild the project (Build-> Rebuild Solution) the event binding that I do in the constructor is lost, so when changing the value of SubClassProperty1 (again at design-time) the event is no more fired.
If I make the setter of Property1 private like this:
public MySubClass Property1 {get; private set;}

the event binding is not lost when rebuilding the project, but now the value of SubClassProperty1 is not persisted (gets reset to the default value when rebuilding the project).
Question:
I am clearly missing something about how to correct implement a class type property, but what am I doing wrong?
To sum up: I want to be able to set the properties of the sub class through the user control class' property from the properties window of Visual Studio, without loosing the event binding.


text:
Q: How to compute the derivative of a curve? Sorry for the naivety of the question, my field is not mathematics. I am writing a script to calculate the derivative of a curve given by a set of (x,y) points as
(x,y)
1,3
2,2
3,7
4,7
5,8
6,12

I calculate the dy/dx for each point from the slope over a unit of x as y(n+1)-y(n) to produce
(x,dy/dx)
2,-1
3,5
4,0
5,1
6,4

Is it mathematically correct? Do I calculate dy/dx correctly?
The given curve is not a mathematical function but an empirical set of data (say x=time, y=temperature). Is it the correct way to calculate the dy/dx for the available set of data?
EDIT: Probably, it is meaningless to calculate the slope between two given points. Instead, it is better to draw a curve based on the best fit. Then, we will have a better approximation of the data points where the slope at each point is meaningful.
Am I right? Should I recalculate the y values based on a best-fit approximation before trying to calculate the slope?

A: I will assume that the underlying function $y$ is several times differentiable for all $x$ in an interval which covers your range of values. This is a reasonable assumption, as temperatures rarely vary abruptly and certainly not on a microscopic scale.
If this assumption is satisfied, then you can certainly approximate the derivative of $y$ at each of your points using finite difference approximations. It simplify matters that the data points are equidistant on the $x$ axis. Let $h$ denote their constant separation. In your case $h=1$.
If $x$ is an internal point, i.e., both $x-h$ and $x+h$ are data points, then the standard space central approximation of $y'(x)$ is
$$ y'(x) \approx \frac{y(x+h) - y(x-h)}{2h} $$
The absolute value of the error is $O(h^2)$, i.e. it is bounded by a constant times $h^2$.
If $x$ is an endpoint, say the left end point, then you can either use
$$ y'(x) \approx \frac{y(x+h)-y(x)}{h},$$
where the error is $O(h)$ or a one side approximation, such as
$$ y'(x) \approx \frac{-3 y(x) + 4y(x+h) - y(x+2h)}{2h},$$
where the error is $O(h^2)$.
More elaborate approximations are possible and precise error estimates can also be derived, but we either need more information about the properties of $y$ or more data points so that information can be inferred from the data.

A: The way to do this is to fit a cubic spline through the data, and then calculate the derivative.
See scipy.interpolate.CubicSpline
Then use the .Derivative() method to get what you want.


text:
Q: Get all fields in one collection and specific field in other collection with $lookup aggregation I have collection timestamps with 10 fields.
and collection ie_settings with 5 fields.
I used $lookup to join them but it will return all fields.
And I also try to put $project to return specific field.
What I want is display all fields from timestamps
and specific field from ie_settings
Here's my what I tried:
Timestamp.aggregate([
                { $match: {
                        $or: [
                            { current_status: '60min break now' },
                            { current_status: 'Time out' }
                        ],
                        createdAt: { $gte: date_from, $lt: date_to } }
                },
                { $lookup: {
                        from: "individual_employment_settings",
                        localField: "staff_id",
                        foreignField: "staff_id",
                        as: "ie_settings" }
                },
                {
                    $project: {
                        "ie_settings.branch_office": 1
                    }
                }
            ])

But it will output branch_office only. I don't want to list all timestamp fields in the $project.
Thanks.

A: Timestamp.aggregate([
                { $match: {
                        $or: [
                            { current_status: '60min break now' },
                            { current_status: 'Time out' }
                        ],
                        createdAt: { $gte: date_from, $lt: date_to } }
                },
                { $lookup: {
                        from: "individual_employment_settings",
                        localField: "staff_id",
                        foreignField: "staff_id",
                        as: "ie_settings" }
                },
                {
                    $project: {
                         document: "$$ROOT",
                        "ie_settings.branch_office": 1
                    }
                }
            ])


text:
Q: rewrite rule on htaccess not working Hi for some reason the htaccess file is not working properly
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(www.)?mallyear.com$
RewriteCond %{REQUEST_URI} !^/prod/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /prod/$1
RewriteCond %{HTTP_HOST} ^(www.)?mallyear.com$
RewriteRule ^(/)?$ prod/ [L]

so all the files are in this directory prod/ but when i enter this url
https://www.mallyear.com/landing
it shows "The requested URL /prod/landing was not found on this server."
why is this happening? Please help


text:
Q: how to bring ul element to the center of the div? CSS I have a div in which i need the inner list in the center of that div.
I can put that in the middle by specifying the width and doing margin 0 auto, but
i need to make it dynamic such that even if i remove 1 element from the list, it would appear in the center of the div. Or if i add another element it would maintain the center align property. How do i do that?
Fiddle:
https://jsfiddle.net/ucxdfmpc/1/

              4
              CREATIVES

              6
              CODERS

              4
              DESIGNERS

              2
              WORKERS

     * {
  padding: 0px;
  margin: 0px;
}
.counter-wrapper {
  background: #fe6261;
  padding-top: 37px;
  padding-bottom: 36px;
  border-top: 1px solid #fe4e4d;
  border-bottom: 1px solid #fe4e4d;
}

.counter-inner ul{
  list-style: none;
 }
.counter-inner ul li {
  float: left;
  width: 14.84375%; /*190px;*/
}

.counter-image {
  display: block;
  width: 66px;
  height: 70px;
  border-right: 2px solid #fc6867;
  float: left;
}

.counter-image.first {
  background: url('../images/counter-1.png') 10px 15px no-repeat;
}

.counter-image.second {
  background: url('../images/counter-2.png') 10px 15px no-repeat;
}

.counter-image.third {
  background: url('../images/counter-3.png') 10px 15px no-repeat;
}

.counter-image.fourth {
  background: url('../images/counter-4.png') 10px 15px no-repeat;
}

.counter-number {
  font-family: 'Roboto', sans-serif;
  font-size: 30px;
  color: #fd7e7e;
  float: left;
  padding: 12px 18px 0px;
}

.counter-text {
  float: left;
  font-size: 10px;
  color: #fd7e7e;
  padding: 4px 18px 0;
}

A: The thing is, you're using floats, which will not clear themselves, and therefore the ul element will not get the correct dimensions dynamically based on the content. So it's a bit hard centering it.
Make those list elements display: inline-block and add text-align: center to the wrapper, is this what you are after? Then you would need to fix the background color, of course, but that should be easy. But the things will be centered in any case.
https://jsfiddle.net/fnsyshzw/1/

* {
  padding: 0px;
  margin: 0px;
}
.counter-wrapper {
  background: #fe6261;
  padding-top: 37px;
  padding-bottom: 36px;
  border-top: 1px solid #fe4e4d;
  border-bottom: 1px solid #fe4e4d;
  text-align: center;
}

.counter-inner ul{
  list-style: none;
 }
.counter-inner ul li {
  display: inline-block;
  width: 14.84375%; /*190px;*/
}

.counter-image {
  display: block;
  width: 66px;
  height: 70px;
  border-right: 2px solid #fc6867;
  float: left;
}

.counter-image.first {
  background: url('../images/counter-1.png') 10px 15px no-repeat;
}

.counter-image.second {
  background: url('../images/counter-2.png') 10px 15px no-repeat;
}

.counter-image.third {
  background: url('../images/counter-3.png') 10px 15px no-repeat;
}

.counter-image.fourth {
  background: url('../images/counter-4.png') 10px 15px no-repeat;
}

.counter-number {
  font-family: 'Roboto', sans-serif;
  font-size: 30px;
  color: #fd7e7e;
  float: left;
  padding: 12px 18px 0px;
}

.counter-text {
  float: left;
  font-size: 10px;
  color: #fd7e7e;
  padding: 4px 18px 0;
}

                  4
                  CREATIVES

                  6
                  CODERS

                  4
                  DESIGNERS

                  2
                  WORKERS


text:
Q: Mouse events on vertex of JUNG graph I have constructed graphs with JUNG but I'm not sure how to add mouse action listeners to the vertices of the graph.
Below is a sample section of my code that I think is the most relevant for the problem.
layout = new FRLayout2<GraphNode, GraphEdge>(graph);
visualizationViewer = new VisualizationViewer<GraphNode, GraphEdge>(layout, new Dimension(1000, 700));

visualizationViewer.getModel().getRelaxer().setSleepTime(500);
visualizationViewer.setGraphMouse(new DefaultModalGraphMouse<GraphNode, String>());
        visualizationViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);
visualizationViewer.setForeground(Color.black);

In particular, I want to detect single and double clicks on the vertices of a graph and act on them.
Note: I have seen a couple of old SO links, but none of the answers seem to be helping me. If someone can just give me the pseudocode or point me to the right direction, it would be really helpful.

A: I think a full example will serve you and others better than just modifying your code. The relevant part here is, assuming you already have a VisualizationViewer, to use this snippet:
visualizationViewer.addGraphMouseListener(new GraphMouseListener() {...});

Besides handling click events, this also allows you to add press and release events.
This standalone class creates a simple graph and -- when a vertex is clicked on -- prints on stdout what vertex was clicked.
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.GraphMouseListener;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

public class METest {

    public static void main(String[] args) {
        //Create a test graph
        Graph graph = new SparseGraph<String, String>();
        graph.addVertex("a");
        graph.addVertex("b");
        graph.addVertex("c");
        graph.addVertex("d");
        graph.addEdge("a->b", "a", "b");
        graph.addEdge("a->c", "a", "c");
        graph.addEdge("b->c", "b", "c");
        graph.addEdge("c->d", "c", "d");
        //Metrics
        visualize(graph);
    }

    public static void visualize(Graph graph) {
        //Layout graph.
        Layout layout = new CircleLayout(graph);
        layout.setSize(new Dimension(500, 500)); // sets the initial size of the space
        VisualizationViewer server = new VisualizationViewer(layout);
        server.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
        //Here you add the listener
        server.addGraphMouseListener(new GraphMouseListener() {

            @Override
            public void graphClicked(Object v, MouseEvent me) {
                if (me.getButton() == MouseEvent.BUTTON1 && me.getClickCount() == 2) {
                    System.out.println("Double clicked "+ v);
                }
                me.consume();
            }

            @Override
            public void graphPressed(Object v, MouseEvent me) {
            }

            @Override
            public void graphReleased(Object v, MouseEvent me) {
            }
        });
        //Show the frame
        JFrame frame = new JFrame("Simple Graph View");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(server);
        frame.pack();
        frame.setVisible(true);
    }
}


text:
Q: ASP.NET Core Default debugging launch URL When using the ASP.NET Core Web API template, the default debugging start up URL is somehow set to api/values. Where is this default configured and how do I change it?

A: There was very little documentation that I could find regarding where this start up URL was declared. There is a brief mention of it in this blog post on MSDN. I eventually stumbled upon it in the launchSettings.json file under the Properties node of the project as shown below:

Here are the contents of this file:
{
  "profiles": {
    "IIS Express": {
      "commandName" : "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables" : {
        "ASPNET_ENV": "Development"
      }
    }
  }
}

You can change the launchURL to your desired default route.


text:
Q: Accesing shadow root inside a function I have created simple web components using vanilla javascript as per the
The problem is on my hideNonVisibleDivs() i want to access shadowRoot
Here are my functions.
var visibleDivId = null;
var i, divId, div;

console.log('shadowroot', this); // display the global shadow root element

function divVisibility(divId) {
     hideNonVisibleDivs.bind(this)(divId); //binding this context
}

function hideNonVisibleDivs(divId) {
    //I want to access a shadow root here using this
    console.log('shadowroot', this); //undefined
}

var panels = this.shadowRoot.querySelectorAll("#tab-info> .share-tab")
panels.forEach(function(el) {
        divVisibility.bind(this)(this.getAttribute('custom-id')); //bind this context

    });
});

What is Expected?
Inside hideNonVisibleDivs(divId) I want to access the shadowRoot as that of out side function (the global shadowroot ) meaning this.

A: The simplest solution I can offer is to stop using this.
The meaning of this changes with every function call, which is why you are having trouble understanding what it refers to at any point in your code.
For example, your divVisibility() function cannot work.
console.log( 'shadowroot', this ); //{this} is a shadowroot

//...

function divVisibility(divId) {

     //shadow root {this} cannot be accessed at all from here

     hideNonVisibleDivs.bind(this)(divId); //binding this context
                           //^Refers to divVisibility

}

Try rewriting your code without using this anywhere. Instead, use a variable name, such as 'shadowroot'. (Without knowing your code, I do not know how useful this advice is, unfortunately.)


text:
Q: VNC connection brokering (RFB protocol server) Please consider the following scenario:

*

*VNC Client try to connect with a VNC Server which is behind a NAT.

*I have written a port forwarder in java which help me achieving above task, and it works fine.

*Now I need to, somehow, add a connection brokering functionality within this forwarder so that I can also intercept the communication between VNC Client – Server, and  authenticate the VNC Client within the forwarding utility as well.
You may have guessed that actually I am using the password received from VNC Client for some authentication in my app. As the RFB Server can be implemented at application layer, I guess this interception is possible... VNCAuthentication (DES encryption/decryption) is used in all above communication. Upon successful authentication within the forwarding utility I shall just let the forwarding continue for that respective client, else I can close it (stop forwarding).
I have tried some implementation, also tried customizing a java implementation of rfb server... but still not able to get there. It will take some time, I know, but need to confirm if I am thinking straight.
Please let me know if the implementation of above scenario is ambiguous, not possible, or illegitimate and if this is possible, let me have some guild lines...

A: This seems like a good implementation. Think of it like a VNC proxy, just like an HTTP(S) proxy. There are also HTTP authenticating proxies. You're implementing part of the VNC protocol to create an authenticating VNC proxy.
Maybe you can get some inspiration from VNCProxy, an existing Java VNC proxy.


text:
Q: Drag and drop png image should override with a background image and be able to resize and rotate (photo editor app) in flutter I have a list of png sticker images which i want to drag and drop over the background image  and be able to resize after placing it on top of the background image and be able to drag it to a new position after resize , any thoughts on this implementation with flutter would be appreciated.

A: You can copy paste run full code below
You can use package https://pub.dev/packages/flutter_simple_sticker_view
To run demo code, you can copy asset from https://github.com/myriky/flutter_simple_sticker_view/tree/master/example/assets
code snippet
FlutterSimpleStickerView _stickerView = FlutterSimpleStickerView(
    Container(
      decoration: BoxDecoration(
          color: Colors.red,
          image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage(
                  "https://images.unsplash.com/photo-1544032527-042957c6f7ce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"))),
    ),
    [
      Image.asset("assets/icons8-superman-50.png"),

working demo
https://user-images.githubusercontent.com/581861/69323565-52a84100-0c8a-11ea-974e-f2887d8755b2.gif
full example code with latest version permission_handler
import 'dart:typed_data';

import 'package:flutter/material.dart';

import 'package:flutter_simple_sticker_view/flutter_simple_sticker_view.dart';

import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title: "Flutter Simple Sticker View", home: HomeView());
  }
}

class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  FlutterSimpleStickerView _stickerView = FlutterSimpleStickerView(
    Container(
      decoration: BoxDecoration(
          color: Colors.red,
          image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage(
                  "https://images.unsplash.com/photo-1544032527-042957c6f7ce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"))),
    ),
    [
      Image.asset("assets/icons8-superman-50.png"),
      Image.asset("assets/icons8-captain-america-50.png"),
      Image.asset("assets/icons8-avengers-50.png"),
      Image.asset("assets/icons8-iron-man-50.png"),
      Image.asset("assets/icons8-batman-50.png"),
      Image.asset("assets/icons8-thor-50.png"),
      Image.asset("assets/icons8-venom-head-50.png"),
      Image.asset("assets/icons8-homer-simpson-50.png"),
      Image.asset("assets/icons8-spider-man-head-50.png"),
      Image.asset("assets/icons8-harry-potter-50.png"),
      Image.asset("assets/icons8-genie-lamp-50.png"),
      Image.asset("assets/icons8-cyborg-50.png"),
      Image.asset("assets/icons8-one-ring-50.png"),
    ],
    // panelHeight: 150,
    // panelBackgroundColor: Colors.blue,
    // panelStickerBackgroundColor: Colors.pink,
    // panelStickercrossAxisCount: 4,
    // panelStickerAspectRatio: 1.0,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Flutter Simple Sticker View"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.save_alt),
              onPressed: () async {
                Uint8List image = await _stickerView.exportImage();

                Map<Permission, PermissionStatus> statuses = await [
                  Permission.storage,
                ].request();
                await ImageGallerySaver.saveImage(image);
              },
            )
          ],
        ),
        body: _stickerView);
  }
}


text:
Q: Doubt while proving that an irreducible matrix lie algebra representation implies an irreducible matrix lie group representation Let $G$ be a connected matrix Lie group with Lie algebra $g$. Let $\Pi$ be a representation of $G$ acting on $V$ a finite dimensional vector space, and $\pi$ the associated representation of $g$. There is a theorem that says that in this case, $\Pi$ is irreducible iff $\pi$ is irreducible.
I am trying to understand the proof. I have understood the part where we show that an irreducible $\Pi$ implies an irreducible $\pi$. Nonetheless there is something I don't see in the proof of the converse.
The proof goes like this. Assume that $\pi$ is irreducible. Let $W$ be an invariant subspace of $V$. Then $W$ is invariant under $\Pi(e^{tX})$ where $t$ is a real number, and $X$ is an element of the Lie algebra $g$. The next claim is that this implies that $W$ is also invariant under
$$\pi(X)=\frac{d}{dt}\Pi(e^{tX})\bigg|_{t=0}.$$
I don't see why. So, why does the fact that $W$ is invariant under $\Pi(e^{tX})$ make it also invariant under $\pi(X)=\frac{d}{dt}\Pi(e^{tX})\bigg|_{t=0}$?


text:
Q: Ideal place to read and write metadata using NSPersistentDocument? In my NSPersistentDocument subclass, I need to save some metadata to my document when I save it and, of course, read it back when I open the document. I did get it working, but I'm not sure if it's the proper way to handle it.  (My testing reflects a new, unsaved document being saved and then opened again. New, unsaved documents do not have an NSPersistentStore assigned until after the first save.)
Here's my working code with comments related to my testing and thought process of how to handle this:
- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{

    // No persistent store available yet

    BOOL result = [super readFromURL:absoluteURL ofType:typeName error:outError];

    // Persistent store available, but metadata may be already altered by configurePersistentStoreCoordinatorForURL:
    // if I were set the data there instead of in writeToURL:

    if (result == YES)
    {
        // Read metadata
        NSPersistentStore *persistentStore = [self.managedObjectContext.persistentStoreCoordinator persistentStoreForURL:absoluteURL];
        NSString * uuid = [persistentStore metadata][DefaultLocationUUIDKey];
        self.defaultLocationUUID = uuid;
    }

    return result;
}

- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)error
{

    // No persistent store available yet

    BOOL result = [super writeToURL:absoluteURL ofType:typeName forSaveOperation:saveOperation originalContentsURL:absoluteOriginalContentsURL error:error];

    // Persistent store available, but has already been saved by this point

    // Get mutable copy of existing metadata and update with new data
    NSPersistentStore *persistentStore = [self.managedObjectContext.persistentStoreCoordinator persistentStoreForURL:absoluteURL];
    NSMutableDictionary *metadata = [persistentStore.metadata mutableCopy];
    metadata[DefaultLocationUUIDKey] = self.defaultLocationUUID;

    // Use this method because it saves the metadata directly to the file without having to re-save the document, is this correct? It works.
    // Are their negative side effects to altering the metadata in this way while the file is open? I haven't tested all possibilities.
    NSError *metadataError = nil;
    [NSPersistentStoreCoordinator setMetadata:metadata forPersistentStoreOfType:typeName URL:absoluteURL error:&metadataError];

    return result;

}

// Called for both open and save, but not for new documents (which is fine, use initWithType:error:)
- (BOOL)configurePersistentStoreCoordinatorForURL:(NSURL *)url ofType:(NSString *)fileType modelConfiguration:(NSString *)configuration storeOptions:(NSDictionary *)storeOptions error:(NSError **)error
{

    // No persistent store available yet

    BOOL result = [super configurePersistentStoreCoordinatorForURL:url ofType:fileType modelConfiguration:configuration storeOptions:storeOptions error:error];

    // Persistent store available, but how to determine if opening existing or saving a new document?
    // Don't want to alter existing record unless saving a new document.

    return result;
}

The documentation seems a little sparse on how best to handle a lot of things when using NSPersistentDocument so any suggestions are welcome.
Thanks.


text:
Q: Extension got rejected 3 times and I don't understand why My CRX got rejected yesterday because I did not comply with following section of our policy: https://developer.chrome.com/webstore/program_policies#chrome_apps

*

*Require a local executable, other than the Chrome runtime, to run.

*Provide a webview of a website that is not owned or administered by you.

*Download or execute scripts dynamically outside a sandboxed environment such as a webview or a sandboxed iframe.

*Misuse notifications by sending spam, ads, promotions of any kind, phishing attempts, or unwanted messages in general.
The extension was working fine for years. It uses native messaging to communicate with an executable.
The support is so slow to answer and still answering generic stuff that don't really apply to my work.
Thanks a lot in advance!


text:
Q: probability and random variables notation I have a probability space $(\Omega, S, P)$, where $\Omega$ is a sample space, $S$ is a sigma-algebra, $P$ is probability measure, $P : S \to [0,1]$. Now I consider some other space $(A, B)$, where $B$ is a sigma-algebra on $A$. This allows me to define a random variable as a measurable function $X : \Omega \to B$ such that for every $\mathcal{B} \in B$ I have $X^{-1} (\mathcal{B}) = \{ \omega \in \Omega : X(\omega) \in \mathcal{B} \} \in S$. Finally I can bring in the probability distribution $\mathbb{P}$ which is another measure, this time defined as $\mathbb{P} : B \to [0,1]$, such that for any  $\mathcal{B} \in B$ we have $\mathbb{P} (\mathcal{B}) = P(X^{-1} (\mathcal{B}))$. This is, I believe, a pushforward measure, literally from the definition, correct?
So now I have some question regarding notation, for example in some textbooks I may encounter random variable $X \sim N(0,1)$ and some exercise to calculate $P ( -1 < X <2 )$. My question is what is $P$ in this case? Is it my original $P : S \to [0,1]$, or is it what I've defined as $\mathbb{P}$? Or maybe is it some not-exactly-formal thing to make the notation easier on the eyes?

A: In $P(-1<X<2)$ $P$ stands for the original probability measure on $\Omega$. In terms of $\mathbb P$ we can write $P(-1<X<2)=\mathbb P ((-1,2))$ since $X^{-1}((-1,2))=\{\omega \in \Omega: X(\omega) \in (-1,2)\}=\{\omega: -1<X(\omega) <2\}$.


text:
Q: CodeIgniter: Auth library or custom for FileMaker I have a site with the following requirements:
• register into MySQL, send activation email to user
• once activation email clicked, record activated and moved into FileMaker
From then on, login, password resets and updating details will be done directly on the filemaker database
There is already a FileMaker PHP API but my question is about authentication. There is obviously no out-of-the-box Auth library that will do exactly as above so I can either write my own or try and hack an existing library, such as TankAuth or IonAuth,
I haven't used either of those existing libraries before so I'm unsure of how much I'll need to hack without getting into it. Has anyone been down this road before?

A: I haven't done anything with FileMaker, but I recently had a similar project where I had a db update after activation (via email).
I used IonAuth which supports the activation email out of the box and you can simply add the extra functionality to the controller method you are using as the activation point. Presumably you can use the FileMaker API if the activation is successful and the rest is out of CodeIgniter's hands? Or did you require the auth package to be able to directly deal with FileMaker?


text:
Q: Merge lines and perform date operations I have a file with the following kind of lines:
file.txt
# 0, 18540, Wed Oct 26 08:01:40 2014
`cd xyz`
# 0, 18571, Wed Nov 26 08:01:41 2014
`cd abc`
# 0, 18881, Wed Nov 26 08:01:55 2014
`mkdir lib`

Now, i want to replace the content of the file to something like this:
new_file.txt
2014/Oct/26 08:01:40 `cd xyz`
2014/Nov/26 08:01:41 `cd abc`
2014/Nov/26 08:01:55 `mkdir lib`

A script or shell command will be great.

A: What about catching the 3rd field on odd lines and computing date like this:
$ date -d"Wed Oct 26 08:01:40 2014" +"%Y/%b/%d %T"
2014/Oct/26 08:01:40

Then, store the variable and print it back together with the full even line:
$ awk -F, 'NR%2{cmd ="date \"+%Y/%b/%d %T\" -d \""$3"\""
                cmd | getline var
                close (cmd)
                next
                }
           {print var, $0}' file

For your input it returns:
$ awk -F, 'NR%2{cmd ="date \"+%Y/%b/%d %T\" -d \""$3"\""; cmd | getline var; close (cmd); next} {print var, $0}' file
2014/Oct/26 08:01:40 `cd xyz`
2014/Nov/26 08:01:41 `cd abc`
2014/Nov/26 08:01:55 `mkdir lib`


text:
Q: Magento2: Editing attribute 'country_of_manufacture' is impossible
I want to edit the attribute country_of_manufacture by adding german translation(for german store view) for each value in the options section, but
I can't do so.
Is there a way how I can achieve this ?

A: I have the same issue. I spent hours for this. As I wanted "Country of Manufacturer" to be displayed on Category Filter.
As it's Magento Default System Attribute you can't do anything, even from the database as well.
I tried with Database also, still, it didn't work.
Solution:
Make you Custom Attribute with your named say example "Manufacturer" & input all the values as you have input
"Country of Manufacturer" Attribute (it's long but no choice).
Then it will work out. So remove "Country of Manufacturer" from Attribute Set & Set your once.
That way will work. I solved an issue by this way. No better option for Now. I think.
Hope it helps you.


text:
Q: ios: delegate doesn't respond i'm trying to create my first delegate here's what i'm trying to do
at class called PAStepper.h i did this
@class PAStepper;
@protocol StepperDelegate <NSObject>

@required
-(void)didIncrement;
-(void)didDecrement;

@end

@interface PAStepper : UIControl
{
    __weak id <StepperDelegate> stepperDelegate;
}
@property (nonatomic, weak) id <StepperDelegate> stepperDelegate;
@end

and synthized the property of course in the .m file
and then putten in the PAStepper.m  the following in a method
[self.stepperDelegate didDecrement];

in the controller i want to take the delegate i did this
.h
@interface OCSideCartViewController : UIViewController<StepperDelegate>

.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    PAStepper *stepper = [[PAStepper alloc]init];
    stepper.stepperDelegate = self;
}

-(void)didIncrement{
    NSLog(@"inc");
}
-(void)didDecrement{
    NSLog(@"dec");

}

knowing that this class is viewController that contain a table that every cell have PAStepper .. all i wanted that the delegate call didIncrement and didDecrement whenever i press the buttons

A: When you call this method
[self.stepperDelegate didDecrement];

NSLog you stepperDelegate and ensure it is not null. Can you confirm the method which calls your delegate is being called?

A: you can call this in your pastapper.h file
if ([stepperDelegate respondsToSelector:@selector(didIncrement)])
{
    [stepperDelegate performSelector:@selector(didIncrement)];
}

A: I can´t download the project, so i am guessing..
Is the Stepper in the Interface Builder?
If yes you don´t have to allocate it.

*

*Make an Outlet Connection of the Stepper in the OCSideCartViewController.

*Post this in OCSideCartViewController:

- (void)viewWillAppear:(BOOL)animated{
     self.stepper.stepperDelegate = self;
     [super viewWillAppear:animated];
}

If the Stepper is not an Outlet, you have to add it to your ViewControllers view after setting it´s bounds..


text:
Q: In XAMPP 7.1.12 I am not getting any output I wrote a function to fetch the user_status from SQL Server but its seems everything is correct but still I am not getting any output.
My connection with SQL Server is established. And my function is as follows:
function fetchuserStatus($username,$password) {
    include("db-settings.php");
    if ($conn) {
        $sql = "SELECT User_status from _yb_all_users_tbl where User_name = ? AND Password = ?";
        $parameters = array($username,$password);
        $stmt = sqlsrv_query($conn, $sql, $parameters);
        if( $stmt === false ) {
          die( print_r( sqlsrv_errors(), true));
         }
        if(sqlsrv_has_rows($stmt) === true) {
            sqlsrv_fetch($stmt);
        }
        sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn);
    } else {
        echo "Connection is not established";
    }
}
echo fetchuserStatus($username,$password);

And my db-settings.php file is:
$serverName = ".";
$connectionOptions = array(
    "Database" => "yaadbook",
    "UID" => "sa",
    "PWD" => "shiftu"
);
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if($conn) {
} else {
    echo "Connection Failure";
    die(print_r(sqlsrv_errors(),TRUE));
}

I am using PHP version 7.1.12. How can I resolve this issue?

A: I am not getting output because I need to use sqlsrv_execute()  after sqlsrv_prepare().
Here is my complete code:
function fetchuserStatus($username,$password){
  include("db-settings.php");
  $sql = "SELECT * from _yb_all_users_tbl where User_name = ? AND Password = ?";
  $parameters = array($username,$password);
  $stmt = sqlsrv_prepare($conn, $sql, $parameters);
  sqlsrv_execute($stmt);
  if(!$stmt) {
      die( print_r( sqlsrv_errors(), true));
  }
  while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
     return $row;
  }
  sqlsrv_free_stmt($stmt);
  sqlsrv_close($conn);
}


text:
Q: TextView.setText() in fragment crashes app I am trying to change TextView content on Sensor change but after calling TextView.setText("foo"); app crashes as if the TextView variable was null. I set up the  TextView variable in onCreateView. Here is the code:
public class fragment1 extends Fragment implements SensorEventListener
{
    private SensorManager mSrMgr = null;
    private Sensor mLight;
    private TextView page1;
    protected View mView;

    public fragment1()
    {
        // Required empty public constructor
    }

    public void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstance);
        mSrMgr = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
        mLight = mSrMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        page1 = container.findViewById(R.id.page1);
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        this.mView = view;
        return inflater.inflate(R.layout.fragment_fragment1, container, false);
    }

    public void onPause()
    {
        super.onPause();
        this.unregister();
    }

    public void onResume()
    {
        super.onResume();
        this.registerSensorListiner();
    }

    private void registerSensorListiner()
    {
        mSrMgr.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void unregister()
    {
        mSrMgr.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        Toast.makeText(getContext(),String.valueOf(event.values[0]),Toast.LENGTH_SHORT).show();
        page1.setText("elo"); //here is the crashing part
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {

    }
}

A: First, inflate the layout
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
page1 = view.findViewById(R.id.page1);
return view, false);

use view object to call findViewById method

A: Use this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
   View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
   this.mView = view;
   page1 = view.findViewById(R.id.page1);
   return view;
}

Instead of this
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        page1 = container.findViewById(R.id.page1);
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        this.mView = view;
        return inflater.inflate(R.layout.fragment_fragment1, container, false);
    }

A: Why Multiple times R.layout. ?
  View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        this.mView = view;
        return inflater.inflate(R.layout.fragment_fragment1, container, false);

It should be One Time. At first modify here.
Note
You will get NullPointerException.

Thrown when an application attempts to use null in a case where an
  object is required.

You should pass View's object .
page1 = view.findViewById(R.id.page1);

Finally
 View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
 page1 = view.findViewById(R.id.page1);
 this.mView = view;
 return view;

A: public class fragment1 extends Fragment implements SensorEventListener {
    private SensorManager mSrMgr = null;
    private Sensor mLight;
    private TextView page1;
    protected View mView;

    public fragment1() {
        // Required empty public constructor
    }

    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        mSrMgr = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
        mLight = mSrMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_fragment1, container, false);
        page1 = mView.findViewById(R.id.page1);
        return mView;
    }

    public void onPause() {
        super.onPause();
        this.unregister();
    }

    public void onResume() {
        super.onResume();
        this.registerSensorListiner();
    }

    private void registerSensorListiner() {
        mSrMgr.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void unregister() {
        mSrMgr.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Toast.makeText(getContext(), String.valueOf(event.values[0]), Toast.LENGTH_SHORT).show();
        page1.setText("elo"); //here is the crashing part
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

A: put your findViewById code in onActivityCreated like below:
 @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        page1 = getActivity().findViewById(R.id.page1);
    }

A: Sometimes when creating layouts in fragments you copy and paste xml code that has duplicate IDs. When you then call the id of the pasted resources it will try to invoke the first defined resources which is probably null at runtime. Double check if the page1 id is found only in one fragment's Xml. If not work around "findviewbyid".I hope that helps, there's little detail in your code(Error msg)