text:
Q: Visual Studio keeps crashing: Application Error VS keeps crashing, usually when I want to click on some text I want to edit.
When I look in the event log I get;
Log Name:      Application
Source:        Application Error
Date:          26/03/2013 15:18:30
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      (removed)
Description:
Faulting application name: devenv.exe, version: 10.0.40219.1, time stamp: 0x4d5f2a73
Faulting module name: clr.dll, version: 4.0.30319.269, time stamp: 0x4ee9ae83
Exception code: 0xc00000fd
Fault offset: 0x00194a5d
Faulting process id: 0x47c
Faulting application start time: 0x01ce2a3396f0faf2
Faulting application path: c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Report Id: 69d0daee-9628-11e2-aeba-005056c00008
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2013-03-26T15:18:30.000000000Z" />
    <EventRecordID>23553</EventRecordID>
    <Channel>Application</Channel>
    <Computer>(removed)</Computer>
    <Security />
  </System>
  <EventData>
    <Data>devenv.exe</Data>
    <Data>10.0.40219.1</Data>
    <Data>4d5f2a73</Data>
    <Data>clr.dll</Data>
    <Data>4.0.30319.269</Data>
    <Data>4ee9ae83</Data>
    <Data>c00000fd</Data>
    <Data>00194a5d</Data>
    <Data>47c</Data>
    <Data>01ce2a3396f0faf2</Data>
    <Data>c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe</Data>
    <Data>C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll</Data>
    <Data>69d0daee-9628-11e2-aeba-005056c00008</Data>
  </EventData>
</Event>

also I get this;
Log Name:      Application
Source:        Windows Error Reporting
Date:          26/03/2013 15:21:01
Event ID:      1001
Task Category: None
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      (removed)
Description:
Fault bucket 2985755835, type 1
Event Name: APPCRASH
Response: Not available
Cab Id: -721041670

Problem signature:
P1: devenv.exe
P2: 10.0.40219.1
P3: 4d5f2a73
P4: clr.dll
P5: 4.0.30319.269
P6: 4ee9ae83
P7: c00000fd
P8: 00194a5d
P9:
P10:

Attached files:
C:\Users\xxx\AppData\Local\Temp\WERE350.tmp.WERInternalMetadata.xml
C:\Users\xxx\AppData\Local\Temp\WERF0C9.tmp.appcompat.txt
C:\Users\xxx\AppData\Local\Temp\WERF108.tmp.mdmp

These files may be available here:
C:\Users\xxx\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_devenv.exe_3f453f47c0d86c534010e7cf6788bb8f42fbcd_cab_144e2fda

Analysis symbol:
Rechecking for solution: 0
Report Id: 69d0daee-9628-11e2-aeba-005056c00008
Report Status: 8
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Windows Error Reporting" />
    <EventID Qualifiers="0">1001</EventID>
    <Level>4</Level>
    <Task>0</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2013-03-26T15:21:01.000000000Z" />
    <EventRecordID>23554</EventRecordID>
    <Channel>Application</Channel>
    <Computer>(removed)</Computer>
    <Security />
  </System>
  <EventData>
    <Data>2985755835</Data>
    <Data>1</Data>
    <Data>APPCRASH</Data>
    <Data>Not available</Data>
    <Data>-721041670</Data>
    <Data>devenv.exe</Data>
    <Data>10.0.40219.1</Data>
    <Data>4d5f2a73</Data>
    <Data>clr.dll</Data>
    <Data>4.0.30319.269</Data>
    <Data>4ee9ae83</Data>
    <Data>c00000fd</Data>
    <Data>00194a5d</Data>
    <Data>
    </Data>
    <Data>
    </Data>
    <Data>
C:\Users\xxx\AppData\Local\Temp\WERE350.tmp.WERInternalMetadata.xml
C:\Users\xxx\AppData\Local\Temp\WERF0C9.tmp.appcompat.txt
C:\Users\xxx\AppData\Local\Temp\WERF108.tmp.mdmp</Data>
    <Data>C:\Users\xxx\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_devenv.exe_3f453f47c0d86c534010e7cf6788bb8f42fbcd_cab_144e2fda</Data>
    <Data>
    </Data>
    <Data>0</Data>
    <Data>69d0daee-9628-11e2-aeba-005056c00008</Data>
    <Data>8</Data>
  </EventData>
</Event>

A: Standard checks to resolve these types of errors:

*

*uninstall any beta/ctp releases for Visual Studio.

*look in the Windows Event Viewer and check for the following two items in the Application log:  it will contain a stacktrace which may help you find the culprit.

*delete any *.*user files and the solution user options file (.suo)

*Run visual studio with activity logging turned on to see if the logs contain a hint to what's causing the crash. (devenv /log)

*Run Visual Studio in Safe mode (devenv /safemode)

*Clear the ComponentModelCache folder

*Check to see if any extensions/add-ons/plugins need updates and update them first to see if that fixes your problem.

*disable all add-ins and extensions (VS Commands, WebEssentials etc)

*uninstall all plugins (resharper, coderush, reflector etc)

*install the latest patches and service packs, you may need to re-apply these servicepacks if you've installed SQL Server or another product that installs a feature which is based on Visual Studio Shell:

*

*2005: SP 1 &  TFS 2010 Forward Compatibiltiy Patch & Visual Studio update for Windows Vista

*2008: SP 1 & TFS 2012/VSO Forward Compatibiltiy Patch

*2010: SP 1 & TFS 2012/VSO Forward Compatibility Patch & Visual Studio update for Windows 8 and TFS 2012.

*2012: Update 5

*2013: Update 5

*2015: Update 3 & KB3165756

*2017: Update to the latest version

*reset vs settings (devenv /resetsetting /resetaddin /resetskippkgs /setup)

*backup & remove the %LOCALAPPDATA%\Microsoft\VisualStudio\ folder to have Visual Studio recreate your setting folder.

*Do not run Visual Studio while installing extensions, updates etc.

Try to reproduce it. If it still occurs, repair Visual Studio and reapply the latest service packs and hotfixes in order. If it then still occurs, submit a support ticket to Microsoft, or an item on connect.
If it doesn't occur turn-on/install/restore the items one by one until you can find the culprit. I know it's a lot of work, but since your error happens somewhere deep inside the CLR (you're seeing a StackOverflow Exception), it's hard to pinpoint the problem easily. When you've found the problematic item, see if there is an update for it or request their support (or update your question).
In the worst case you can perform a force-uninstall of Visual Studio using vs_setup /uninstall /force, that should work on the 2012 and newer installers.
If you're still on an old version of Visual Studio (2010 or older), really, really. really consider upgrading. These versions are past their support lifetime and were built for versions of Windows that are not even supported anymore. I know the pain these upgrades can cause in the short term, but the long-term solution is really to move away from the old versions.

A: None of the above worked. But I saw a user settings file had appeared next to the .sln file. I deleted it, and the solution's corresponding .suo file. This fixed the problem.

A: A quick and dirty approach is to rename your %LOCALAPPDATA%\Microsoft\VisualStudio\ folder to VisualStudio.backup\ and restart devenv.  It will recreate the folder and populate it with default settings files. You will lose any customizations of course,  but many times that is ok and/or easily recreated.  You always have the backup folder just in case.
If you want to take it a step further, you can move settings one-by-one from the backup back into the new folder until you can completely isolate the problem.


text:
Q: delete function in yii controller How do i get the delete button to work in Yii? These are my controller and view and i have a custom delete button.
public function actionDelete($id)

{
    $model = $this->loadModel($id);
    $model->DeletedItem = 1;

$model->save();

    echo"success";
    if(!isset($_GET['ajax']))
    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

}

and my view is:
function Delete(Iid,Itype){

    if(type=="a")
    {
        console.log("Assignment");
        $.ajax({
            type: 'GET',
            //data: Iid,
            url:  '/grade/delete/' + Iid,
            success: function (data) {
                console.log(data);
                //$.fn.yiiGridView.update('Assignment-grid');
            }
    });

A: Normally in yii1 for delete you should do this way (using $model->delete();)
public function actionDelete($id)
{
  $model = $this->loadModel($id);
  //$model->DeletedItem = 1;
  $model->delete();
  // $model->save();

 echo"success";
 if(!isset($_GET['ajax']))
 $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

}

For the view custom delete botton  could be a path problem
try assign the routed path this way
 url:  <?php echo "'" .  Url::to(['grade/delete/']) ."'" ?>  + Iid,

redpajama_set_name: RedPajamaStackExchange


text:
Q: \footnotesize in output stream generates unexpected "Undefined control sequence" I am writing styled text to an external file (using the newfile package). I can successfully style the text with many attributes, e.g., \large\mdseries\itshape. But, very puzzling to me, when I style the text with \footnotesize, I get an unexpected "Undefined control sequence" error, and I can't tell why it is arising:
(/compile/output.nameofstream
! Undefined control sequence.
l.1 ... {10}{12}\selectfont \abovedisplayskip 10\p
                                                  @ plus2\p@ minus5\p@ \abov...

The following MWE compiles fine and generates appropriately styled text both in the external file and in the output. The external file contains:
\relax \fontsize {14.4}{18}\selectfont \mdseries \itshape Text to be styled

But when I uncomment out \renewcommand{\styleForText}{\footnotesize}, I get the above error message and the external file contains:
\relax \fontsize {10}{12}\selectfont \abovedisplayskip 10\p@ plus2\p@ minus5\p@ \abovedisplayshortskip \z@ plus3\p@ \belowdisplayshortskip 6\p@ plus3\p@ minus3\p@ \def \leftmargin \leftmargini \parsep 5\p@ plus2.5\p@ minus\p@ \topsep 10\p@ plus4\p@ minus6\p@ \itemsep 5\p@ plus2.5\p@ minus\p@ {\leftmargin \leftmargini \topsep 6\p@ plus2\p@ minus2\p@ \parsep 3\p@ plus2\p@ minus\p@ \itemsep \parsep }\belowdisplayskip \abovedisplayskip Text to be styled

I never expected that \footnotesize would result in such different behavior than \large. What's going on?
\documentclass[12pt]{article}
\usepackage{newfile}
\newcommand{\streamName}{nameofstream}
\newcommand{\sendStyledTextToStream}[1]{%
    \addtostream{\streamName}{\styleForText#1}%
}
\newcommand{\printStream}{%
    \closeoutputstream{\streamName}%
    \input{\jobname.\streamName}%
}
\newcommand{\styleForText}{\large\mdseries\itshape}
%\renewcommand{\styleForText}{\footnotesize}
\begin{document}
\newoutputstream{\streamName}
\openoutputfile{\jobname.\streamName}{\streamName}
\sendStyledTextToStream{Text to be styled}
\printStream
\end{document}

A: I'm answering my own question in order to bring closure. A commenter (@GuM) answered it in a comment, but never converted it into an answer.
His solution: Use \protect\footnotesize.
He gave the further explanation:

It's best to \protect the \large declaration too; it doesn't exhibit
  the same problem, in this particular situation, just because its
  expansion doesn't happen to contain "internal" commands using the @
  character, contrary to \footnotesize. On the other hand, you might
  have uncovered a bug: several years ago, the commands for changing the
  font style (e.g., \itshape, \mdseries…) were made robust so that they
  no longer required to be \protected; but apparently, they forgot to
  apply a similar change to the commands that change the font size!


text:
Q: PDO rowCount not returning correct number of affected rows I'm having a problem with PDO prepared statement and rowCount returning incorrect number of affected rows.
I have a simple test database of:
create table test (
   boolean var1;
);

Then I have the following test code:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => true));
echo $sth->rowCount();

Which returns as expected: 1 rows affected
And when I insert an invalid type and the Insert fails:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => 20));
echo $sth->rowCount();

Which returns as expected: 0 rows affected
However, When I have multiple inserts -
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");

$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";

$sth->execute(array(':val' => 20));
echo $sth->rowCount();

Results in: 1, 1
And if I flip execution order I get: 0, 1
Why is the rowCount() -- Affected rows not being set to zero on a fail statement after a success statement?
I'm running php 5.3.6-13 and Postgresql 9.1

A: It seems to me that $sth->execute(array(':val' => true)) completes successfully thus increasing the rowCount, but $sth->execute(array(':val' => 20)) does not. Here is the state of the rowCount for the $sth at each stage:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");

# No successful DML queries have been done with the $sth yet.
# rowCount == 0

$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";

# rowCount increases because of a successful INSERT statement
# rowCount == 1

$sth->execute(array(':val' => 20));
echo $sth->rowCount();

# rowCount does not increase due to failed INSERT statement
# rowCount == 1

Now, lets look at that in the opposite order:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");

# No successful DML queries have been done with the $sth yet.
# rowCount == 0

$sth->execute(array(':val' => 20));
echo $sth->rowCount();

# rowCount does not increase due to failed INSERT statement
# rowCount == 0

$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";

# rowCount increases because of a successful INSERT statement
# rowCount == 1


text:
Q: fscanf only reads one line This may have some other mistakes. But the only thing I concern is fscanf. It doesn't read new line. It reads only the first line. Can you please tell me how to fix it.
#include <stdio.h>
#include<stdlib.h>
int main(void){

    int no = 0;
    FILE *cPtr;

    cPtr = fopen("number.dat","a");
    if(cPtr==NULL){
        printf("Unexpected error detected while creating new file\n");
    }

    do{

    printf("Enter your number : ");
        scanf("%d",&no);
        if(!(no==-99)){
            fprintf(cPtr,"%d\n",no);
        }

    }while(!(no==-99));

    fclose(cPtr);

    int n,i;
    FILE *fp;

    fp=fopen("number.dat","r");
    if(fp==NULL){
        printf("Error");
        exit(1);
    }

    for(i=1;i<10;i++){

        fscanf(fp,"%d",&n);
        printf("\n%d",n);

        fclose(fp);

    }

}


text:
Q: How do I make my enemies spawn randomly between 4 different Vector3 positions? I am currently creating a game where the player is on a square platform and I want the enemies to spawn randomly from the four edges of the platform. So far I am able to make my enemies spawn randomly from one edge, but don't know how to make them spawn from all four. I imagine it would work with a Vector3 array? But I am struggling to get this right. Please help!
My spawn code so far:
void SpawnRandomEnemy()
    {
        if(!playerControllerScript.gameOver && !playerControllerScript.hasFreezePowerup)
        {
            int enemyIndex = Random.Range(0, enemyPrefabs.Length);
            Vector3 spawnPos = new Vector3(Random.Range(-spawnRange, spawnRange), 0, spawnPosZ);

            Instantiate(enemyPrefabs[enemyIndex], spawnPos, enemyPrefabs[enemyIndex].transform.rotation);
        }
    }

A: The easiest thing you could go for is placing 4 empty gameobjects to serve as spawners at each of the 4 sides of the square. Place them in an array consisting of gameobjects (similar to what you've done with the enemyPrefabs array).
Then you would pick 1 of them randomly just like picking the enemy index:
int spawnIndex = Random.Range(0, spawnPoints.Length);

Then you could take the position of that spawn point.
Vector3 spawnPos = spawnPoints[spawnIndex].transform.position;

Then you can edit that spawn position in many ways you would like. For example, you can set Y to be equal to 0 (or whatever fits your needs), you can add some offset to the X position of the gameobject (so that they do not spawn everytime at the same position). You can basically do that for either X, Y, Z - you just have to play around with it until it really starts acting as a randomly set spawner (just be careful with the offsets so that your enemies do not spawn out of the square).
spawnPos.X = spawnPos.X + someOffset;

You will have to generate the offset randomly, too - just like the things above.


text:
Q: Link ul with Ajax Action Link? How can i link my 'box' with my ajax action link?
code

@item.SiteName

Link
 @Ajax.ActionLink(@item.SiteName, "GetSiteApplications", "Sites", new { siteName = @item.SiteName }, new AjaxOptions { UpdateTargetId = @item.SiteId.ToString() })


text:
Q: Archiving a zip file and save it to a location of choice, with no extra file paths? I am trying to save a XAP file witch is basically like a zip file, and i can Archive and save it, but it adds to many folders?
I am using Ionic.Zip DLL to Archive my XAP file.
The file saves to my path, but when i open it up it has the folder users, then in there it has the folder Shaun, and in that folder a folder Documents, in the the folder FormValue then in side there it has my 3 files i zipped.
I need the Xap file only to contain the 3 files i zipped and not all the extra folders inside.
using (ZipFile zip = new ZipFile())
{
// add this map to zip
zip.AddFile("C://Users//Shaun//Documents//FormValue//" + property_details_locality_map);
zip.AddFile("C://Users//Shaun//Documents//FormValue//data.xml");
zip.AddFile("C://Users//Shaun//Documents//FormValue//dvform.dvform");
zip.Save("C://Users//Shaun//Documents//FormValue//NewValuation.xap");
}

A: List<string> filesToBeAdded = new List<string>();
filesToBeAdded.Add("C://Users//Shaun//Documents//FormValue//" + property_details_locality_map);
filesToBeAdded.Add("C://Users//Shaun//Documents//FormValue//data.xml");
filesToBeAdded.Add("C://Users//Shaun//Documents//FormValue//dvform.dvform");
zip.AddFiles(filesToBeAdded, false, "ShaunXAP"); // you could pass empty string here instead of "ShaunXAP"
zip.Save("C://Users//Shaun//Documents//FormValue//NewValuation.xap");

this will put all files into one common folder("ShaunXAP" in this case) and ignores the folder hierarchy of the files that are archieved.

A: Use the zip.AddFile(string fileName, string directoryPathInArchive) overload and specify the empty string "" for the second parameter:
zip.AddFile("C://Users//Shaun//Documents//FormValue//" + property_details_locality_map, "");
zip.AddFile("C://Users//Shaun//Documents//FormValue//data.xml", "");
zip.AddFile("C://Users//Shaun//Documents//FormValue//dvform.dvform", "");

From the documentation:
/// <param name="directoryPathInArchive">
///   Specifies a directory path to use to override any path in the fileName.
///   This path may, or may not, correspond to a real directory in the current
///   filesystem.  If the files within the zip are later extracted, this is the
///   path used for the extracted file.  Passing <c>null</c> (<c>Nothing</c> in
///   VB) will use the path on the fileName, if any.  Passing the empty string
///   ("") will insert the item at the root path within the archive.
/// </param>


text:
Q: How to fix "Invalid row number (-4) outside allowable range (0..1048575)"? I am trying to write some data into a xlsx file using apache poi.
and my code goes like this
The excel sheet contains 6 rows and 2 columns already
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class excelwrite {

public void excelWrite(String filepath, String filename, String
sheetname, String[] dataTowrite) throws IOException
{
    File file = new File(filepath+"\\"+filename);
    FileInputStream inputstream  = new FileInputStream(file);
    Workbook workbook = null;
    String fileextensionname =
filename.substring(filename.indexOf(".")+1);
    if(fileextensionname.equalsIgnoreCase("xlsx"))
        workbook = new XSSFWorkbook(inputstream);
    else
        workbook = new HSSFWorkbook(inputstream);
    Sheet sheet = workbook.getSheet(sheetname);

    int Rowcount = sheet.getFirstRowNum() - sheet.getLastRowNum();

    Row row = sheet.getRow(0);

    Row newrow = sheet.createRow(Rowcount+1);

    for(int i=0;i<row.getLastCellNum();i++)
    {
        Cell cell = newrow.createCell(i);
        cell.setCellValue(dataTowrite[i]);
    }
    inputstream.close();

    FileOutputStream outputstream = new FileOutputStream(file);

    workbook.write(outputstream);
    outputstream.close();
  }

public static void main(String[] args) throws IOException {

    excelwrite write = new excelwrite();
    String[] datatowrite = {"Mr. E","DURGAPUR"};
    String filepath = "C:\\Users\\malfoy\\Desktop";
    write.excelWrite(filepath,"testfile.xlsx","read",datatowrite);

}

}

Now while running the program, there is an exception which says
"Invalid row number (-4) outside allowable range (0..1048575)".
How to fix this?

A: int Rowcount = sheet.getLastRowNum() - sheet.getFirstRowNum();


text:
Q: How do I change a color of a Html element in a canvas? I have made a post on this before however, it was not in a canvas, but when you try to apply this to a canvas It gives an error along the lines of Cant change the color of undefined so I thought it was an error of the way I defined it so I would add it to a class then run it as changing the color of all elements in the class, but when I try it the canvas just disappears..  but getting to the point is there an easy way to change the color of a HTML element in a canvas or am I just crazy
Code

var myGamePiece = el.classList.add("class1");
var myObstacles = [];
var myScore;

function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 120);
  myGamePiece.gravity = 0.05;
  myScore = new component("30px", "Consolas", "black", 280, 40, "text");
  myGameArea.start();
}

var myGameArea = {
  canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
  },
  clear: function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }
}

function component(width, height, color, x, y, type) {
  this.type = type;
  this.score = 0;
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.gravity = 0;
  this.gravitySpeed = 0;
  this.update = function() {
    ctx = myGameArea.context;
    if (this.type == "text") {
      ctx.font = this.width + " " + this.height;
      ctx.fillStyle = color;
      ctx.fillText(this.text, this.x, this.y);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
      this.gravitySpeed = 0;
    }
  }
  this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  myScore.text = "SCORE: " + myGameArea.frameNo;
  myScore.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

function everyinterval(n) {
  if ((myGameArea.frameNo / n) % 1 == 0) {
    return true;
  }
  return false;
}

function accelerate(n) {
  myGamePiece.gravity = n;
}

function Test() {
  document.getElementsByClassName("class1").style.background = "yellow";
}
canvas {
  border: 1px solid #d3d3d3;
  background-color: #f1f1f1;
}

.class1 {}
<body onload="startGame()">
  <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
  <p> Credit To W3Schools.com </p>
  <button onclick="test">Click To Change Player's Color</button>
</body>

A: The code starts with: var myGamePiece = el.classList.add("class1");el is not defined but anyway myGamePiece needs to be a component as created in startGame, it is not an ordinary HTML element.
It is the creation of that component that the color is set. Currently the color is hardcoded as 'red'. To change the color you need to set a variable, let's call it playerColor, and use that in the component creation call rather than 'red'.
You are using function test to set up a color so let's change the test function to do that, but you need to get that color set up before startGame otherwise the canvas will have the incorrect color for the piece (or no set color).
var playersColor = "red"; //the default value if the player doesn't change it
var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
  myGamePiece = new component(30, 30, playersColor, 10, 120);//use playersColor
  myGamePiece.gravity = 0.05;
  myScore = new component("30px", "Consolas", "black", 280, 40, "text");
  myGameArea.start();
}

var myGameArea = {
  canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.frameNo = 0;
    this.interval = setInterval(updateGameArea, 20);
  },
  clear: function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }
}

function component(width, height, color, x, y, type) {
  this.type = type;
  this.score = 0;
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.gravity = 0;
  this.gravitySpeed = 0;
  this.update = function() {
    ctx = myGameArea.context;
    if (this.type == "text") {
      ctx.font = this.width + " " + this.height;
      ctx.fillStyle = color;
      ctx.fillText(this.text, this.x, this.y);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
      this.gravitySpeed = 0;
    }
  }
  this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].x += -1;
    myObstacles[i].update();
  }
  myScore.text = "SCORE: " + myGameArea.frameNo;
  myScore.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

function everyinterval(n) {
  if ((myGameArea.frameNo / n) % 1 == 0) {
    return true;
  }
  return false;
}

function accelerate(n) {
  myGamePiece.gravity = n;
}

function test() {
  playersColor = "yellow";
}

<body>
  <button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
  <p> Credit To W3Schools.com </p>
  <button onclick="test()">Click To Change Player's Color</button>
  <button onclick="startGame();">Click to start the game</button>
</body>

...............................................................................
Although the following errors are not fundamentally what is causing non-changing of the player's color, they contain some coding errors which it might be helpful to point out for the future.
<button onclick="test">Click To Change Player's Color</button>
<script>
    function Test() {
         document.getElementsByClassName("class1").style.background = "yellow";
</script>

The onclick="test" does nothing - you may be confusing the structure element.onclick = test - which sets which function is run on the element being clicked - with the syntax for the onclick="test();" needed in the button element attributes.
A further error is that the function is called Test, not test. Javascript is case sensitive. Also you need to select the one element with class1, not retrieve a collection of such elements, so you can set its style (if that is useful, is it?).


text: Q: Защита ключа/сертификата OpenVPN Можно ли привязать ключ/сертификат для пользователя к физическому адресу машины (компьютеру). Как сделать так, чтоб клиентский ключ/сертификат не сработал на других компьютерах при передачи их другому лицу. Привязка по айпи невозможна, так как он очень часто меняется. Подскажите, как это сделать, подтолкните в правильное направление пожалуйста.


text:
Q: Sort by field before the first comma but keep the first line of the file as is !sort -k 1n hits.csv -o output.csv
The above sorts the file according to the field preceding the first comma. But how do I keep the first line? (I want the first line of hits.csv to appear as first line in output.csv as well.)

A: $ pg test1.txt
keep this line
55, some stuff 1, other stuff 1
6, some stuff 2, other stuff 2
111, some stuff 3, other stuff 3
2, some stuff 4, other stuff 4
4, some stuff 5, other stuff 5
6, sdsdsdsdsdsdsds
7, ttttttttt

$ head -n 1 test1.txt >sorted.txt && tail -n +2 test1.txt | sort -k 1n >> sorted.txt

$ pg sorted.txt
keep this line
2, some stuff 4, other stuff 4
4, some stuff 5, other stuff 5
6, sdsdsdsdsdsdsds
6, some stuff 2, other stuff 2
7, ttttttttt
55, some stuff 1, other stuff 1
111, some stuff 3, other stuff 3


text:
Q: R: how to change font and alignment of text in knitr word ```{r results = 'asis'}
for(i in 1:10){
  cat(paste("This is iteration number" i))
}
```

After I output the resulting .docx file, the text is left-aligned in size 12 Cambria font by default. How can I change the alignment to center, change the font size, and font type in my .Rmd file?

A: One way to do this is to use the reference_docx tag in the YAML header like this:
---
title: "Untitled"
author: "Me X. Person"
date: "April 3, 2018"
output:
  word_document:
    reference_docx: word-style-02.docx
fontsize: 10pt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r results = 'asis'}
for(i in 1:10){
  cat(paste("This is iteration number", i, "<P><br>"))
}
```

Next, prepare a file in Word where all you do is control the styles -- I knit to Word and found out that in this example, the code is controlled by the style titled Compact. So I clicked on that square in the ribbon in the MS Word header, and set it to 16 point Courier New (centered). The Word file that I used is here so you can download and open/try it: Drive link
The output it generates looks like this in Word:

If this is way off of what you were looking for, just let me know and I will delete it. Hopefully it is at least little bit useful.

A: The above solution didn't really work for me but I found a tweak to fix.
In Microsoft Word, you want to make sure you modify a section of text in the .docx reference document for each of the styles:

*

*First Paragraph

*Body Text

*Compact

Changing font size from the home tab won't do anything. You have to right click on the selected style ribbon -> Modify and change the font size in the popup window for that specific style.
Here's a download link that makes the style more similar to SAS outputs when using the cat() function to print text in your .Rmd to word output:
https://drive.google.com/file/d/12VZUPXaAGMKPUAJsohZRYQrToFr6awzY/view?usp=sharing

note that I call the file word-style.docx not word-style-02.docx


text:
Q: Emacs input-decode-map for terminal I have asked a question about Ctrl-arrow keybinding in Emacs in terminal:
Emacs Ctrl modifiers don't work in console
And was told, that Linux terminal emulator doesn't process this combination. I managed to create a file for loadkeys command, that processes these keys:
control keycode 105 = F100
string F100 = "\033[[left"
control keycode 106 = F101
string F101 = "\033[[right"

Then loaded it from root:
#loadkeys ./funcskeys

After that every time I click Ctrl-right or Ctrl-left in console, I get 'right' or 'left' printed. Now I need to process this in Emacs. As far as I understand from this question:
Binding M-<up> / M-<down> in Emacs 23.1.1
it must be done, using input-decode-map function. But I couldn't make it work. Plz, help.

A: Change your "funcskeys" file slightly to produce the following escape sequences:
control keycode 105 = F100
string F100 = "\033[1;5D"
control keycode 106 = F101
string F101 = "\033[1;5C"

Then add the following lines to your .emacs file:
(define-key input-decode-map "\e[1;5C" [(control right)])
(define-key input-decode-map "\e[1;5D" [(control left)])

After running loadkeys and restarting Emacs, CTRL+left and CTRL+right should work. You can verify this by typing:
C-h k C-right
and
C-h k C-left
To actually bind these keystrokes to a command, such as forward-word, you might have to add the following lines to your .emacs file as well:
(global-set-key [(control right)] 'forward-word)
(global-set-key [(control left)] 'backward-word)

Note that this whole approach specifically only makes the key combinations CTRL+left and CTRL+right work. It does not for instance make ALT+left / ALT+right work, or any other key combinations involving the CTRL character.


text:
Q: If P then not Q and if not P then Q. What is the relationship called? Is there a name of this relationship?
P => Q and ~P => ~Q seems to be called equivalence. But could not find a name for P => ~Q and ~P => Q by cursory googling and browsing related Wikipedia articles.

A: $(P\to Q) \wedge (\neg P\to \neg Q)$ is an equivalence between $P$ and $Q$.
$$\begin{align}(P\to Q) \wedge (\neg P\to \neg Q) \quad\iff&\quad P\leftrightarrow Q\\[1ex]\iff&\quad (P\wedge Q)\vee(\neg P\wedge \neg Q)\\[1ex]\iff&\quad (P\vee\neg Q)\wedge(\neg P\vee Q)\end{align}$$
$(P\to \neg Q)\wedge(\neg P\to Q)$ is an exclusive disjunction between $P$ and $Q$.
$$\begin{align}(P\to \neg Q)\wedge(\neg P\to Q) \quad\iff&\quad P\oplus Q\\[1ex]\iff&\quad (P\vee Q)\wedge(\neg P\vee\neg Q)\\[1ex]\iff&\quad (P\wedge\neg Q)\vee(\neg P\wedge Q)\\[1ex]\iff&\quad P\leftrightarrow \neg Q\end{align}$$


text:
Q: Abelianization of the free product of two cyclic groups. Suppose that $G=G_1*G_2$ where $G_1$ and $G_2$ are cyclic of orders $m$ and $n$ respectively.  Show that $G/[G,G]$ has order $mn$. Can anyone help me?

A: A categorical solution: Abelization is left adjoint to forgetting commutativity and therefore commutes with colimits. Since $G\ast H$ is a coproduct of groups, and $G\oplus H$ is a coproduct of abelian groups, we have $$A(G_1\ast G_2)\cong A(G_1)\oplus A(G_2)\cong G_1\oplus G_2\,,$$where the last step follows from commutativity of cyclic groups (this concept has a name, $\mathbf{Ab}$ is a reflective subcategory of $\mathbf{Grp}$). Of course, $A$ denotes the abelization functor.

A: Hint 1: Let $G=\langle a, b; a^n, b^m\rangle$. Then the abelianisation of $G$ has presentation $\langle a, b; a^n, b^m, [a, b]\rangle$.
Hint 2: The group $G/H$ is abelian if and only if the map $G\rightarrow G/H$ factors through the quotient $G/[G, G]$.


text:
Q: Drag drop URL into a Swing panel Is there a way to capture the URL of a link dragged from any browser into a Java Swing based panel?
I am building an application where such ability (to capture links based on what users drag and drop) greatly enhances the ease of use.
I noticed that Java 7 supports drag and drop of files in a simpler manner, but am not sure how to use that for capturing dragged links.


text:
Q: How to compare two adjacent items in the same list - Python I am searching for a way to compare two adjacent items in a list, eg. comparing which has a higher value, and then I will sort them accordingly. It is a list the user will be inputting, so it is not a case of just
if l[1] > l[2], as I will not know the length of the list, so
I will need a general statement for use in a for loop.
I had the idea of having something akin to
    for i in l:
    if x > i[index of x + 1]
 but do not know how to find the index of the variable.
Any help appreciated, Thank you
EDIT: I am aware of the built in sort function, but just wanted to practice coding and algorithm-writing by creating my own :)

A: The quick-and-ugly solution would be this (don't use it!):
for i, item in enumerate(lst):
    # here you can use lst[i + 1] as long as i + 1 < len(lst)

However, do not implement list sorting by yourself! Use .sort() to sort in-place or sorted() if you want to create a new list instead. There is a really good guide on how to sort things on the python website.
If that's not your intention.. instead of the loop I posted above there's also a much nicer way to iterate over chunks from a list in another SO question:
import itertools
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

You use to like this:
for x, y in grouper(2, lst):
    # do whatever. in case of an odd element count y is None in the last iteration

A: You can use zip():
In [23]: lis = [1,7,8,4,5,3]

In [24]: for x, y in zip(lis, lis[1:]):
   ....:     print x, y           # prints the adjacent elements
             # do something here
   ....:
1 7
7 8
8 4
4 5
5 3

A: you can also use inbuilt reduce function
e.g. :
l = [1,2,3,4,5,6,7]

def my_function(a,b):
    # your comparison between a and b
    # return or print values or what ever you want to do based on the comparison

reduce(my_function, l)

reduce will automatically take care of i and i + 1.
Hope it helps. :)

A: there is built in function cmp, which you can use for the comparison
I needed to check if all items in list are identical, so I did this:
def compare(x, y):
    if x == y:
        return x
    return False

reduce(compare, my_list)

When you run this with say [1,1,1,1,1,1], it prints 1, when one of numbers doesn't match, it returns False .. simple


text:
Q: Generated primary keys start form 9951 instead of the 10000 I make use of:
NetBeans IDE 6.7.1,
GlassFish v2.1,
Oracle 10g XE,
JAVA 6 SE,
JAVA 5 EE,
From inside a stateless EJB I persist entities of type customer I have the annotation:
@SequenceGenerator(name="seq", sequenceName="cust_id_seq") in the class customer so the
primary keys are autogenerated in the database from the sequence cust_id_seq but when I persist the first customer the primary key is 9951 instead of 10000, the primary key of the second customer is 9952. The output of the GlassFish v2.1 after I persisted two customers is:
Application server startup complete.
My id is: 0
TopLink, version: Oracle TopLink Essentials - 2.1 (Build b31g-fcs (10/19/2009))
Server: unknown
file:/C:/Documents%20and%20Settings/IOANNIS_PAPAIOANNOU/My%20Documents/NetBeansProjects/VideoClub/dist/gfdeploy/VideoClub-ejb_jar/-vc_pu login successful
My id is: 9951
My id is: 0
My id is: 9952
@Entity
@Table(name = "customer")
@SequenceGenerator(name="seq", sequenceName="cust_id_seq")
public class Customer implements Serializable
{

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
@Column(name="CUST_ID")
private int id;

@Column(name = "phone_number")
private int phoneNumber;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "credit")
private int credit;

@OneToMany
private Collection<CustRentMovie> rents = new ArrayList<CustRentMovie>();

public int getCredit()
{
    return credit;
}

public void setCredit(int credit)
{
    this.credit = credit;
}

public String getFirstName()
{
    return firstName;
}

public void setFirstName(String firstName)
{
    this.firstName = firstName;
}

public int getId()
{
    return id;
}

public void setId(int id)
{
    this.id = id;
}

public String getLastName()
{
    return lastName;
}

public void setLastName(String lastName)
{
    this.lastName = lastName;
}

public int getPhoneNumber()
{
    return phoneNumber;
}

public void setPhoneNumber(int phoneNumber)
{
    this.phoneNumber = phoneNumber;
}

public Collection<CustRentMovie> getRents()
{
    return rents;
}

public void setRents(Collection<CustRentMovie> rents)
{
    this.rents = rents;
}

}

the code of the EJB:
@Stateless
public class ClerkSessionBean implements ClerkSessionRemote
{

@PersistenceContext(unitName = "vc_pu")
private EntityManager em;

public int writeCustomer(AlmostCustomer almostCustomer)
{

    Customer customer = new Customer();
    System.out.println("My id is: " + customer.getId());
    customer.setFirstName(almostCustomer.getFirstName());
    customer.setLastName(almostCustomer.getLastName());
    customer.setPhoneNumber(almostCustomer.getPhoneNumber());
    em.persist(customer);
    System.out.println("My id is: " + customer.getId());
    return customer.getId();
}
}

part of the script that creates the database:
CREATE table customer
(
cust_id NUMBER(5),
phone_number NUMBER(10) NOT NULL,
first_name VARCHAR2(12) NOT NULL,
last_name VARCHAR2(30) NOT NULL,
-- Τα χρήματα που έχει ένας πελάτης στο λογαριασμό του.
credit NUMBER(5, 2) DEFAULT 0 NOT NULL,
CONSTRAINT cust_pk PRIMARY KEY (cust_id),
-- Μόνο ένας λογαριασμός για κάθε σπίτι.
CONSTRAINT phone_unique UNIQUE (phone_number)
)
/

DROP SEQUENCE cust_id_seq
/

CREATE SEQUENCE cust_id_seq MINVALUE 10000 MAXVALUE 99999 INCREMENT BY 1 START WITH 10000 NOCACHE  NOCYCLE ORDER

/
Yiannis P.

A: I think you should change CREATE SEQUENCE cust_id_seq ... INCREMENT BY1 to ... INCREMENT BY50.  Here is why.
The declared sequence increment should match the @SequenceGenerator's allocationSize parameter. allocationSize is not specified and therefore defaults to 50.  But the true INCREMENT BY is only 1, not 50.  So there is a mismatch between allocationSize and the real INCREMENT BY.
Here's how this mismatch could cause the problem.  TopLink Essentials (TLE) calls NEXTVAL() on cust_id_seq.  The sequence returns 10000 + 1.  TLE assumes the sequence just incremented by 50 (default JPA allocationSize) instead of 1 (actual amount).  TLE subtracts allocationSize = 50 from 10001 to get 9951.
By the way, if you have the freedom to do so,  consider upgrading to TLE's successor, EclipseLink (and to Glassfish v3).

A: In the customer entity in the annotation @SequenceGenerator I added the atribute allocationSize with value 1, now the primary keys start from 10000.
@Entity
@Table(name = "customer")
@SequenceGenerator(name="seq", sequenceName="cust_id_seq", allocationSize=1)
public class Customer implements Serializable
{

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
    @Column(name="CUST_ID")
    private int id;
...
}


text:
Q: Produce MSE by using cv.glm() in multiple linear regression, how about a transformed y variable I applied 10-fold cross validation by using cv.glm() function in the linear regressions.
I am able to obtain the MSE in this way,
mse=cv.glm(data,model,K=10)$delta
However, if I applied transformation on the y variable (such as log) in my model, the generated MSE is the MSE based on log(y), right?
How can I get the MSE for the y variable in this case? I do not think simply apply exp(mse) here is a good solution


text:
Q: pandas cleaning 1+1 values in a column I have a column that has the following data
column
------
1+1
2+3
4+5

How do I get pandas to sum these values so that the out put is 2,5,9 instead of the above?
Many thanks

A: You column obviously contains strings, so, you must somehow evaluate them. Use pd.eval function. Eg
frame['column'].apply(pd.eval)

If interested in performance, probably use an alternative method, like ast.literal_eval. Thanks to user @Serge Ballesta for mentioning


text:
Q: Spectrum of cycle graph with edges replaced by triangles I'm interested in the following question. Start with a cycle $C_n$. Now, add $n$ more vertices, each of them connected to a different pair of adjacent vertices in the cycle. I think this is sometimes called the semitotal graph of the cycle, but I can't find the spectrum anywhere. Anyway, I want to find the eigenvalues of the adjacency matrix.
Here's what I have so far. The graph has $n$ vertices of degree 4 (the original vertices of the cycle, which I'll call the "original vertices"), and $n$ vertices of degree 2 (the vertices added, which I'll call the "points"). Let's look first for eigenfunctions which are constant on the original vertices and on the points. Let's assume the constants are nonzero, so normalize so that on the points it's equal to 1, and on the original vertices say it's equal to $b$. When we hit it with the adjacency matrix, we get the equations
$$
2b+2 = \lambda b  \qquad 2b = \lambda
$$
by examining the original vertices and the points separately. This leads to $b^2 - b -1 = 0$, from which $b = \frac{1 \pm \sqrt{5}}{2}$ and $\lambda = 1 \pm \sqrt{5}$. OK, so that's 2 eigenvalues out of the way, $2n-2$ more to go, and I believe $1 + \sqrt{5}$ would be the P-F one. Now I get a bit stumped. If $n$ is even, then we could put 0's at all the points, then alternate $1$'s and $-1$'s around the cycle, and this would lead to an eigenvalue of $-2$, and similarly we can alternate $1$'s and $-1$'s around the points and put zeroes at the original points, and this gives $0$ as an eigenvalue. However these don't work if $n$ is odd, and in any case we are still missing many eigenvalues. Any suggestions?
Greg

A: Well, you know the eigenvectors for $C_n$: take an $n^{\text{th}}$ root of unity $\omega$, and assign $\omega^i$ to the $i^{\text{th}}$ vertex around the cycle.
We can try extending each of these to an eigenvector of your graph. If this works out, then the point between the $i^{\text{th}}$ and $(i+1)^{\text{th}}$ original vertex must be assigned the value $\lambda^{-1}(\omega^i + \omega^{i+1})$, where $\lambda$ is the eigenvalue. If this happens, the $i^{\text{th}}$ original vertex goes from $\omega^i$ to
$$
   \omega^{i-1} + \omega^{i+1} + \lambda^{-1}(\omega^{i-1} + \omega^i) + \lambda^{-1}(\omega^i + \omega^{i+1})
$$
and we would like this to be equal to $\lambda \omega^i$. Simplifying, we get
$$
   \omega^{-1} + \omega + \lambda^{-1}(\omega^{-1} + 2 + \omega) = \lambda
$$
which is a quadratic equation in $\lambda$. So for each $n^{\text{th}}$ root of unity, we get two extensions of the corresponding eigenvector of $C_n$. (An exception is when $\omega = -1$, when we get a linear equation. But you've already found the missing eigenvector in that case: it's the one with all the original vertices set to $0$.)
In fact, this is the same idea you started with, except you only applied it in the case $\omega = 1$.


text:
Q: How would I go about fixing SyntaxError: Unexpected token, as it suddenly pops up? I was typing a Discord bot, and then right as I executed the command, I got SyntaxError: Unexpected token ')' I want to know, where exactly did I go wrong? This is my code
v

const client = new Discord.Client();

const prefix = '-d'

client.once('ready', () => {
    console.log('DaveBot is online!');
});

client.on('message', message =>{
    if(!message.content.startsWith(-d) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('pong!');
    }
});

client.login('bot token, censored so it doesn't get taken');```

A: I think this:
if(!message.content.startsWith(-d) || message.author.bot) return;

should be this:
if(!message.content.startsWith(prefix) || message.author.bot) return;

The issue is that -d is interpreted as the negative of d which is undefined, you probably meant either prefix or "-d" in quotes.


text:
Q: Brand new Mac, should I use Macports? got a new mac, need to have it setup ready for development. I heard great things about macports, should i use it? Is it really easier than manually download and compile? anyone has any problems using it?
It is for typical ruby web development stuff.
thanks

A: Try homebrew. It's really good because it's highly optimized, and has no redundant packages.
It's also built in Ruby, which seems particularly relevant to you.

A: It really is easier than doing it manually. For example:

sudo port install gimp

will download, build, and install Gimp, plus all its dependencies. There are a lot of dependencies.
If you're doing "typical" stuff, the versions of stuff in MacPorts will be sufficient. Only if you need to be on the bleeding edge will you need to bypass MacPorts and download and install manually.

A: While macports can make installation easier, it's the difference between 4 commands (wget/tar/configure/make) and 1 command. Where macports really shines is in package management. If you're primarily interested in Ruby development, RubyGems might be all you need. If you're doing Ruby on Rails, macports will be quite helpful with all the non-ruby software you'll need. If you want to go completely GUI, you can use Porticus as a macports frontend.
I have had the occasional problem during the build phase, but that's under Tiger, which is behind the times.

A: I prefer macports, but some people like doing it themselves. Macports tends to be behind releases, but it's still good for me

A: The strongest problem with macports is that it's not cross platform, and it's hard to specify a well defined development scenario (e.g. you use Foo version 1.2.3, Bar version 0.5.6 etc.). It makes your life easier, but as of today, I still haven't found a decent solution to the definition and building of a development runtime environment which is efficient, easy and cross platform. See also this question.
So my suggestion is: go with macports, unless you want very strict control of your development environment.

A: You should use a package manager unless you have a well defined, specific reason not to.
'Course, I prefer fink.


text:
Q: aspose email throwing The operation 'FetchMessage' terminated. Timeout '100000' has been reached I am developing RPA for email automation . I am using email service aspose.
I am getting Timeout exception intermittently.Although there is a setTimeout() api which can be use to wait till passed time.
My understanding is that due to increased number of messages in mail box it is taking longer time to gather/populated mail message.
Is there anyway to use pagination concept so that I can fetch limited number of mail messages at one shot?

A: POP3 is old protocol and It does NOT actively develops now. It's better to use IMAP instead of it. POP3 does not allow to implement retrieving of brief information about mail messages as group operation. That's why when we retrieve list of message info, we have to do to the server the same number of requests like number of messages in list. That's leads to long time of operation. To avoid of it we implemented ability to load messages info later by request. More detailed information can be loaded with LoadMessageInfoList method. Please see code snippet below.
Pop3Client client = createPop3Client();
try {
    Pop3MessageInfoCollection messageInfoCol = client.listMessages(Pop3ListFields.SequenceNumber);
    int pageSize = 20;
    List<List<Pop3MessageInfo>> pages = new ArrayList<List<Pop3MessageInfo>>();
    List<Pop3MessageInfo> page = new ArrayList<Pop3MessageInfo>();
    for (int i = 0; i < messageInfoCol.size(); i++)
    {
        Pop3MessageInfo messageInfo = messageInfoCol.get_Item(i);
        if (page.size() < pageSize)
        {
            page.add(messageInfo);
            continue;
        }
        else
        {
            client.loadMessageInfoList(page);
            pages.add(page);
            page.clear();
            page.add(messageInfo);
        }
    }
    if (page.size() > 0)
    {
        client.loadMessageInfoList(page);
        pages.add(page);
    }
} finally {
    client.dispose();
}

The following is IMAP based code:
    ImapClient client = new ImapClient("exchange.domain.com", "username", "password");

    int itemsPerPage = 500;

    client.selectFolder(ImapFolderInfo.IN_BOX);

    List<ImapPageInfo> pages = new ArrayList<ImapPageInfo>();

    ImapPageInfo pageInfo = client.listMessagesByPage(itemsPerPage);

    System.out.println("Pages: " + pageInfo.getTotalCount());

    pages.add(pageInfo);

    int iPageCount = 1;
    while (!pageInfo.getLastPage())
    {
        pageInfo = client.listMessagesByPage(pageInfo.getNextPage());

        pages.add(pageInfo);

        iPageCount += 1;

        System.out.println(iPageCount);
    }

    int retrievedItems = 0;
    for (ImapPageInfo folderCol : pages)
        retrievedItems += folderCol.getItems().size();
    System.out.println(retrievedItems);


text:
Q: How would I write contents from inherited list to a text file? I'm probably going about this the completely wrong way, but I'm trying to write the contents from an inherited list into a text file using a method, called Load.
public class Appointments : List<Appointment>

There are no problems here, however when I try to write each item from the list into a text file with the code:
public bool Load(string fileName)
{
    TextWriter tw = new StreamWriter("Appointment.txtr");
    foreach (string s in List<Appointment>)
    {
        tw.WriteLine(s + "\n");
    }
}

I get the error "List<Appointment>" is a type which is not valid in the given context.
Any ideas how I can fix this? Or has anyone got another way of doing what I'm trying to achieve.
Thanks for reading!

A: List<Appointments> is a type...In foreach loop,you have to use instance of class which is of type IEnumerable..In your case, Appointments which inherits List<Appointments> which in turn is of type IEnumerable. So instance of Appointments is what you should use in foreach loop. As the load method in that class itself..you can do something like this
public bool Load(string fileName)
{
    TextWriter tw = new StreamWriter("Appointment.txtr");
    foreach (Appointment a in this)
    {
       var s = a.ToString(); // code which converts appointment to string
        tw.WriteLine(s + "\n");
    }
}

A: Assuming that Load is a member of Appointments you can do this:
public bool Load(string fileName)
{
    using(TextWriter tw = new StreamWriter("Appointment.txtr"))
    {
        foreach (Appointment a in this)
        {
            tw.WriteLine(a.ToString() + "\n");
        }
    }
}

By doing the foreach over this you'll access the items in the base List class.
NOTE: You forgot to close the writer, so I've added a using block to take care of this.
On another note, calling the method Load is a bit misleading as you're actually saving the data to a file, rather than loading it. I suspect a better name would be Save.


text:
Q: read files from in Android internal storage using delphi is it possible to read file.db from internal storage in android /data/data/....
using android firemonkey app using delphi not java?, i tried opening files from internal storage but access was denied even my devise is Rooted !
any help will be appreciated. many thanks.

A: Files stored in Internal storage are private to the app that creates them. Your app cannot access another app's internal storage files unless that app explicitly grants access when it creates them. This is clearly stated in the Android documentation:
Using the Internal Storage

By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user).

When an app creates a file in internal storage (using Context.openFileOutput()), it choose whether to use MODE_PRIVATE permission:

the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).

Or whether to enable MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE permissions:

allow all other applications to have read access to the created file.

allow all other applications to have write access to the created file.

Without those permissions, your app WILL NOT HAVE ACCESS to the other app's files.  Also note that these permissions were deprecated in API level 17:

Creating world-(readable|writable) files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore.


text:
Q: Raising an event from usercontrol and notifying subscribers I have a usercontrol DmsRegisterPod which is being output within a repeater which is itself, inside an UpdatePanel. I have an event on the DmsRegisterPod called OnUpdated which I'm subscribing to in the repeaters ItemDataBound event e.g:
protected void rptPendingDmsRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DealershipIRLink irLink = (DealershipIRLink)e.Item.DataItem;
        DmsRegisterPod dmsRegisterPod = (DmsRegisterPod)e.Item.FindControl("ucDmsRegisterPod");
        dmsRegisterPod.ValidationGroup = string.Format("dms-pod-{0}", e.Item.ItemIndex);
        dmsRegisterPod.DealershipIRLink = irLink;
        dmsRegisterPod.OnUpdated += dmsRegisterPod_OnUpdated;
    }
}

private void dmsRegisterPod_OnUpdated(object sender, EventArgs e)
{
    this.DataBind();
}

The event is setup as such in the usercontrol:
public event EventHandler OnUpdated;

private void Updated(EventArgs e)
{
    if (this.OnUpdated != null)
    {
        OnUpdated(this, e);
    }
}

It's being raised in the Accept click handler:
protected void btnAccept_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        this.DealershipIRLink.dms_account_number = txtDmsNumber.Text;

        this.DealershipIRLink.id_dealer_ir_link_status = DealerIRLinkStatus.DealerIRLinkStatusIdentifier.Approved;

        this._irLinkService.UpdateDealershipIRLink(this.DealershipIRLink);

        this.Updated(e);
    }
}

However, the handler, OnUpdated is always null so the event never gets raised. It's as though the control is losing the event binding somehow. Can anybody see what I've done wrong here?

A: Register the event handler in ItemCreated instead of ItemDataBound which is triggered only when you databind the control and not on every postback(required):
protected void rptPendingDmsRequests_ItemCreated(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DmsRegisterPod dmsRegisterPod = (DmsRegisterPod)e.Item.FindControl("ucDmsRegisterPod");
        dmsRegisterPod.OnUpdated += dmsRegisterPod_OnUpdated;
    }
}

All other logic that depends on the datasource belongs to ItemDataBound:
protected void rptPendingDmsRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DealershipIRLink irLink = (DealershipIRLink)e.Item.DataItem;
        DmsRegisterPod dmsRegisterPod = (DmsRegisterPod)e.Item.FindControl("ucDmsRegisterPod");
        dmsRegisterPod.ValidationGroup = string.Format("dms-pod-{0}", e.Item.ItemIndex);
        dmsRegisterPod.DealershipIRLink = irLink;
    }
}


text:
Q: How to return a reference to an array of ten strings It's an exercise of C++ Primer 5th. I don't know how to solve it?
The problem described as:
Write the declaration for a function that returns a reference to an array of ten strings, without using either a trailing return, decltype, or a type alias.
My codes:
#include <iostream>
#include <string>

std::string (&func(std::string a[])) [10]
{
    return a;
}

int main()
{
    std::string a[10];
    std::string (&b)[10] = func(a);
    for (const auto &c : b)
        std::cout << c << std::endl;
    return 0;
}

compile errors:

e6_36.cc:6:12: error: non-const lvalue reference to type 'std::string
  [10]' cannot bind to a value of unrelated type 'std::string *' (aka
  'basic_string, allocator > *')
return a;
       ^

1 error generated.

A: You can pass the array by reference, so you can return it :
std::string (&func(std::string (& a) [10])) [10]
{
    return a;
}

Or to make things clearer, use a typedef for your array of strings:
typedef std::string StrArray[10];

StrArray& func2(StrArray& a) {
   return a;
}

EDIT:
When you did :
std::string (&func(std::string a[])) [10]
{
    return a; // error !
}

The argument a is an array of std::string and decays to a pointer to std::string* , which is passed by value (so, copied): You are asking the compiler to bind a non-const reference (the return type) to a temporary, which is illegal in C++.

A: string (&func(string (&as)[10]))[10]

*

*string (&as)[10] is a reference to an array of 10 string type elements.

*func(string (&as)[10]) says we can call func whose parameter is a reference to an array of 10 string type elements.

*(&func(string (&as)[10])) says reference is return.

*(&func(string (&as)[10]))[10] says that reference yields an array of size 10.

*string (&func(string (&as)[10]))[10] says that the element type in the array is of string type.

#include <iostream>
#include <string>

std::string (&func(std::string(&as)[10]))[10]
{
    for (int i = 0; i != 10; ++i) {
        as[i] = as[i] + " number " + std::to_string(i); //append to string
    }
    return as;
}

int main()
{
    std::string array_str[10];
    // initialize array with "I am"
    for (auto &str : array_str) {
        str = "I am";
    }
    // give reference of string[10] to func
    using aStr = std::string[10];   // alias
    aStr &ref_aStr = func(array_str);
    // print to see results
    for (auto str : ref_aStr) {
        std::cout << str << std::endl;
    }
    return 0;
}


text:
Q: SQLAlchemy create trigger after its tables exist I have a trigger which deletes a row from table B when table A is updated.
I am using the following code to create the trigger via DDL:
event.listen(
        TableA.__table__,
        'after_create',
        my_trig_ddl.execute_if(dialect='mysql')
)

But, error:
sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) 1146 (42S02): Table 'sqlalchemy_example.TableB' doesn't exist

How can I solve this other than guessing which table is created last? This seems like a bad solution as upgrades or code re-factoring may change the order in which tables are created.


text:
Q: Printing drawn objects in C# I have an application that draws object on a Panel using
private void Canvas_Paint(object sender, PaintEventArgs e)

The function draws a user defined amount of rectangles that represent molds of urethane. There are also strings that label the "mold" on the Panel. The Panel is scrollable and, like I said, has a variable (and potentially large) amount of rectangles within it.
I have been asked to provide a printing function for these rectangles. I am completely new to C#, in fact I have never used it before this program. Is there a way to take what I have drawn on the Panel and print them? I have seen some methods of drawing to a PrintDocument, but it looks like I would have to redraw them inside the PrintPage function. I would like to just print what I have already drawn.

A: The image on the panel should be accessible through the .Image property.
Using a new graphics object, draw that image to the PrintDocument.
Alternatively, you could hold your own reference to the image in the form as you draw it.
However, due to the difference between printers and screens, you're probably going to want to re-render the whole thing anyway using different anti-aliasing settings, etc.


text:
Q: Launch Instance with smaller root volume storage I want to launch an instance with custom size of root volume on Amazon EC2.
At step no.4 - Add Storage, the root volume default setting came with a default snapshot and a default 10 size (GiB). Then I lowered the size into 5GiB.

But at the final step, it wouldn't allow me to launch the instance because of only 5GB root volume.

Any idea or solution that I can lower the size when launching an instance?

A: You cannot create an Amazon EBS volume that is smaller than the snapshot that you want loaded.
You could attempt to make your own AMI by launching with 10GB, attaching a 5GB volume, copying files across, turning it into an AMI, etc but frankly it isn't worth the bother.
If you are merely wishing to save money, then at 10¢ per GB per month, it would only save 50¢ per month.


text:
Q: Node.js + Mongodb: is it possible to invoke 'save' on a data returned from a database? db.users.findOne({}, function (err, user) {
  //update or add a field
  user.name = 'Phil';
  //is the next line possible?
  user.save(); //error :(
});

is there a function like 'save' so that my changes to 'user' will be save in the db?

A: You can use the save method on the collection to do that:
db.users.findOne({}, function (err, user) {
  user.name = 'Phil';
  db.users.save(user);
});

It performs a full document replacement by _id, so using an update with {$set: {name: 'Phil'}} would be more efficient in your example.

A: I don't think this is possible with the native driver.
This sort of syntax works fine if you use Mongoose as a MongoDB driver.


text:
Q: How to use Front Facing Camera on Samsung Galaxy S I've tried several answer I've found across the web, such as:
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("camera-id", 2);
mCamera.setParameters(parameters);

or
mMediaRecorder.setVideoSource(2);

But it doesn't work. I've also set permissions on the manifest file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

Am i missing out on something? I've searched StackOverflow and I know this has been asked before but there seem to be no confirmed solution on this, any kind of help would be appreciated.
Note: I'm using Galaxy S on the 2.1 platform

A: There currently isn't a standard API for front-facing cameras; you will need to rely on whatever (if any) documentation the hardware manufacturer has for using their extensions to access the front-facing camera.  This will of course only work on those specific devices.
Note writing raw strings like "camera-id" is often a good sign you have wandered into the woods outside of the official SDK. :)

A: Anyway after a few trials and error, I figured it out how to do it:
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("camera-id", 2);
parameters.setPreviewSize(640, 480); // or (800,480) this is supported front camera preview size @ Samsung Galaxy S
mCamera.setParameters(parameters);

Or, if you need to use it with MediaRecorder:
MediaRecorder mMediaRecorder = new MediaRecorder();
Camera mCamera = Camere.open();
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("camera-id", 2);
parameters.setPreviewSize(640, 480); // or (800,480)
mCamera.setParameters(parameters);
mCamera.unlock(); // unlock, to give other process to access it otherwise it can't be used later
mMediaRecorder.setCamera(mCamera);
// continue with mMediaRecorder standard routines here

If you need to have a smaller preview size, you could set/scale down your SurfaceView size instead.

A: I think this is as good a place as any to add some details I've worked out.
In case you're using the front facing camera in portrait mode and the resulting file comes out cut up into squares with green blocks thrown in try inverting the width and height (both preview and recorder) and setting the encoder to H263...
This solved the problem on my Samsung Galaxy S on 2.3.3+...


text:
Q: creating variable-names through loop and adding extension I'm new to Stack Overflow. I searched for tips on my problem but unfortunately i could not find the solution i was looking for. I think it is not a very hard problem but i don't see the syntax error and it's driving me crazy. so the code:
MP = []
MP_ext = 2019
MP_num = 3

for x in range(0:MP_num):
  MP[x] = MP.append('MP%s_%s' %MP_ext %x)

print(MP)

alternatively i tried this:
for x in range(0:MP_num):
  MP[x] = MP.append('MP' + str(MP_ext) + '_' + str(x))

print(MP)

What i try to get is the vector MP like this:
[
  MP2019_1,
  MP2019_2,
  MP2019_3
]

Thanks in advance for any advices

A: Welcome to Stack Overflow! I hope this helps:
MP = []
MP_ext = 2019
MP_num = 3

# range takes a single argument: an integer
# (it has optional arguments, see: https://www.w3schools.com/python/ref_func_range.asp)
# it will return a range of values like this: range(3) = [0,1,2]
for x in range(MP_num):
  # string formatting using f-strings (Python 3.6+)
  # list.append is in-place - list is mutable, don't need to reassign it
  MP.append(f'MP{MP_ext}_{x+1}')

print(MP)


text:
Q: Image processing: Calculate the area of the region of interest I am trying to compute the area of a particular region of interest from images which are obtained from an experiment. The original data looks like this:
I have to calculate the area of the region which has a darker shade compared to the rest of the image. Then using the scale bar, I have to convert the measurement into real life values. I have trimmed and binarized the images to obtain the portion of the image where I want to calculate the area.
After trimming and binarization, the image looks like this:

To get to this black and white image, I found the threshold of the image and then binarized the image such that all the pixel values < threshold value are replaced by 0 and all above threshold value are replaced by 1.
However, I cannot calculate the area of the black portion and then use the scale bar to compute the results.
Any suggestions ?

A: You only need one more line for evaluation of the coverage of the colors:
coverage = DominantColors[yourImageBlackWhite, 2, "Coverage"]
{0.762952, 0.213876}

-
Edit: To answer your comment (posted as an answer), I want to add this:
You can show the number of covered pixels as well as the coverage. Using the command:
DominantColors[yourImageBlackWhite, 2, {"Color", "Count", "Coverage"}]

you obtain:

A: For an alternative approach to counting the number of black pixels in the binarised image you could try getting the image data and counting how many zeroes it has:
Count[Flatten@ImageData@yourBinaryImage,0]


text:
Q: Finitely Generated General Linear Group Is there a $F$ over which $GL_n(F)$, the general linear group, is finitely generated?
Obviously one generator won't work, since $GL_n(F)$ is never abelian for any field. This is possibly a silly question, which I can't really trace to any single source (just sort of came to me one day). By the way, $n$ neither has to be a fixed number nor arbitrary, so interpret the question as you wish (just so long as your interpretation doesn't render the question trivial).
EDIT:
As Morgan Rodgers points out, the question becomes relatively trivial by taking $F$ to be finite. So, perhaps I should stipulate that $F$ is infinite. What's the answer in that case?

A: If $\text{GL}_m(F)$ is finitely generated, then $F^*$ is finitely
generated (take determinants of a finite set of generators).
Note that any subgroup of a finitely generated Abelian group is
finitely generated.
If $F$
has characteristic zero, $F^*$ contains a copy of $\Bbb Q^*$
which is not finitely generated.
If $F$ has characteristic $p$, and infinite, then either it is (i)
algebraic over $\Bbb F_p$ or (ii) transcendental. In (i) the group $F^*$
is torsion, so cannot be finitely generated (lest it be finite). In (ii)
$F^*$ contains a copy of the $\Bbb F_p(X)^*$ which is not finitely generated.

A: Here is a proof that $GL_m(K)$ is not finitely generated, for any infinite field $K$ and $m\ge 2$, also applying, unlike the determinant one, to $PGL_m(K)$ and $SL_m(K)$.
Lemma 1: $A\subset B$ be subrings. If $A\neq B$ then all the inclusions $SL_m(A)\subset SL_m(B)$, $PGL_m(A)\subset PGL_m(B)$, $GL_m(A)\subset GL_m(B)$ are proper.
Proof: take the elementary matrix $e_{12}(b)$ for any $b\in B-A$. Then it does not belong to $GL_2(A)$ (and does not represent an element of $PGL_2(A)$).
Corollary 2: if $B$ is a commutative ring and is not finitely generated, and $m\ge 2$ then each of $GL_m(B)$, $PGL_m(B)$, $SL_m(B)$ is not finitely generated.
Proof: write $G$ for $GL_m$, $PGL_m$ or $SL_m$. Then $G(B)$ is the filtering union of $G(A)$ for $A$ ranging over finitely generated subrings of $B$, and the inclusion of $G(A)$ in $G(B)$ is proper for each such $A$, by the lemma. Whence the conclusion.
Lemma 3: a field which is a finitely generated ring is finite.
This is classical.
Corollary 4: for any infinite field $K$ and $m\ge 2$, none of $GL_m(K)$, $PGL_m(K)$, $SL_m(K)$ is finitely generated.
For $SL_m$ and $PGL_m$ of course we need $m\ge 2$ since for $m=1$ this is the trivial group. On the other hand $GL_1(K)=K^*$ is also not finitely generated, by the answer by "Lord Shark...".


text:
Q: Validation on dynamically generated fields I am working on the dynamically generated fields and validation on it in AngularJs but for some reason it's not working.
I am new with angular, can some one please help me to make it work?
Here is a link to the JsFiddle
HTML part is below.

            Max length: 10
             Allowed: Only Numbers

            Max length: 4
             Allowed: Only Numbers

           Add another contact

JavaScript part
(function (angular) {
    'use strict';

   angular.module('app').controller(
   'specialConditionsController', [
      '$scope', '$log', '$window', '$http', 'SweetAlert',
  function (
    $scope, $log, $window, $http, SweetAlert
) {
  var counterAuthorisedPerson = 0;
  var maxContactCountAllowed = 3;

  $scope.tetboxContactInformationAuthorisedPersonFullName = [
    {
        authorisedPersonFullName: 'AuthorizedPersonproviderFullName_' + counterAuthorisedPerson,
        providerFullName: '',
        authorisedPersonPhone: 'AuthorizedPersonContactPhone_' + counterAuthorisedPerson,
        providerPhoneNumber: '',
        authorisedPersonPhoneExt: 'AuthorizedPersonContactPhoneExt_' + counterAuthorisedPerson,
        providerPhoneExtension: ''
    }
  ];

  $scope.addAnotherContactforAuthorisedPerson = function () {
    if (counterAuthorisedPerson == maxContactCountAllowed) {
      alert("Upto Four contacts are allowed");
      return;
    } else {
      counterAuthorisedPerson++;
      $scope.tetboxContactInformationAuthorisedPersonFullName.push({
        authorisedPersonFullName: 'AuthorizedPersonproviderFullName_' + counterAuthorisedPerson,
        providerFullName: '',
        authorisedPersonPhone: 'AuthorizedPersonContactPhone_' + counterAuthorisedPerson,
        providerPhoneNumber: '',
        authorisedPersonPhoneExt: 'AuthorizedPersonContactPhoneExt_' + counterAuthorisedPerson,
        providerPhoneExtension: ''
      });
      return false;
    }
  }
   }
 ])
})(angular);


text:
Q: Can't install Rasa on Ubuntu 18.04 + Python 3.7.5? I have succeed to install Rasa NLU on my Win 10 with python 3.7 but couldn't do this on Ubuntu 18.04.
Please help.
Here is the error I get:
pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple

Could not find a version that satisfies the requirement
  tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x) (from versions:
  1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1) No matching distribution found for tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x)

Please advise what is the difference to my Win10 machine?
Please advise how can I install it.

A: I had followed these following steps and it's working fine for me for ubuntu 18.04 + Python3
Firstly create directory name of your choice and get inside of it
mkdir rasaprojects #directory name of your choice in place of rasaprojects

cd rasaprojects   #get inside that directory

Now create virtual environment of python3
virtualenv rasaenv -p python3 #write your environment name instead of rasaenv

Now activate the environment
source rasaenv/bin/activate

Now you are good to go with rasa installation
pip3 install rasa

A: Updating your pip version should solve the issue. I believe TensorFlow and your current pip version don't go well together.
Do this:

*

*Download pip installer python script from here.

*Run it using python get-pip.py
Another thing is that TensorFlow was not supported by python3.7 untill recently. So if the first solution doesn't work you can try downgrading python to python3.6

A: Upgrade pip before instaling rasa.
pip3 install --upgrade pip


text:
Q: How IIS handle http request headers with same name If I send http request with two same header name, for example:
Accept: application/json
Accept: application/xml

Which one will be used by IIS?
I have two windows server 2008 R2, and the IIS version is 7.5. But they have different behavior. One accept "application/json", and the other accept "application/xml". So I want to know if there is configuration in IIS?


text:
Q: Covariance of Random Proportions in Multinomial Counts In Agresti's Categorical Data Analysis Second Edition, at Section 14.1.4, there is a proof of the Asymptotic Normality of Functions of Multinomial Counts. It is stated that for a vector of responses $Y_i = ( Y_ {i1},...Y_{iN})$ where $Y_{ij} = 1 $ when a response falls in the jth cell and $Y_{ij} = 0 $ otherwise, then $E(Y_{ij}) = \pi_j$ and $cov(Y_i)= \Sigma$ $\thinspace$ $i= 1,...,n.$
The covariance matrix for entries where $j \neq k$ has a form in vector notation:
$\Sigma = diag(\pi) - \pi\pi{\prime}$.
If P is a sample mean of n independent observations i.e. $P = \sum_{i=1}^n Y_{ij} /n$ then it is stated that $cov(p) =  [diag(\pi) - \pi\pi{\prime}]/n$. My attempt to replicate the analysis is as follows:
$cov(p)$:
$\sigma_{jj} = \pi_j (1- \pi_j)/ n $ .
$\sigma_{jk} = cov({\sum_{i=1}^n Y_{ij}/n}, {\sum_{i=1}^n Y_{ik}/n})$ $\thinspace$ $j \neq k$
The last expression breaks down as follows:
$1/n^2 \sum_{i=1}^n \sum_{i=1}^n cov(Y_{ij}, Y_{ik})=
1/n^2 \sum_{i=1}^n \sum_{i=1}^n (-\pi_{j} \pi_{k})=
(n^2/n^2)(-\pi_{j} \pi_{k})$.
In the text, this should have been $(-\pi_{ij} \pi_{ik})/n$. Would be glad to know what I am missing.
Editted:
Incorporating the suggestion to change the index from i to l, this is what I have:
$\sigma_{jk} = cov({\sum_{i=1}^n Y_{ij}/n}, {\sum_{l=1}^n Y_{lk}/n})$ $\thinspace$ $j \neq k$
$1/n^2 \sum_{i=1}^n cov(Y_{ij}, Y_{1k}) + cov(Y_{ij}, Y_{2k})...+ cov(Y_{ij}, Y_{nk})$
$1/n^2 [cov(Y_{1j}, Y_{1k}) + cov(Y_{1j}, Y_{2k})...+ cov(Y_{1j}, Y_{nk})] +
[cov(Y_{2j}, Y_{1k}) + cov(Y_{2j}, Y_{2k})...+ cov(Y_{2j}, Y_{nk})] +...+
[cov(Y_{nj}, Y_{1k}) + cov(Y_{nj}, Y_{2k})...+ cov(Y_{nj}, Y_{nk})]
$.
So equating covariances where $i \neq l$ to zero, I will have:
$1/n^2 [(-\pi_{j} \pi_{k}) + 0...+ 0)] +
[0 + (-\pi_{j} \pi_{k}))...+ 0)] +...+
[0 + 0...+ (-\pi_{j} \pi_{k}))] = (1/n^2) n (-\pi_{j} \pi_{k})= (1/n) (-\pi_{j} \pi_{k})
$
Is this reasoning correct?

A: You cannot write nested summations as $\sum_{i=1}^n \sum_{i=1}^n f(i)$  since it is then unclear which summation index the $i$ in the expression $f(i)$ refers to. To avoid this confusion, try starting from
\begin{equation}
\sigma_{jk} = \operatorname{Cov}\left(\sum_{i=1}^n Y_{ij}, \sum_{l=1}^n Y_{lk}\right),j\neq k
\end{equation}
(there is nothing wrong with using $i$ in two different sum as in the corresponding expression in the question, except this formulation may make it easier to not get confused in the next step). There is also a typo(?) in the question in that you should have $j\neq k$ rather than $i \neq j$.


text:
Q: ORA-01843: not a valid month -- working on DB but not when doing the same on asp.net web pages I'm trying to insert a record into the DB via asp.net C# web page using 'add button'. The date format on my DB is 'dd/MON/yyyy'. the isert statement works fine on my DB but it doesnt in asp.net.
On my DB:: WORKS FINE!
INSERT INTO EVENT (RES_ID,EMP_ID,PHONE_NUMBER,EVENT_DT,TIME_SLOT)
values (null,100,'123-123-1233','01/Oct/2012','08:00 PM - 12:00 AM');

Om myaspx.cs page:: THROWS THE ERROR ""Error inserting record! ORA-01843: not a valid month"" on the webpage.
    string insertSQL;
    insertSQL = "insert into event (res_id,emp_id,phone_number,event_dt,time_slot) ";
    insertSQL += " values (:res_id,:emp_id,:phone_number,:event_dt,:time_slot)";

    OracleConnection con = new OracleConnection(connectionString);
    OracleCommand cmd = new OracleCommand(insertSQL, con);

    cmd.Parameters.Add(":emp_id", cboResOrEmpName.SelectedValue);
    cmd.Parameters.Add(":res_id", null);
    cmd.Parameters.Add(":phone_number", txtContactNo.Text);
    cmd.Parameters.Add(":time_slot", rblTimeSlot.Text);
    cmd.Parameters.Add(":event_dt", txtEvtDt.Text);

    // Try to open the database and execute the update.
    int added = 0;
    try
    {
        con.Open();
        added = cmd.ExecuteNonQuery();
        lblResults.Text = added.ToString() + " record added!";
    }
    catch (Exception err)
    {
        lblResults.Text += "Error inserting record! ";
        lblResults.Text += err.Message;
    }
    finally
    {
        con.Close();
    }

I used a textbox for the event date with AJAX caledar extansion. Following is its definition.
<asp:TextBox ID="txtEvtDt" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtEvtDt_CalendarExtender" runat="server"
TargetControlID="txtEvtDt" Format="dd/MMM/yyyy">
</asp:CalendarExtender>

Please help me understand the problem. Any help is greatly appreciated. Thank you!

A: Hope this will work
cmd.Parameters.Add(":event_dt", DateTime.ParseExact(txtEvtDt.Text, "dd/MMM/yyyy", CultureInfo.InvariantCulture));

A: Your SQL statement works fine on your database presumably because DD/Mon/YYYY is the default date format for whatever program you use to connect to Oracle (SQL*Plus, SQL Developer, TOAD, PL/SQL Developer, etc.)  Presumably when ASP.NET connects to the database it doesn't use the same default date format.
I'd recommend not relying on automatic conversion between dates and strings.  If you're converting between dates and strings, always be explicit about it.  Use TO_DATE(some_string, 'DD/Mon/YYYY') to convert a string to a date, and TO_CHAR(some_date, 'DD/Mon/YYYY') to convert a date to a string.
So, in your insertSQL string, I'd recommend replacing :event_dt with TO_DATE(:event_dt, 'DD/Mon/YYYY').


text:
Q: Lexicographic sorting in Java creating a strange order I am trying to sort an object array by the names that are inside of the array.
grades[].name
I am using an insertion method with lexicographic sorting using compareTo and it is sort of working so I know I am using the compareTo correctly but not all the name is being moved correctly and I am not sure if it is my understanding of the way lexicographic works or if my loop is causing the issue. I know lexicographic compares each letter by itself to determine the place. I originally thought it just gave the string a numeric value and was looking for a way to find that but I don't think that was the case. I have looked at the other questions in regards to how this sorting works but it doesn't seem to shed any light on my issue. I would like to know if my issues is the loop, my understanding of the sorting method or something else cause this output issue.
I have 3 classes. The object calling the .insert method is a reference to class that contains my actually array so that the array can remain private.
   `GradeArray gradeArr = new GradeArray();

    gradeArr.insert("Evans", 78, courseID);
    gradeArr.insert("Smith", 77, courseID);
    gradeArr.insert("Yee", 83, courseID);
    gradeArr.insert("Adams", 63, courseID);
    gradeArr.insert("Hashimoto", 91, courseID);
    gradeArr.insert("Stimson", 89, courseID);
    gradeArr.insert("Velasquez", 72, courseID);
    gradeArr.insert("Lamarque", 74, courseID);
    gradeArr.insert("Vang", 52, courseID);
    gradeArr.insert("Creswell", 88, courseID);`

this is to make the entries in the array.
Here is my sorting loop.
`  public String reportgrades() //this is grade sorted by name
    {
        String output = "Sorted by name ";
        int in, out;
        StudentGrade temp; //this is to hold the orginal variable.
        //for the first letter cycle
        for (out = 1; out < nElems; out++) {
            temp = grades[out];
            in = out;
            while (in > 0 && 0 < (grades[in - 1].name.compareTo(grades[in].name))) {
                grades[in] = grades[in - 1];
                in--;
            }
            grades[in] = temp;
        }
        for (int j = 0; j < nElems; j++) {
            output += grades[j].name + ", ";
        }
        return output;
    }`

The output this is creating is Sorted by name Evans, Smith, Adams, Hashimoto, Stimson, Velasquez, Lamarque, Vang, Creswell, Yee,
I am confused as to why Evans and Smith are before Adams. I have tried to look at the docs for the way compareTo works but I didn't seem to see anything that would give me any information on it.

A: First, add all names into list, then sort:
Collections.sort(list);

A: Your use of compareTo is fine, but you aren't comparing the right elements for insert sort.  You need to compare the element that was at out with each earlier element.  But after the first step in your loop, you are instead only comparing elements from earlier that out against each other.
You can either change the while loop to compare against temp:
while (in > 0 && 0 < (grades[in - 1].name.compareTo(temp.name))) {

or keep that while, but change the loop to swap the elements in the array rather than just shift them to the right:
    for (out = 1; out < nElems; out++) {
        in = out;
        while (in > 0 && 0 < (grades[in - 1].name.compareTo(grades[in].name))) {
            // swap grades at in-1 and in
            StudentGrade temp = grades[in];
            grades[in] = grades[in - 1];
            grades[in - 1] = temp;
            in--;
        }
    }

A: There is a problem with the algorithm when you shift the values.
You need to put grades[in-1] = temp; inside your while statement in order to the shift work.
I did not use a GradeStudent just a String but you can adapt.
The grades array was just for an example.
public static String reportgrades() //this is grade sorted by name
    {

    String[] grades = {"Evans", "Smith", "Adams", "Hashimoto",
    "Stimson", "Velasquez", "Lamarque", "Vang", "Creswell", "Yee"};
    String output = "Sorted by name ";
    int in, out;
    String temp; //this is to hold the orginal variable.
    //for the first letter cycle
    long nElems = grades.length;
    for (out = 1; out < nElems; out++) {
        in = out;
        while (in > 0 &&  0 < (grades[in - 1].compareTo(grades[in]))) {
            temp = grades[in];
            grades[in] = grades[in-1];
            grades[in-1] = temp;
            in--;
        }
    }
    for (int j = 0; j < nElems; j++) {
         output += grades[j] + ", ";
    }
    return output;
}

A: I followed vladwoguer answered and moved the grades[in-1] = temp; into my while loop. I didn't realize I wasn't actually moving the variable I wanted. I thought everything had to move everything over before I reinserted the original name.


text:
Q: SQL Server version numbers, when related to hotfixes, are they "inclusive"? I am looking at the list of version numbers from this page: Microsoft SQL Server Version List, and here's an excerpt:
9.00.3182   2005.90.3182.0  940128 FIX: You receive error 8623 when you run a complex query in SQL Server 2005  August 3, 2007
9.00.3179   2005.90.3179.0  938243 FIX: Error message when you run a full-text query against a catalog in SQL Server 2005: "The execution of a full-text query failed. The content index is corrupt."   July 30, 2007
9.00.3178   2005.90.3178.0  938086 FIX: A SQL Server Agent job fails when you run the SQL Server Agent job in the context of a proxy account in SQL Server 2005 August 22, 2007

(note, the question is not about what I should install for SQL Server 2005, it's about that list, and the hotfix version numbers)
Since all of these 3 are hotfixes, if my SQL Server reports version 9.00.3182 (the topmost, latest hotfix, of the 3 I extracted), does that imply that the previous 2 has been installed as well?
I see that a lot of later hotfixes or patches are named "Cumulative update package". Is that just a naming convention or was the earlier ones that aren't named like that individual hotfixes?
Concrete question example. With the above 3 hotfixes, and SQL Server reporting version number 9.00.3182, which of the 3 scenarios below is the most correct one:

*

*All three hotfixes have been applied.

*Hotfix 9.00.3182 has been applied, but definitely not the other 2.

*Hotfix 9.00.3182 has definitely been applied, there simply isn't enough information available to determine if the other 2 have been applied or not.

The reason I am interested in this is that I'm creating a class library for .NET for reporting what is installed on the SQL Server, since there isn't a single week where someone doesn't ask how to check for a specific .NET version, Windows version, or SQL Server version on Stack Overflow. I thought I at least, for my own part, that I should do enough research to be able to build a class library that can answer it, and thus have a definite answer to give for those questions.
But from the list on that page, given a hotfix KB940545, which SQL Server will report as 9.00.3186, my question is thus if the version number is above that, can I report that KB940545 has been installed (either specifically, or as part of later hotfixes/patches), or is it simply not possible to know this information?

A: Unless you have access to the log files for every cumulative update install, the only thing you would know is #3:

Hotfix 9.00.3182 has definitely been applied, there simply isn't enough information available to determine if the other 2 have been applied or not.

Cumulative updates are, well, cumulative. So are the builds within a CU branch. So 9.00.3182 will contain the fixes from 3179, 3178, 3165, 3122, 3068, etc. Microsoft used to release certain critical fixes individually, but now they have almost completely stopped doing that, opting for a ~60 day Cumulative Update delivery model (security fixes excepted).
The challenge comes when you pass a service pack boundary. There are cases where a fix is released in a cumulative update right before a service pack is released. The service pack code path was frozen at least 60 days earlier (since SPs go through more rigorous testing/regression etc). So, the service pack - even though released later - is missing fixes that won't be in that branch until the first cumulative update for that service pack. This is why you will often see a CU released out of band, almost immediately after a service pack is released.
Then, of course, there is the situation where multiple branches are being maintained, and multiple CUs come out for the lower service pack. There will be fixes there which weren't even known issues when the newer service pack was released.
This means that in many cases a newer build (say, 2005 SP4, 9.00.5000) is missing fixes from cumulative updates for SP3 (say, CU15, which was released several months after SP4). All of those fixes are usually also available in subsequent CUs for the later service pack, but just looking at version number alone wouldn't really tell you that unless you knew which fixes you are trying cross-reference. You'd need a database for that, not a numeric/string compare.
You're kind of playing with fire here, anyway. You're running SQL Server 2005, and not even on the most recent service pack. Unless you have gone through extended support, you are completely on your own. In fact 2008 and 2008 R2 both hit end of mainstream support in about 60 days.
My philosophy is to always be on the absolute latest service pack for any version I am running, and unless there is something prohibitive, always be on the latest CU for that service pack as well. So, rather than worry about whether the fixes for 3179 or 3178 were installed independently, I'd focus more on getting onto a more modern build (SP4 + MS12-070, putting you at 9.00.5324), or a more modern version (and one that isn't about to sunset).


text:
Q: Can't add a new schema in Kafka after deleting the old one I'm trying to use a proper schema for keys too. By default, it is created as:
{"subject":"AVROTEST-key","version":1,"id":60,"schema":"\"string\""}

But I want it like:
{"subject":"AVROTEST-key","version":1,"id":60,"schema": "{\"type\":\"record\",\"name\":\"AVROTEST\",\"fields\":[{\"name\":\"key\",\"type\":\"long\"}]}"}

Because of the compatibility issues, I tried to delete it completely and add a new one. I've deleted it using
curl -X DELETE http://XXXXXX.XXXXXX:1234/subjects/AVROTEST-key/versions/1

there are no other versions and I get a 404 error when I try to GET it after deleting, which means it's deleted successfully. But when I try to register a new schema, I get this error:

"error_code":409,"message":"Schema being registered is incompatible
with an earlier schema"

How can it be incompatible with an earlier schema, while there is no schema? What am I missing?
This is how I register a new schema:
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" --data '{"schema": "{\"type\":\"record\",\"name\":\"AVROTEST\",\"fields\":[{\"name\":XXXXXX.XXXXXXXX:1234/subjects/AVROTEST-key/versions

A: Looks like there was another schema version which I didn't know about it. A funny mistake actually, I should've deleted all the versions, instead of [1]. So entering the command
curl -X DELETE http://XXXXXX.XXXXXX:1234/subjects/AVROTEST-key/versions/

solved my problem. All the previous schemas are deleted. But notice the new schema will not be registered as version [1]. It will increase the latest schema id.


text:
Q: how to use returned seperated lists of function in python? hi i have a function which returns a list and a dictionary.
if functions renturns one thing i know how to use that.
but how i can use returned list and dict of function?
my code is :
def links(url):
    __url = str(url)  # find_dl_url()
    __page = requests.get(__url)
    __page_content = bs4.BeautifulSoup(__page.content)
    __links = __page_content.select('a[href*=".mkv"]')
    __dict = {}
    __sorted_dict = {}
    __list = []
    for links in __links:
        __dict[links.string] = links.get('href')
        __list.append(links.string)
    __list = sorted(__list)
    print(__list)
    print(__dict)
    return  __list, __dict

if function returnes just one list i could write:
list=links(url)

but how i can get both of list and dictionary?

A: You can unpack the returned variables
lst, dct = links(url)