text:
Q: How to call JQuery functions after page is loaded? I have a page that has a button. When the button is pressed an AJAX call is made and then the html from that call replaces a div container I have on the main page. I have scripts that need to be loaded on the second page. So my concern is that when the scripts from the second page are running, it gives me a " Object # has no method 'find' " error in the console. Which I know that this is an issue of the script not being able to call the JQuery functions. Does anyone know how I can call the JQuery functions after a second page is generated? Here is an example as to what my page does:
MAIN PAGE:

<button class="button" value="Click me!"></button>

PAGE.PHP:
echo '
';
echo '
Drop files here
';
echo '
';
echo '';
echo '';

And then when the scripts are executed from the second page I get the < Object # has no method 'find' > error. If I include the scripts on the main page, nothing works in the scripts. Anyone know where to point me in the right direction for all of this to work?
EDIT **
Sorry to confuse you guys. The code I put was just something that I had put together real quick. The button click code would be in the document.ready, but the other functions that are called from the second scripts are not in a document.ready. Do they need to be in a document.ready callback for them to recognize the JQuery functions?
EDIT 2 **
Thanks for clarifying that you can have more than one Document.Readys. I will be selecting the answers after the 10 minute window is up.

A: Your script tags are in the wrong order. You have to load jQuery before you use it. Also, put all code that interacts with the DOM in a $(document).ready() callback:

A: put your code inside
$(document).ready(function() {
  // your code
  $('body').on('click', '.button', function() {
     $.ajax({
        type: 'GET',
        url: 'page.php'
        data { ... },
        success: function(e){
            $('#container').html(e);
        }
    });
  });
});

document.ready means that page are loaded or create your file myscript.js, in that file wrap all your code in document.ready and
echo '';


text:
Q: How to get correct launcher icon for google-earth? How can I get correct icon for Google Earth in the launcher?
First I downloaded google-earth-stable_current_amd64.deb from
https://www.google.com/earth/download/ge/agree.html
Then I ran:
sudo dpkg -i google-earth-stable_current_amd64.deb

When I now start Google Earth from the terminal:
google-earth &

and I get this incorrect icon in the launcher:

I checked that the desktop file at
/usr/share/applications/google-earth.desktop
[Desktop Entry]
Version=1.0
Name=Google Earth
GenericName=3D planet viewer
Comment=Explore, search and discover the planet
Exec=/opt/google/earth/free/google-earth %f
Terminal=false
MultipleArgs=false
Icon=google-earth
Type=Application
Categories=Application;Network
MimeType=application/vnd.google-earth.kml+xml;application/vnd.google-earth.kmz;application/earthviewer;application/keyhole

and it looks ok. Note that the Exec value in the desktop file /opt/google/earth/free/google-earth is a correct symbolic link to the google-earth command.
Also, the icon at /usr/share/icons/hicolor/64x64/apps/google-earth.png

looks ok.
How can I display this icon in the launcher?

A: Update your file to :
Icon=/usr/share/icons/hicolor/64x64/apps/google-earth.png

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google sheets script to sort rows imported from another tab by column I am new to scripting in google sheets and I am trying to add a function in a script to sort a range by column value in ascending order.
I'm using a script that allows me to move rows from one tab to another based on payment status. All imported rows are placed in row 7, just below the header. As a result, the lines are completely messy.
I have tried so many things that I am lost. I don't know if I've tried the wrong function or if I'm placing them in the wrong place in the script.
function onEdit(e) {
  var sh = e.source.getActiveSheet();
  var rng = e.source.getActiveRange();

  if (sh.getName()=='Suivi Clients' && rng.getColumn()==21){
    if(rng.getValue()=='OUI' || rng.getValue()=='ANNULÉ'){

      var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Clients Finalisé')
      dest.insertRowBefore(7)

      var plage = sh.getRange('C' + rng.getRow() + ':G'  + rng.getRow())
      plage.copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('L' + rng.getRow() + ':N'  + rng.getRow())
      plage.copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('P' + rng.getRow())
      plage.copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('U' + rng.getRow() + ':W'  + rng.getRow())
      plage.copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)

      sh.deleteRow(rng.getRow())
    }
  }

  if (sh.getName()=='Clients Finalisé' && rng.getColumn()==21){
    if(rng.getValue()=='NON'){

      var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Suivi Clients')
      dest.insertRowBefore(7)

      var plage = sh.getRange('C' + rng.getRow() + ':G'  + rng.getRow())
      plage.copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('L' + rng.getRow() + ':N'  + rng.getRow())
      plage.copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('P' + rng.getRow())
      plage.copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('U' + rng.getRow() + ':W'  + rng.getRow())
      plage.copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)

      sh.deleteRow(rng.getRow())
    }
  }

  // other onEdit here
}

Dans l'onglet "Suivi Clients" je voudrais trier par colonne G et dans l'onglet "Clients Finalisé" je voudrais trier par colonne P.
That's one of the functions I tried:
function sort() {
       var ss = SpreadsheetApp.getActiveSpreadsheet();
       var sheet = ss.getSheetByName("Suivi Clients");
       var range = sheet.getRange("B6:W");
       range.sort(7);
    }

A: Sort a range ascending
function sort() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Suivi Clients");
  var range = sheet.getRange("B6:W" + (sheet.getLastRow()-5));
  range.sort({column:7,ascending:true});
}

function onEdit(e) {
  var sh = e.range.getSheet();
  if (sh.getName() == 'Suivi Clients' && e.range.getColumn() == 21) {
    if (e.range.getValue() == 'OUI' || e.range.getValue() == 'ANNULÉ') {
      var dest = e.source.getSheetByName('Clients Finalisé');
      dest.insertRowBefore(7)
      sh.getRange('C' + e.range.rowStart + ':G' + e.range.rowStart).copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      sh.getRange('L' + e.range.rowStart + ':N' + e.range.rowStart).copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      sh.getRange('P' + e.range.rowStart).copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      sh.getRange('U' + e.range.rowStart + ':W' + e.range.rowStart).copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      sh.deleteRow(e.range.rowStart);
    }
  }
  if (sh.getName() == 'Clients Finalisé' && e.range.getColumn() == 21 && e.value == 'NON') {
    var dest = e.source.getSheetByName('Suivi Clients')
    dest.insertRowBefore(7);
    sh.getRange('C' + e.range.rowStart + ':G' + e.range.rowStart).copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    sh.getRange('L' + e.range.rowStart + ':N' + e.range.rowStart).copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    sh.getRange('P' + e.range.rowStart).copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    sh.getRange('U' + e.range.rowStart + ':W' + e.range.rowStart).copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
    sh.deleteRow(e.range.rowStart);
  }
}

This sort sorts the values in the array and then using setValues it places the values back into the spreadsheet.  If you are using formulas in this range then it could damage the formulas. It also assumes that the values in column7 within the range are all dates.
function sort() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet0");
  var vs = sheet.getRange("B6:W" + sheet.getLastRow()).getValues();
  vs.sort((a, b) => {
    let vA = new Date(a[5]).valueOf();
    let vB = new Date(b[5]).valueOf();
    return vA - vB;
  })
  sheet.getRange("B6:W" + sheet.getLastRow()).setValues(vs);
}

A: Try
function sortSC() { // Suivi Clients
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Suivi Clients");
  var range = sheet.getRange("B6:W" + (sheet.getLastDataRow(3)));
  range.sort({column:7,ascending:true});
}

function sortCF() { // Clients Finalisé
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Clients Finalisé");
  var range = sheet.getRange("B6:W" + (sheet.getLastDataRow(3)));
  range.sort({column:16,ascending:true});
}

Object.prototype.getLastDataRow = function (col) {
  var lastRow = this.getLastRow();
  if (col == null) { col = 1 }
  var range = this.getRange(lastRow, col);
  if (range.getValue() !== "") {
    return lastRow;
  } else {
    return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
  }
};

FYI, complete script
function onEdit(e) {
  var sh = e.source.getActiveSheet();
  var rng = e.source.getActiveRange();

  if (sh.getName() == 'Suivi Clients' && rng.getColumn() == 21) {
    if (rng.getValue() == 'OUI' || rng.getValue() == 'ANNULÉ') {

      var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Clients Finalisé')
      dest.insertRowBefore(7)

      var plage = sh.getRange('C' + rng.getRow() + ':G' + rng.getRow())
      plage.copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('L' + rng.getRow() + ':N' + rng.getRow())
      plage.copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('P' + rng.getRow())
      plage.copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('U' + rng.getRow() + ':W' + rng.getRow())
      plage.copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)

      sh.deleteRow(rng.getRow())
      SpreadsheetApp.flush()
      sortCF()
    }
  }

  if (sh.getName() == 'Clients Finalisé' && rng.getColumn() == 21) {
    if (rng.getValue() == 'NON') {

      var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Suivi Clients')
      dest.insertRowBefore(7)

      var plage = sh.getRange('C' + rng.getRow() + ':G' + rng.getRow())
      plage.copyTo(dest.getRange("C7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('L' + rng.getRow() + ':N' + rng.getRow())
      plage.copyTo(dest.getRange("L7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('P' + rng.getRow())
      plage.copyTo(dest.getRange("P7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)
      var plage = sh.getRange('U' + rng.getRow() + ':W' + rng.getRow())
      plage.copyTo(dest.getRange("U7"), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false)

      sh.deleteRow(rng.getRow())
      SpreadsheetApp.flush()
      sortSC()
    }
  }

  if (sh.getName() != 'Suivi Clients') return;
  var editRange = {
    top: 6,
    left: 3,
    right: 7
  };
  var thisRow = e.range.getRow();
  if (thisRow < editRange.top || thisRow > editRange.bottom) return;
  var thisCol = e.range.getColumn();
  if (thisCol < editRange.left || thisCol > editRange.right) return;
  removeEmpty()
}

function sortSC() { // Suivi Clients
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Suivi Clients");
  var range = sheet.getRange("B6:W" + (sheet.getLastDataRow(3)));
  range.sort({ column: 7, ascending: true });
}

function sortCF() { // Clients Finalisé
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Clients Finalisé");
  var range = sheet.getRange("B6:W" + (sheet.getLastDataRow(3)));
  range.sort({ column: 16, ascending: true });
}

Object.prototype.getLastDataRow = function (col) {
  var lastRow = this.getLastRow();
  if (col == null) { col = 1 }
  var range = this.getRange(lastRow, col);
  if (range.getValue() !== "") {
    return lastRow;
  } else {
    return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
  }
};


text:
Q: Create a custom string c# I have a numeric id of integer type. I want to add that integer type value to 00000 and concatenate it with string type variable.Assume my integer variable value is 1. After adding the variable it should look like 00001. And I want to concatenate with a string like "Added" and then convert whole thing to a string variable. like this "Added00001". As another example if my integer value is 111 it should look like "Added00111" at the end. Another example integer variable = 1234. Final string should be "Added01234". How to do it...? An example of how to do it.. or Any tutorial how to do such a thing would be really great. Thanks in advance.

A: You should use the short form format specifier of the ToString method. In the example below, D5 indicates that the integer 111 should be converted to a string with padded zeros to a length of 5 digits, e.g. 00111.
int i = 111;
string s = "Added";
var s = s + i.ToString("D5");

//s = "Added00111"


text:
Q: Why does my script still try to create my directory? I am attempting to write a PHP script that organizes uploaded files into directories according to the date they were uploaded.  The script needs to detect whether or not the appropriate directories exists before it executes the upload.  First, it checks if the folder 'attachments/2014' exists.  If it doesn't, it's created.  Next, it checks if the folder 'attachments/2014/October" exists.  If it doesnt, create it.  Finally, it checks if the folder 'attachments/2014/October/29' exists.  If it doesnt, it's created.  Then the file is uploaded to the last folder.
For some reason, my script always tries to create the directory, even if it already exists.  It only works if the directory doesn't exist.  Not really sure why about the former.  This is CodeIgniter PHP.
$dtree = array(
    date('Y'),
    date('Y').'/'.date('F'),
    date('Y').'/'.date('F').'/'.date('d')
);

$this->load->library('ftp');

$this->ftp->connect();

foreach($dtree as $dir) {

    if($this->ftp->list_files('attachments/'.$dir)) === FALSE) {

        $this->ftp->mkdir('attachments/'.$dir);

    }

}

If the directory exists, I get the CI error saying "Unable to create the directory you have specified."


text:
Q: What prevents a node in an SCC graph to point to itself I'm trying to prove the following:

Let $G^{SCC}=(V^{SCC},E^{SCC})$ be an SCC graph. Then $G^{SCC}$ is acyclic.

During my proof, I stumbled upon the next confusion: Suppose I have $u \in V^{SCC}$. Then, for each pair of nodes $v_1,v_2 \in u$ there exists a path between $v_1$ and $v_2$. So, by this logic and by the definition of nodes in SCC graphs, $u$ must have an edge that points to itself, which contradicts what I'm trying to prove.
I'm really stuck on this and I can't reconcile why such thing couldn't happen. Thanks!

A: It seems that you are using $SCC$ for the condensation of $G$. During the construction of $G^{SCC}$, no vertex is given an edge that points to itself, so your problem will not arise. This is simply a matter of definition.


text:
Q: Node JS + AWS Promise Triggered Twice AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
ses = new AWS.SES();

var params = {};

return ses.sendEmail(params, function (err, data) {
    console.log('----->sending email')
}).promise().then((data) => {
    console.log('---->sending promise')
}).catch((err) => {
    console.log('----->am in error')
    console.log(err)
})

Can someone help my above code promise is triggered twice.
I should get below
----->sending email
---->sending promise
But i got
----->sending email
---->sending promise
----->sending email

A: It looks like you are providing both a callback function and using the promise approach. Effectively, this means that you have two different functions that execute when the request is done. Choose one of the following:
You can use the promise approach, with then and catch.
function send(params) {
    ses.sendEmail(params).promise().then((data) => {
        console.log('Email was sent')
    }).catch((err) => {
        console.log('There was an error')
    })
}

You can use promise with async/await. Make sure you add the async keyword to your function header. Make sure your Node runtime supports async/await or that you code is transpiled to whatever Node version you are using.
async function send(params) {
    try {
        const data = await ses.sendEmail(params).promise();
        console.log('Email was sent')
    } catch(err) {
        console.log('There was an error')
    }
}

Finally, you could use the callback approach:
function send(params) {
    ses.sendEmail(params, function(err, data) {
        if (err) {
            console.log('There was an error')
            return
        }
        console.log('Email was sent')
    })
}


text:
Q: evaluation of assignment in php I have a kind of 'basics' question about php. In the example code for fgets, it has this snippet as an example of reading through a file's contents:
while (($buffer = fgets($handle, 4096)) !== false) {
    echo $buffer;
}

How is it that the statement ($buffer = fgets($handle, 4096)) can have a value? Is it a kind of assignment+evaluation of $buffer? I mean, how does it get its value? Is there a name for this? I notice its using strict comparison, so do all assignments evaluate to a boolean true or false?
If I wanted to write a function that could be treated this way, do I have to do anything special, other than return false on certain conditions?

A: When you do an assignment in PHP, the assignment returns the value that was assigned.  This allows you to evaluate the assignment in conditionals or loops or other expressions.
var_dump ($var = 'test');

This results in 'test' being assigned to $var, and also the newly assigned value of $var being displayed.
The above code example does an assignment and a test in the same operation, a kind of programmer's shorthand that's quite common.  fgets() returns a line from an open file, or false if there isn't a line to return.  You could do
while ($buffer !== false) {
    echo $buffer;
    $buffer = fgets($handle, 4096);
}

but you would of course have to set buffer to a non-false value before entering the loop (by doing a fgets before the loop, or assigning a value that won't get displayed but isn't false such as an empty string).
Or you could simplify even further:
while ($buffer = fgets($handle, 4096) !== false) {
    echo $buffer;
}

A: Because FALSE is returned for either "no more data" or "error," the while loop will just execute until it must stop.
A more clear way of writing that would be:
$buffer = fgets($handle, 4096);
while( $buffer !== false )
{
    echo $buffer;
    $buffer = fgets($handle, 4096);
}

But that's nowhere near as clean.

A: In PHP an assignment is an expression, i.e. it returns a value. $buffer = fgets($handle, 4096) will first assign the value to $buffer and then return the assigned value.
So, basically, you could write:
$buffer = fgets($handle, 4096);
while ($buffer !== false) {
    echo $buffer;

    $buffer = fgets($handle, 4096);
}

Here you would have the assignment on a separate line. Because in that case you need to duplicate the assignment, the assignment in the loop condition is preferred.
PS: The most common example for an assignment in a while loop is probably fetching rows from mysql:
while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'] . ' ' . $row['lastname'];
}

A: In the context of a condition (eg. while or if), (x = y) is both an assignment and an expression.  It returns the value that's being assigned.
You don't need to do anything special to your functions to allow them to be used like this - it's a feature of the language.

A: It evaulates while fgets is not returning false. Assigment in brackets returns value that has been assigned. So ($buffer = fgets($handle, 4096)) is returning fgets value.

If there is no more data to read in the file pointer, then FALSE is returned.

Simple example:
$a = 'a';
$b = 'b';
echo ($a = $b);

Returns
b

A: Per the documentation, and what others have already said, it doesn't alwasy return boolean.  It only returns boolean when it's done or there's an error.
From PHP Manual:

Returns a string of up to length - 1
  bytes read from the file pointed to by
  handle.
If an error occurs, returns FALSE.

So, anyway, there's nothing special about how a method like this works, you could write your own method this way:
function increment($num) {
    if( $num < 10 ) { return ++$num; }
    return false;
}

$i=-1;
while( ($i = increment($i)) !== false ) {
    echo( $i."<br />" );
}

A: The === operator not only checks if a function returns something that might be seen as false (like 0, NULL, etc.) It really checks against the boolean false as you can read here: http://de.php.net/manual/en/language.operators.comparison.php


text:
Q: How to show two objects in one cell (tableView)? I ran into a small problem. I created a UITableView where the user can add his contacts from his addressbook. The firstName gets displayed in the first row, the lastName in the second one. I know where the problem is, because right now I actually tell him how to do that.
But how can I tell him to display both names in the same cell? I did it with the following methods but they don't work.
-(void)addObjectsFromArray:(NSArray *)otherArray
{
     NSMutableArray *myArray = [[NSMutableArray alloc] init];
     [myArray addObjectsFromArray:menuArray];
     NSLog(@"%@", myArray);
     [self.tableView reloadData];
}

The problem is that I cannot display objects from myArray because cellforRowAtIndex method does not get the value. And with that one I get the same result (firstName first Row, lastName second Row):
NSArray *objects = [[NSArray alloc] initWithObjects:firstName, lastName, nil];
NSString *cellValue = [objects objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
NSLog(@"%@", objects);

return cell;

A: Not only does your code display the first name and last name in different cells, it also does not work for rows at indexes greater than one. This is because your table data source reads from a brand-new array that you create with alloc/init on the first line, rather than reading from your model. Your little array contains only two objects, explaining the two rows.
Here is what you need to do: first, make an array of users available to your table's data source. Suppose it's called userArray. Put user data for each user into that array. Suppose each user is stored as an object of type MYUser that responds to [user firstName] and [user lastName] calls with the first and the last name of the user.
Now put this code into your table's data source:
MYUser *user = [userArray objectAtIndex:indexPath.row];
NSString *cellValue = [NSString stringWithFormat:@"%@ %@", [user firstName], [user lastName]];
cell.textLabel.text = cellValue;

EDIT : If your menuArray stores the first and the last names in separate consecutive string objects, you can still do it (though I recommend against it, because it will be confusing to people who maintain your program in the future).
First, you need to change the method that returns the number of items in the table to return menuArray.count / 2 instead of just menuArray.count. Then you can modify your code as follows:
NSString firstName = [menuArray objectAtIndex:indexPath.row/2];
NSString lastName = [menuArray objectAtIndex:indexPath.row/2 + 1];
NSString *cellValue = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
cell.textLabel.text = cellValue;

EDIT2 : Here is how you create a class that stores the first and the last name of a user. You add the @interface part to MYUser.h, and the @implementation part to MYUser.m file. You then import MYUser.h in .m files from which you reference MYUser class, and use initWithFirstName:andLastName: to initialize new instances. The sample below assumes that you use ARC:
MYUser.h file:
#import <UIKit/UIKit.h>
@interface MYUser : NSObject
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
-(id)initWithFirstName:(NSString*)first andLastName:(NSString*)last;
@end

MYUser.m file:
@implementation MYUser
@synthesize firstName, lastName;
-(id)initWithFirstName:(NSString*)first andLastName:(NSString*)last {
    self = [super init];
    if (self) {
        self.firstName = first;
        self.lastName = last;
    }
    return self;
}
@end


text:
Q: Continuity of trigonometric function I'm puzzled as to whether the following function is deemed continuous or not:
$$f(x) = \begin{cases}
0 & \text{if } x=0\\
2x\sin \frac 1x - \cos \frac1x &\text{otherwise}\\
\end{cases}$$
It oscillates a whole lot when x -> 0, and hence would setting y = 0 when x = 0 make it continuous? I also don't see how Squeeze Theorem could be applied over here...

A: Hint: A function is continious at a point $c$ if $\lim_{x\to c}=f(c)$. Because the function is otherwise well defined and has no other discontinious points, all you need to prove is that the limit is in fact 0 at 0. Try using the squeeze theorem for finding the limit.


text:
Q: Solve $\int_{-\infty}^{\infty} \text{sech}^2(x-a)\text{sech}^2(x+a)\ \mathrm{d}x$ I am wondering if anyone knows a trick on how to solve this integral $$f(a)=\int_{-\infty}^{\infty} \text{sech}^2(x-a)\text{sech}^2(x+a)dx.$$  The answer should be a function of $a$.
Basically I am trying to reproduce some results from a paper. I've tried Matlab/Wolfram/Mathematica to no avail.

A: Use the exponential definition, $\operatorname{sech}(x)=\frac{2}{e^{x}+e^{-x}}$, to rearrange the integrand.
$$\begin{aligned}\operatorname{sech}^2(x-a)\operatorname{sech}^2(x+a)&=\left(\frac{2}{e^{x-a}+e^{-(x-a)}}\right)^2\left(\frac{2}{e^{x+a}+e^{-(x+a)}}\right)^2
\\
&=\frac{16}{\left(e^{2x}+e^{-2x}+c\right)^2}
\end{aligned}$$
where $c=e^{2a}+e^{-2a}=\frac{2}{\operatorname{sech}(2a)}$. The integrand is an even function, so $f(a)=32\int_{0}^{+\infty}\frac{1}{\left(e^{2x}+e^{-2x}+c\right)^2}\ \mathrm{d}x$. Substitute $t=e^{2x}$, $\mathrm{d}x=\frac1{2t}\mathrm{d}t$.
$$\begin{aligned}f(a)&=32\int_1^{+\infty}\frac{1}{(t+1/t+c)^2}\cdot\frac{1}{2t}\ \mathrm{d}t
\\
&=16\int_1^{+\infty}\frac{t}{(t^2+ct+1)^2}\ \mathrm{d}t
\end{aligned}$$
It then suffices to use the standard integrals of $\frac{x}{(Ax^2+Bx+C)^n}$ and $\frac{1}{Ax^2+Bx+C}$. To avoid confusion (since unfortunately we've chosen the same letters), I'll only refer to the constants from the integral table in capitals.
$$\begin{aligned}f(a)&=16\left[-\frac{ct+2}{(4-c^2)(t^2+ct+1)}-\frac{c}{4-c^2}\int\frac{1}{(t^2+ct+1)}\ \mathrm{d}t\right]_1^{+\infty}
\\
&=16\left[-\frac{ct+2}{(4-c^2)(t^2+ct+1)}-\frac{c}{4-c^2}\left(\frac{1}{\sqrt{c^2-4}}\ln\left|\frac{2t+c-\sqrt{c^2-4}}{2t+c+\sqrt{c^2-4}}\right|\right)\right]_1^{+\infty}
\end{aligned}
$$
Note that $4-c^2<0$ except when $a=0$. Hence, we used the integral in the table for the case $4AC-B^2<0$.
As $t\to+\infty$, the $t^2$ in the denominator of the first term dominates, so the term tends to $0$. Likewise, the argument of the logarithm tends to $1$, so the second term tends to $0$. Hence, we just substitute $t=1$ and remember to take the negative sign since it's the integral's lower bound.
$$
\begin{aligned}
f(a)&=-16\left[-\frac{c+2}{(4-c^2)(1+c+1)}-\frac{c}{4-c^2}\left(\frac{1}{\sqrt{c^2-4}}\ln\left|\frac{2+c-\sqrt{c^2-4}}{2+c+\sqrt{c^2-4}}\right|\right)\right]
\\
&=
\frac{16}{(4-c^2)}\left(1+\frac{c}{\sqrt{c^2-4}}\ln\left(\frac{c-\sqrt{c^2-4}}{2}\right)\right)
\\
\end{aligned}$$
Note that $c>0$, which allowed us to simplify the absolute value in the logarithm.
Now, to find $f(a)$ in terms of $a$, we substitute back $c=e^{2a}+e^{-2a}$ and find
$$
\begin{aligned}
f(a)&=\frac{16}{-(e^{4a}-2+e^{-4a})}\left(1+\frac{e^{2a}+e^{-2a}}{\sqrt{(e^{4a}-2+e^{-4a})}}\ln\left(\frac{e^{2a}+e^{-2a}-\sqrt{(e^{4a}-2+e^{-4a})}}{2}\right)\right)
\\
&=\frac{-16}{(e^{2a}-e^{-2a})^2}\left(1+\frac{e^{2a}+e^{-2a}}{e^{2a}-e^{-2a}}\ln\left(\frac{e^{2a}+e^{-2a}-e^{2a}+e^{-2a}}{2}\right)\right)
\\
&=\frac{16}{(e^{2a}-e^{-2a})^2}\left(2a\frac{e^{2a}+e^{-2a}}{e^{2a}-e^{-2a}}-1\right)
\\
&=4\left(2a\frac{e^{2a}+e^{-2a}}{e^{2a}-e^{-2a}}-1\right)\left(\frac{2}{e^{2a}-e^{-2a}}\right)^2
\\
&=4\left(2a\coth(2a)-1\right)\operatorname{csch}^2(2a)
\end{aligned}$$
Where, in the second line, we have used $(e^{4a}-2+e^{-4a})=(e^{2a}-e^{-2a})^2$. Hence, the solution to the integral agrees with the one given by Wolfram Alpha.

A: Using the identity $\cosh \left( x\pm a \right)=\cosh x\cosh a\pm \sinh x\sinh a$ the  integrand can be written as:
$$
\begin{align}
  & ={{\left( \frac{1}{\cosh \left( x-a \right)}\frac{1}{\cosh \left( x+a \right)} \right)}^{2}} \\
 & =\frac{1}{{{\left( {{\cosh }^{2}}x{{\cosh }^{2}}a-{{\sinh }^{2}}x{{\sinh }^{2}}a \right)}^{2}}} \\
 & =\frac{{{\operatorname{sech}}^{4}}x\ {{\operatorname{sech}}^{4}}a}{{{\left( 1-{{\left( \tanh x\ \tanh a \right)}^{2}} \right)}^{2}}} \\
\end{align}
$$
Enforcing  $u=\tanh x\ \tanh a$ where $a\ne 0$ and the identity ${{\operatorname{sech}}^{2}}x=1-{{\tanh }^{2}}x$
$$
f\left( a \right)=2\frac{{{\operatorname{sech}}^{4}}a}{{{\tanh }^{3}}a}\int_{0}^{\tanh a}{\frac{{{\tanh }^{2}}a-{{u}^{2}}\ }{{{\left( 1-{{u}^{2}} \right)}^{2}}}du}
$$
For the last integral(##)
$$\begin{align}
  & ={{\tanh }^{2}}a\ \int{\frac{\ du}{\left( 1-{{u}^{2}} \right)}}+\left( {{\tanh }^{2}}a\ -1 \right)\int{\frac{{{u}^{2}}\ }{{{\left( 1-{{u}^{2}} \right)}^{2}}}du} \\
 & ={{\tanh }^{2}}a\ {{\tanh }^{-1}}u+\left( {{\tanh }^{2}}a\ -1 \right)\ \times -\frac{1}{2}\left( \frac{u}{{{u}^{2}}-1}+{{\tanh }^{-1}}u \right) \\
\end{align}$$
Finally
$$f\left( a \right)=2\frac{{{\operatorname{sech}}^{4}}a}{{{\tanh }^{3}}a}\left( \frac{1}{2}\left( a\left( {{\tanh }^{2}}a+1 \right)-\tanh a \right) \right)$$.
(##)
I have used the following integration rules:
$$\begin{align}
  & \int{\frac{\ du}{\left( 1-{{u}^{2}} \right)}}={{\tanh }^{-1}}u+C \\
 & \int{\frac{{{u}^{2}}\ }{{{\left( 1-{{u}^{2}} \right)}^{2}}}du}=-\frac{1}{2}\left( \frac{u}{{{u}^{2}}-1}+{{\tanh }^{-1}}u \right)+C \\
\end{align}$$
Notice that the second one is easily verified using integration by parts.


text:
Q: JDBC error but no error when I run my query in MySQL workbench I am running a query on a MySQL database, I am using JDBC and I am using MySQL workbench to run the query.
When I run it in MySQL work bench I get what I was expecting but when I run it in my code I get.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT Character.CharacterID, Character.CharacterName, Characte' at line 1
Here is the Java:
for (int i = 0; i < 3; i++) {
    try {
        result = s.executeQuery("USE `arbitrary-hero`; SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), "
                + "SUM(ItemStrength), SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON `Character`.CharacterID = Character_Items.CharacterID INNER JOIN "
                + "Items ON Character_Items.ItemID = Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "+ name[i] +" GROUP BY `Character`.CharacterName;;");
       }
       catch(Exception e) {
           System.out.println(e);
       }
    }
    s.close();

Here is the SQL:
SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), SUM(ItemStrength),
SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON
`Character`.CharacterID = Character_Items.CharacterID INNER JOIN Items ON
Character_Items.ItemID= Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "Maxinfet" GROUP BY `Character`.CharacterName;

A: Not sure, but I think you can't use two SQL commands together, so everything after the semi-colon is an error.


text:
Q: I want to use GRUB as my MBR instead of Windows MBR....HOW? I hear that this can b done I just don't know how. Im stil all too new to LINUX

A: Assuming you want to use GRUB as default bootloader, you can achieve this by reinstalling GRUB.
You can use the GParted tool (available in ubuntu install media) to identify disks and partitions.
If ubuntu is installed in EFI mode, boot from ubuntu install media, open a terminal and execute:
(Maybe you have to change the boot order in BIOS / UEFI setup menu afterwards nevertheless.)
sudo mount /dev/sd*** /mnt
sudo mount /dev/sd** /mnt/boot/efi
for i in /dev /dev/pts /proc /sys /run; do sudo mount -B $i /mnt$i;
done
sudo chroot /mnt
grub-install /dev/sd*
update-grub

Note : *= disk | ** = efi partition | *** = system partition
If ubuntu is installed in MBR mode, boot from ubuntu install media, open a terminal and execute:
sudo mount /dev/sd** /mnt
sudo grub-install --boot-directory=/mnt/boot /dev/sd*

Note : *= disk | ** = system partition


text:
Q: Listbox dinâmica com faixa de valores O meu problema consiste em conseguir tratar de uma maneira adequada o meu listbox em que estou fazendo uma "faixa de valores" em meu sistema.
Preciso que ele não deixe por codebehind adicionar um valor que esteja contido na faixa de valores.. Ex: 0-10 foi adicionado, agora não posso deixar ele adicionar 9-20 pois o 9 é contido na faixa 0-10..
Como posso proceder? Segue em anexo as imagens do sistema e suas linhas de código.

protected void btnAdicionarGastos_Click(object sender, EventArgs e)
                {
                    if (Tratar.Int(txtGastosDe.Value) <= Tratar.Int(txtGastosAte.Value))
                    {
                        string gasto = txtGastosDe.Value + " - " + txtGastosAte.Value;
                        if (!string.IsNullOrEmpty(gasto))
                        {
                            DataTable dt = new DataTable("dxlstGastos");
                            if (lstGastos.Visible == false)
                            {
                                lstGastos.Visible = true;
                                btnRemoverGastos.Visible = true;
                            }
                            if (!string.IsNullOrEmpty(txtGastosDe.Value) && !string.IsNullOrEmpty(txtGastosAte.Value))
                            {
                                if (!lstGastos.Items.Contains(lstGastos.Items.FindByText(gasto)))
                                {
                                    dt.Columns.Add("GASTOS");
                                    foreach (ListItem item in lstGastos.Items)
                                    {
                                        DataRow dr;
                                        dr = dt.NewRow();
                                        dr["GASTOS"] = item.Value;
                                        dt.Rows.Add(dr);
                                    }
                                    DataRow row = dt.NewRow();
                                    row.BeginEdit();
                                    row["GASTOS"] = gasto;
                                    row.EndEdit();
                                    dt.Rows.InsertAt(row, 0);
                                    dt.AcceptChanges();

                                    lstGastos.DataSource = dt;
                                    lstGastos.DataTextField = "GASTOS";
                                    lstGastos.DataBind();
                                }
                            }
                        }
                        else
                        {
                            Alerta("Não insira valores em branco.");
                        }
                    }
                    else
                    {
                        Alerta("Por favor, insira valores finais maiores que os iniciais.");
                    }
                }

A: Respondi da seguinte maneira:
protected void btnAdicionarGastos_Click(object sender, EventArgs e)
        {
            if (Tratar.Int(txtGastosDe.Value) <= Tratar.Int(txtGastosAte.Value))
            {
                string gasto = txtGastosDe.Value + " - " + txtGastosAte.Value;
                if (!string.IsNullOrEmpty(gasto))
                {
                    foreach (ListItem item in lstGastos.Items)
                    {
                        string[] itm = Tratar.String(item.Value.Replace("-", ",")).Split(new char[] { ',' });
                        int valorinicial = Tratar.Int(itm[0], 0);
                        int valorfinal = Tratar.Int(itm[1], 0);
                        int gastode = Tratar.Int(txtGastosDe.Value, 0);
                        int gastoate = Tratar.Int(txtGastosAte.Value, 0);
                        if ((gastode <= valorinicial && gastoate >= valorfinal) || (gastoate >= valorinicial && gastoate <= valorfinal))
                        {
                            Alerta("Valores foram encontrados no intervalo entre as faixas");
                            return;
                        }
                        else if ((gastode >= valorinicial && gastode <= valorfinal) || (gastoate >= valorinicial && gastoate <= valorfinal))
                        {
                            Alerta("Valores foram encontrados no intervalo entre as faixas");
                            return;
                        }
                    }
                    lstGastos.Items.Add(gasto);
                }
                else
                {
                    Alerta("Não insira valores em branco.");
                }
            }
            else
            {
                Alerta("Por favor, insira valores finais maiores que os iniciais.");
            }

        }


text:
Q: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference MainActivity.java has following code:
package com.softjourn.redmineclient.activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.softjourn.redmineclient.R;
import com.softjourn.redmineclient.models.Issue;
import com.softjourn.redmineclient.models.IssuesResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

private final static String URI="https://redmineng.softjourn.if.ua/issues.json?assigned_to_id=me";
@Bind(R.id.list_issues) ListView mListIssues;
Login li;

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

    li = new Login();
    li.execute(URI);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

class Login extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {
        HttpURLConnection c = null;
        try {
            c = (HttpURLConnection) new URL(strings[0]).openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        c.setUseCaches(false);
        try {
            c.setRequestMethod("GET");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        c.setRequestProperty("Accept", "application/json");
        c.setRequestProperty("Authorization", "basic " + Base64.encodeToString("osavchak:mhgT7322".getBytes(), 0));
        try {
            c.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader((c.getInputStream())));
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        String output;
        try {
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        JsonArray ja = new JsonParser().parse(result).getAsJsonObject().getAsJsonArray("issues");
        IssuesResponse ir = new IssuesResponse(ja);

        ArrayAdapter<Issue> adapter = new ArrayAdapter<Issue>(MainActivity.this, android.R.layout.simple_list_item_1, ir.getIssues());
        mListIssues.setAdapter(adapter);
    }
}
}

I've created two model classes.
First, IssuesResponse.java:
package com.softjourn   .redmineclient.models;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class IssuesResponse {
@SerializedName("issues")
private List<Issue> issues;

public IssuesResponse(JsonArray ja) {
    if (issues == null) {

    }
    for(JsonElement je : ja) {
        Issue issue = new Issue(je);
        issues.add(issue);
    }
}

public List<Issue> getIssues() {
    return issues;
}
}

The second one, Issue.java:
package com.softjourn.redmineclient.models;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;

public class Issue {
@SerializedName("id")
private int id;

@SerializedName("description")
private String description;

public Issue(JsonElement je) {
    Issue issue = new Gson().fromJson(je,Issue.class);
    this.id = issue.id;
    this.description = issue.description;
}
}

When I run my application an error occurs:

java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
              at com.softjourn.redmineclient.models.IssuesResponse.(IssuesResponse.java:26)
              at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:125)
              at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:79)
              at android.os.AsyncTask.finish(AsyncTask.java:636)
              at android.os.AsyncTask.access$500(AsyncTask.java:177)
              at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I wait for your suggestions how it could be fixed.

A: You haven't initialised List<Issue> in the IssuesResponse class. Try
private List<Issue> issues = new ArrayList<>();


text:
Q: How to use custom font with WebView Now I want to display some unicode characters and I have used tag: something here. But it seems that WebView can not find the Arial
font because I can only see UFO-characters. Do I have to copy arial.ttf to
somewhere or how can I use this TrueType font with WebView? Thanks.

A: loadData didn't work for me either, so I used file:///android_asset in the src path.
It worked with loadDataWithBaseURL!
For this example I changed the CSS to:
@font-face {
    font-family: 'feast';
    src: url('fonts/feasfbrg.ttf');
}

body {font-family: 'feast';}

Then use the assets path as the base url:
loadDataWithBaseURL("file:///android_asset/",myhtml,"text/html","utf-8",null);

A: Apparently, you can use a custom font for WebView, as @raychung above suggested. But this won't work for 2.1 (Bug is reported here). This should work for 1.5, 1.6 and 2.2.
You can put your custom font TTF file in your /assets folder, then in your CSS file you can put in:
@font-face {
    font-family: "myIPA";
    src: url('IPA.TTF');
}
.phon, .unicode
{
    display: inline;
    font-family: 'myIPA', Verdana, sans-serif;
    font-size: 14pt;
    font-weight: 500;
    font-style:normal;
    color: black;
}

You can now reference this font style in your HTML file.

A: You can get it to work on all versions by copying the font file from your assets to your files folder on the first launch of the app, and then reference it as:
"@font-face {
 font-family: cool_font;
 src: url('file://"+ getFilesDir().getAbsolutePath()
  + "/cool_font.ttf');
}"

A: @font-face {
 font-family: 'MyCustomFont';
 src: url('/assets/fonts/MaycustomFont.ttf')
}

It works for me.
->src
->assets
   ->fonts
      ->MaycustomFont.ttf
->..
->res

A: I used below code for rtl direction with persian font, hope someone used this code or someone suggest me best way. thanks
            String myCustomStyleString="";
                    webView.loadDataWithBaseURL("", myCustomStyleString+"
"+myHtm+"
", "text/html", "utf-8", null);

A: It didn't worked for me, I have had to link the font on my web server instead of using the reference to a local file:
   @font-face {
   font-family: 'feast';
   src: url('http://yoursite.com/tutorial/css/feasfbrg.ttf');
}

body {font-family: 'feast';}

A: This works great for me on all the devices I've tested it on.
Place your font files in /src/main/assets/fonts, then use this method:
public class HTMLUtils {

    public static String getLocalFontInHTML(String html, String fontFamily, String fontFileName) {

      return "<!DOCTYPE html>\n" +
            "\n" +
            "\n" +
            "" +
            "\n" +
            "\n" +
            html +
            "\n" +
            "\n" +
            "";
     }
}

as follows
webView.loadDataWithBaseURL("file:///android_asset/", HTMLUtils.getLocalFontInHTML(item.text, Config.FONT_FAMILY, Config.REGULAR_FONT),"text/html", "UTF-8", null);

where
public static final String FONT_FAMILY = "Montserrat";

public static final String REGULAR_FONT = "fonts/Montserrat-Regular.otf";

Hope it helps someone!
If you want to keep the font size from your html code remove
 "* {font-size: 1rem !important;}"

Have in mind that 1rem is equivalent to about 14sp

A: As Felipe Martinez Carreño said you can copy from assets and it will work.
You can refer this for more details

A: The basic idea is that the web page should have access to the font file. This is why the suggested original solution works when both the HTML file and the font file are in the assets folder, and the HTML file is loaded from there.
It isn't an Android feature, it's CSS, so should work with any Android SDK.
Loading the font from the files folder should work as well, if the font file is really there and the correct path to it is given in the style. But tho approach is messier, one needs to write code to copy the file, then code to figure out the location of the file.
I am quite happy to simply have the HTML content and the font file in the assets, and loading from there.
webView.loadUrl("file:///android_asset/content.html");

A: use css
    @font-face {
     font-family: cool_font;
     src: url('cool_font.ttf');
    }


text:
Q: Problems installing Thin on windows 7 x86 I'm having problems getting thin working on my Windows 7 machine (I've already installed eventmachine v0.8.1):

>gem install thin --ignore-dependencies
  checking for main() in -lc... no
  creating Makefile
make
  'make' is not recognized as an internal or external command, operable program or batch file.

Are there not meant to be precompiled binaries available for thin?

A: Apparently, there aren't any pre-built binaries.
You will need a C compiler installed. If you installed Ruby via the RubyInstaller, that is going to be really easy, if you used the One-Click Installer, it's goint to be a PITA.
See also: problems installing thin on Windows, which contains an answer by the RubyInstaller and One-Click Installer maintainer.

A: I've worked around the lack of precompiled binaries by installing a compiler:

*

*I iInstalled MinGW to C:\MinGW (see here for installation instructions)

*I then installed MSYS to C:\msys\1.0

*I then added c:\MinGW\bin and C:\msys\1.0\bin to my %PATH%

*Finally I ran gem install thin and amazingly it all worked!

I hope this helps out some other poor Windows ruby developer! :-)

A: There actually are pre-built binaries for particular versions of Thin but you need to know which ones.  To get the latest pre-built win32 version do the following:

*

*Go to the RubyGems Thin page

*Look under the "Versions" section for a version that has "x86-mswin32" to the right of it.  (As of today versions 1.2.11, 1.2.10, etc all have win32 binaries)

*Run the following following "gem install" command with the version of Thin included with the "-v" flag:

gem install thin -v 1.2.11

Here are the results from my installation:

c:\>gem install thin -v 1.2.11
Successfully installed thin-1.2.11-x86-mswin32
1 gem installed
Installing ri documentation for thin-1.2.11-x86-mswin32...
Updating ri class cache with 3611 classes...
Installing RDoc documentation for thin-1.2.11-x86-mswin32...

A: A binary for thin is in fact available (and apparently one has been since ver 1.2.2).
However, I couldn't install thin on Windows 7 with Ruby 1.9.2 (p290) because of its dependency on EventMachine.
Running gem install thin --ignore-dependencies was what was needed to get thin itself installed.
Just wanted to add this note for some other ruby on Windows user.


text:
Q: Still unable to run all tasks in parallel with Airflow I have task that is set up as in this question.
Based on the UI it looks like the dependencies are well-defined:

I have tested individual tasks as follows: airflow test capone_dash_preproc AAAG5608078M2 2017-07-25. This works great, updating the target database entries corresponding to that user. When I try to run the full task, however, it seems like it's getting hung up. python3 dash_dag.py basically results in the following terminal output on the web server, repeated endlessly. All CPUs are quiet, so it doesn't seem like there's much calculation happening:
/usr/local/lib/python3.6/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
  .format(x=modname), ExtDeprecationWarning
[2017-07-25 16:48:23,266] [58627] {models.py:167} INFO - Filling up the DagBag from /Users/aaronpolhamus/airflow/dags
[2017-07-25 16:48:25 -0500] [58487] [INFO] Handling signal: ttou
[2017-07-25 16:49:13 -0500] [58557] [INFO] Worker exiting (pid: 58557)
[2017-07-25 16:49:44 -0500] [58487] [INFO] Handling signal: ttin
[2017-07-25 16:49:44 -0500] [58642] [INFO] Booting worker with pid: 58642
/usr/local/lib/python3.6/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
  .format(x=modname), ExtDeprecationWarning
[2017-07-25 16:49:44,607] [58642] {models.py:167} INFO - Filling up the DagBag from /Users/aaronpolhamus/airflow/dags
[2017-07-25 16:49:46 -0500] [58487] [INFO] Handling signal: ttou
[2017-07-25 16:50:21 -0500] [58568] [INFO] Worker exiting (pid: 58568)
[2017-07-25 16:50:51 -0500] [58487] [INFO] Handling signal: ttin
[2017-07-25 16:50:51 -0500] [58661] [INFO] Booting worker with pid: 58661
/usr/local/lib/python3.6/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
  .format(x=modname), ExtDeprecationWarning
[2017-07-25 16:50:52,324] [58661] {models.py:167} INFO - Filling up the DagBag from /Users/aaronpolhamus/airflow/dags
[2017-07-25 16:50:54 -0500] [58487] [INFO] Handling signal: ttou
[2017-07-25 16:51:20 -0500] [58596] [INFO] Worker exiting (pid: 58596)
[2017-07-25 16:51:50 -0500] [58487] [INFO] Handling signal: ttin
[2017-07-25 16:51:50 -0500] [58677] [INFO] Booting worker with pid: 58677
...

My confusion arises from the fact that the individual tests run just fine and populate the database. It is the entire run that hangs and fails. Anything obvious here?

A: Airflow exists of multiple components. The most important being the scheduler, webserver, and worker (in case of horizontal scaling). The scheduler always* needs to be running to have Airflow execute tasks. The webserver is only there to provide a nice UI on top of what the scheduler is doing and for the Rest API. All components use the backing database.
You are showing the output of the webserver, while I would have expected to see the output of the scheduler. From the screenshot you posted and the way you try running your DAG my assumption is that you did not start it.
So start the scheduler by issuing airflow scheduler on the command line and your DAG will probably kick off.
*backfills are an exception


text:
Q: jQuery's load() doesn't display images Good evening everyone,
I am using a JavaScript to load/override content from an HTML-File into specified divs.
You can watch a demo.
The javascript that does the load job looks like the following:
function loadScreenie(elementSelector, sourceURL) {
    $(""+elementSelector+"").load("img/screenies/"+sourceURL+"");
}

and gets invoked by a hyperlink looking like this:
mibmib

( i have also tried the same with onclick="")
This is the content of screenie2.htm
hello world

The problem is that images are not displayed. The behaviour is like this:
- you click the link and the javascript is executed.
- the text in screenie2.htm is displayed correctly in the correct div
- the image is not displayed. there also isnt any broken image symbol or an empty space.
Do you have an idea what could cause this error?
Thanks a lot in advance,
-- benny

A: Ok. Let me conclude to you what is happening here.

*

*When link is clicked, jQuery loads "img/screenies/screenie2.htm

*The image-tag  is inserted into the DOM.

So, we have an image linking to a supposed image at ./screenie2.png, where you would believe it should be linking to *./**img/screenies/**screenie2.png*.
You need to use absolute URLs in your load():ed content.

A: If you're testing with IE, the problem might be that Jquery uses innerHTML instead of creating individual dom elements with the load command.  IE can be very finicky about that.


text:
Q: Contar los input[] en javascripts Tengo el siguiente código donde creo input[] con un boton pero quiero calcular el total de input agregado para ese valor multiplicarlo en otra funcion en javascripts

   <input type="text" name="id_tecnico[]"  value=""  placeholder="Codigo" >

   <input type="button" id="more_fields" class="btn btn-primary" onclick="add_fields();" value="Otro" />

A: Puedes hacerlo asi:

  function add_fields() {
           var d = document.getElementById("content");

           d.innerHTML += "
  <input type='text' name='id_tecnico[]''  value=''  placeholder='Codigo' class='form-control'>";
           contar();
        }

        function contar (){
          var inputs = $('input[name^=id_tecnico]');
          var count = inputs.length;
          alert(count);
        }

   <input type="text" name="id_tecnico[]"  value=""  placeholder="Codigo" >

   <input type="button" id="more_fields" class="btn btn-primary" onclick="add_fields();" value="Otro" />


text:
Q: policykit1-kde notification sound does not work In kubuntu20.04 the policykit1-kde notification sound does not work. For example, in konsole, when I try service apache2 restart an authentication dialogue is prompted but without any notification sound as shown in the following screen shots:

Is there any solution or work around to make notification sound works fine?


text:
Q: Can't reach DRF permissions in testing The unsafe methods mustn't be available to students.
I try to test it but fail with AssertionError: 201 != 403, whereas post methods intended to be prohibited.
My function gets to the permissions just in one particular case, which I can't understand why(emphasized in the code)
permissions:
class IsTeacherOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        print (request.method)
        print (request.user)
        if request.method in permissions.SAFE_METHODS:
            return True
        print(request.user.staff)
        return request.user.staff == 'T'

settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    # 'rest_framework.authentication.BasicAuthentication',
    # 'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'core.permissions.IsTeacherOrReadOnly',
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_FILTER_BACKENDS': (
    'django_filters.rest_framework.DjangoFilterBackend',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json'

}

test(I am not sure what exactly will be usefull, so I'm going to write the whole function):
def test_student_API(self):
    factory = APIRequestFactory()
    User(username='student1', password='qwert1234', staff="S").save()
    student = User.objects.get(username='student1')

    Token.objects.create(user=student)

    self.student_list_api(factory, student)
    self.student_detail_api(factory, student)

def student_list_api(self, factory, student):
    class_time_list = ClassTimeViewSet.as_view({'get': 'list'})
    self._student_list_api_request(factory, student, class_time_list, 'api/v0/classtimes', 8)

def _student_list_api_request(self, factory, student, class_time_list,
                              url, resp_len):
    student_request = factory.get(url)
    response_unauthenticated = class_time_list(student_request)
    self.assertEqual(response_unauthenticated.status_code,
                     status.HTTP_401_UNAUTHORIZED)
    force_authenticate(student_request, student, token=student.auth_token)
    response = class_time_list(student_request)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(len(response.data), resp_len)

def student_detail_api(self, factory, student):
    class_time_detail = ClassTimeViewSet.as_view({'get': 'retrieve'})
    student_request = factory.get('api/v0/classtimes')
    response_unauthenticated = class_time_detail(student_request, pk=1)
    self.assertEqual(response_unauthenticated.status_code, status.HTTP_401_UNAUTHORIZED)
    force_authenticate(student_request, student, student.auth_token)

    print('--------------')
    print('Only in this case permissions is reached')
    response = class_time_detail(student_request, pk=1)
    print('---------------')

    response.render()
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(json.loads(response.content), {
        "id": 1,
        "lesson_start": "08:30:00",
        "lesson_end": "09:15:00"
    })
    class_time_detail = ClassTimeViewSet.as_view({'post':'create'})

    student_request = factory.post('api/v0/classtimes',{'lesson_start':'20:00:00','lesson_end':'20:45:00'},format='json')
    force_authenticate(student_request,student,student.auth_token)
    response = class_time_detail(student_request)
    response.render()
    self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

output:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
----
Only in this case permissions is reached
GET
student1
---

Failure
Traceback (most recent call last):
  File "D:\PyProjects\DjangoReact\classtime\tests.py", line 33, in test_student_API
    self.student_detail_api(factory, student)
  File "D:\PyProjects\DjangoReact\classtime\tests.py", line 83, in student_detail_api
    self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
AssertionError: 201 != 403

Destroying test database for alias 'default'...

A: The reason was in overriding the wrong function.
I should have overridden:
"def has_permission(self,request,view)" not the
"def has_object_permission(self,request,view,obj)


text:
Q: Azure storage account - Unable to connect to the remote server I have logged onto to Azure Portal and created a storage account and the container to hold the images. (container has the access type set to container).
Now I'm trying to upload an image using the C# code.(Works fine on uploading an image via portal and able to access the image.)
//   actName contains the storage account name and actKey contains the Access Key for that storage account.

StorageCredentials creds = new StorageCredentials(actName, actKey);
CloudStorageAccount imageStorageAccount = new CloudStorageAccount(creds, useHttps: true);

CloudBlobClient blobClient = imageStorageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference("newimages");
container.CreateIfNotExists();

It is throwing an error:

No connection could be made because the target machine actively
  refused it 51.136.40.24:443

Any input on this will be helpful.
Update 19/12/2016
It required me to change the Identity from ApplicationPoolIdentity to Custom user name and account. Is there a way to work on it without changing the ApplicationPoolIdentity?


text:
Q: Como criar um método único para tratar erros com ajax Tenho um aplicativo web que executa varias chamadas ajax. O meu professor da faculdade me desafiou a criar uma mensagem genérica e unir o tratamento de erro todo em uma única função. Alguém poderia me ajudar ?
function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    }).fail(function() {
        toastr.error('Erro ao buscar sapatos')
    });
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    }).fail(function() {
        toastr.error('Erro ao buscar casacos')
    });
}

A: Você pode utilizar os eventos globais do ajax do jQuery, por exemplo o .ajaxError(). Sempre que uma solicitação do Ajax é concluída com um erro, o jQuery dispara o evento .ajaxError() nele você pode adicionar seu tratamento, conforme o código abaixo:
$( document ).ajaxError(function() {
     //sua menssagem de erro genérica
     toastr.error('Problemas ao buscar os dados!')
});

Implementação em cima de seu código:
/*executa após todo conteudo ser carregado*/
$( document ).ready(function() {
    /*adiciona o evento global no ready da sua pagina*/
    $( document ).ajaxError(function() {
         //sua menssagem de erro genérica
         toastr.error('Problemas ao buscar os dados!');
    });
});

/*agora você pode editar suas funções retirando o evento do fail,
pois todos os erros serão tratados acima. Centralizando assim os erros*/
function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    });
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    });
}

A: Da maneira que o @Brunno fez, você estaria definindo um erro que seria padrão para todos as requisições XHR da sua página.
Uma outra maneira de fazer é declarar uma função que retorne o erro como meio de reutilização de código e, em seguida, chamá-las como parâmetro de fail.
Veja:
function ajaxError()
{
     console.log('Problemas ao buscar os dados!');
}

Em seguida basta passar o nome da função como parâmetro de fail
function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    });
    .fail(ajaxError);
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    })
    .fail(ajaxError);
}


text:
Q: Docker compose - python: can't open file 'manage.py': [Errno 2] No such file or directory I want to create with docker-compose 2 Docker containers. 1 for DB (Postgres) and 1 for web (Django). Here are my files
docker-compose.yml
version: '3.7'

services:
  api:
    build: ./portal
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./app/:/usr/src/app/
    ports:
      - 8000:8000
    env_file:
      - ./portal/.env
  db:
    image: postgres:13p.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - POSTGRES_USER=portal
      - POSTGRES_PASSWORD=portal
      - POSTGRES_DB=sterling

volumes:
  postgres_data:

Dockerfile
# pull official base image
FROM python:3.8.3-alpine

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --upgrade pip

RUN apk add --no-cache \
    build-base cairo-dev cairo cairo-tools \
    # pillow dependencies
    jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev

RUN pip install "flask==1.0.1" "CairoSVG==2.1.3"

COPY ./requirements/base.txt .

RUN \
 apk add --no-cache python3 postgresql-libs && \
 apk add --no-cache --virtual .build-deps gcc python3-dev \
 libxml2 libxml2-dev musl-dev postgresql-dev && \
 apk add libxslt-dev && \
 python3 -m pip install -r base.txt --no-cache-dir && \
 apk --purge del .build-deps

# copy project
COPY . .

when i run docker-compose up it throws me the following error:
web_1  | python: can't open file 'manage.py': [Errno 2] No such file or directory

Do you have an idea why docker-compose doesn't find my file when starting?

A: Remove volumes from docker-compose.yml and build again.
There is an issue with docker-compose on ubuntu. it can't mount the volume. And as I can see you want to mount . to /usr/src/app
and make sure you build the image again after you update the code.


text:
Q: How to find which server in the DNS 'chain' is returning NXDOMAIN For almost 48 hours now we've been experiencing sporadic DNS outages for A and CNAME records. Have mostly been tracking the issue via ping and nslookup on Windows.
Lookups for 'www' (A), 'img1' (CNAME), 'store' (A) have come back as not found (windows ping or nslookup says it just cant find the host) - andon one online DNS tester I even saw an NXDOMAIN response.
I'm pretty sure that somewhere in the DNS 'chain' there is a cached NXDOMAIN response coming back thats still getting cached after 46 hours now.
I've even seen a case where - using nslookup - i've done a lookup on a CNAME record img1.example.com 10 times within 5 seconds and had negative and positive responses from the same verizon DNS server within a second.
Like I said this has happened for 48 hours now. The 'outage' occurs only briefly for a few minutes, but has been seen from at least 4 differnet geographical locations/networks.
I thought the bad record would have cleared itself out by now, but I'm hoping that finding the offending DNS server I can at least try to contact them - or find out whose fault it is.
Answers to obvious questions

*

*DNS currently godaddy, has not been changed at all

*domain has been active with DNS on godaddys hosted DNS (ns41.domaincontrol.com) for 3 years

*Problem observed on several differnet networks, verizon DSL, comcast cable, verizon EVDO, site24x7 website

*even happening with CNAME records to amazon A3 (i.e. 100% not a webserver problem and 100% DNS problem)

*I'm not an expert, but the problem confirmed by two people that know more than i do. one thinks the most likely issue is a cached NXDOMAIN response somewhere.

Should we just wait up to 4 days before changing DNS providers?
Is there a tool of some sort to trace where the DNS is coming from and find the actual server which is caching the NXDOMAIN response - or perhaps a service to just test hundreds/thousands of DNS servers for their responses?

A: I think you may have a conceptual issue with how DNS works.
Only DNS servers performing recursive resolution cache lookups. The DNS servers that the affected users on "verizon DSL, comcast cable, verizon EVDO, site24x7 website" are using are the ones caching lookups.
The root DNS servers, .com servers, and the servers authoritative for your domain aren't caching lookups, because they're not providing recursive resolution service.
It's possible (likely, actually, from what I'm seeing in Google searches) that GoDaddy is sporadically returning NXDOMAINs for your domain, and those NXDOMAINs are being cached by recursive resolvers. (Per RFC2308, they should be cached, at most, either the TTL for the zone as specified in the SOA, or the SOA minimum-- whichever is least.)
Apparently, GoDaddy's "free" DNS service isn't too highly regarded. I don't use it, personally, so I can't comment on it.
There is no central "list" of DNS servers providing recursive resolution for you to "test against". (I have one here in my house, and I could spin a few more up on VMs if I needed to...) You need a reliable provider to be authoritative for your domain, and you just have to hope that everybody else in the world honors TTLs and acts as "good DNS citizens".

Edit:
"Recursive resolution" is the process by which the a DNS server resolves a record for which it is not authoritative. The process starts with the root DNS servers, and proceeds recursively (that is, a process that loops back on itself) through all the authoritative DNS servers for the domains specified in the query until the last DNS server is reached and the desired resource record (or a negative response) is returned.
For a three-level query, like "www.example.com", the following occurs (I am leaving out the fact that, all along the way, the ISP DNS server is checking its cache in lieu of issuing queries to remote DNS servers and putting the results it receives into its cache, to make this clearer and a bit more simplistic):

*

*Your PC issues a query to your specified DNS server (at your ISP, for example).

*The ISP DNS server verifies that it doesn't have a response in cache, and then queries one of the root DNS servers.

*The root DNS server, only being authoritative for the root, responds with a list of DNS servers authoritative for the gTLD specified in the query (.com, .net, .tv, .fu, etc). The protocol continues as such, w/ the full query always being sent to each successive DNS server throughout this process. Since it's not possible to know which DNS server will be authoritative for any given query and we want to minimize the number of round-trips, we always send the full domain in each query.

*The ISP DNS server queries one of the DNS servers returned as authoritative for the gTLD specified.

*The gTLD DNS server, being authoritative for the second-level domain (example, microsoft.com, example.com, etc) only, responds with a list of DNS servers authoritative for the second-level domain.

*The ISP DNS server queries one of the DNS servers returned as authoritative for the second-level domain.

*The DNS server authoritative for the second-level, being for the third-level domain (www.microsoft.com, ftp.example.com, etc), domain returns the record requested.

*The ISP DNS server returns the record your PC queried back to your PC.
Typically ISPs offer recursive resolution services to their Customers. The DNS servers at hosting providers that are authoritative for Customer hosted domains generally don't provide recursive service (and will return the root servers if queried for domains they aren't authoritative for).

A: You really need to address the root of the problem. This is what I would do:

*

*Perform a whois query for the domain in question.

*Write down the name servers listed for the domain.

*Perform an NS nslookup against each of the name servers listed in whois and make sure they return the same list of name servers that whois listed.

*Query each name server from step 2 for the domain in question and make sure they all return the correct info. If any of the name servers return an NXDOMAIN response then you've found the culprit.
Any name servers that are listed in whois that aren't listed when you query the name servers individually need to be removed from whois.
Conversely, any name servers returned from your NS nslookup that aren't listed in whois need to be removed as name servers.


text:
Q: Flash StageQuality.LOW causes strange jiggling, anyone know why? We have a cpu-intesive Flash app that needs to run at StageQuality.HIGH if possible due to how much better it looks. On slower machines we kick it down to StageQuality.LOW, but it causes the entire app to look horrible - the images and even sprites "jiggle".
Here's a link to a 20s movie showing the problem. It has to be seen to understand "jiggling".
http://cloud.tourbuzz.net.s3.amazonaws.com/tmp/Flash%20Low%20Quality%20Jiggling.mov
Anyone have any idea what's going on? I can understand if LQ mode doesn't anti-alias, but the actual Sprites jumping around is unacceptable. Can't tell if it's me or a bug or what.

A: The only thing I can think of is that, in low quality mode, it's turning on pixel snapping?  It shouldn't cause this kind of stutter, unless the elements that are jiggling were moving in sub-pixel increments in the normal course of your app, so that when pixel snapping gets toggled on, it's making that very subtle movement much more 'jiggly'.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Bitmap.html#pixelSnapping


text:
Q: Angular date - invalid input not being marked as invalid on form submit I have a simple form with only one date control in it. When I type an invalid date like 30-Feb-2018, the control is in invalid state and my CSS style kicks in and control is shown with red border.
My problem is that, when the user clicks save, this.appFormGroup.invalid returns false and a save operation is performed. How do I stop the save operation (I want to inform the user that the date is invalid?)
The following code demonstrates the issue that I am facing:
app.component.ts file
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  appFormGroup: FormGroup;

  constructor(public formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.appFormGroup = this.formBuilder.group({
      sampleDate: ['']
    });
  }

  onButtonClick() {
    if (this.appFormGroup.invalid) {
      alert("Invalid");
    }
    else {
      alert("Valid");
    }
  }
}

app.component.html file
<form [formGroup]="appFormGroup">

      Sample Date
      <input type="date" [id]="sampleDate" formControlName="sampleDate" min="" class="form-control-dynamic">

    <button (click)="onButtonClick()">Save</button>

</form>

app.components.css file
input[type="date"]:invalid {
    border-width : 2px;
    border-color: red;
}

A: In your form control you have not used any validation. First remove min attr from HTML and create a custom date validator  and  use that validator, when you are creating control.
To avoid error on blank don't use required and return true from custom validator if value is there and it's invalid.
sampleDate: ['', [DateValidator]] //don't use required

function DateValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (control.value !== undefined && YOUR_CUSTOM_VALIDATION_LOGIC) {
            return { 'dateInvalid': true }
        };
        return null;
    }
}

A: The thing is that your Angular form is not doing any validation on the date, hence why it's not invalid.
You will need to add a validator onto your form e.g.
sampleDate: ['', [Validators.required, customDateValidator]

You will probably need to create your own Date Validator see here
Then if your custom validator returns that the date is not valid, the form property invalid will be set to true.


text:
Q: Evaluate integral of $2\pi$ periodic function's multiplication Let f and g be $2\pi$ periodic Riemann integrable funtions.
I want to evaluate $\lim_{n \to \infty} \frac{1}{2\pi} \int_0^{2\pi}f(x)g(nx)dx$
I think that this integral express by using fourier coefficient.
How to evaluate this integral?

A: Let $g_0 = \frac{1}{2\pi}\int_{0}^{2\pi}g(x)dx$ and $f_0=\frac{1}{2\pi}\int_{0}^{2\pi}f(x)dx$. Then
\begin{align}
   \frac{1}{2\pi}\int_{0}^{2\pi}f(x)g(nx)dx
      &=\frac{1}{2\pi}\int_{0}^{2\pi}f(x)(g(nx)-g_0)dx+f_0g_0 \\
      &=\frac{1}{2\pi}\sum_{k=1}^{n}\int_{\frac{2\pi}{n}(k-1)}^{\frac{2\pi}{n}k}f(x)(g(nx)-g_0)dx+f_0g_0 \\
      &=\frac{1}{2\pi}\sum_{k=1}^{n}\int_{\frac{2\pi}{n}(k-1)}^{\frac{2\pi}{n}k}\left(f(x)-f(\frac{2\pi}{n}k)\right)(g(nx)-g_0)dx+f_0g_0
\end{align}
Because $g$ is Riemann integrable, then $g$ is uniform bounded by some constant $M$. Let $I_k$ be the interval $[\frac{2\pi}{n}(k-1),\frac{2\pi}{n}k]$ with length $|I_k|=\frac{2\pi}{n}$. Then, assuming $f$ is real,
\begin{align}
 \left|\frac{1}{2\pi}\int_{0}^{2\pi}f(x)g(nx)dx-f_0g_0\right|
   &\le \frac{1}{2\pi}\sum_{k=1}^{n}\left(\sup_{x\in I_k}f(x)-\inf_{x\in I_k}f(x)\right)2M\frac{2\pi}{n} \\
   & =\frac{M}{\pi}\sum_{k=1}^{n}\left(\sup_{x\in I_k}f(x)-\inf_{x\in I_k}f(x)\right)|I_k| \\
   & =\frac{M}{\pi}\left(\overline{S}_{\mathcal{P_n}}(f)-\underline{S}_{\mathcal{P_n}}(f)\right)
\end{align}
where $\overline{S}_{\mathcal{P}}(f)$, $\underline{S}_{\mathcal{P}}(f)$ are the upper and lower Riemann sums of $f(x)$ over the partition
$$
       \mathcal{P}=\{ 0,\frac{2\pi}{n},2\frac{2\pi}{n},3\frac{2\pi}{n},\cdots\frac{2\pi}{n}\}.
$$
Because $f$ is Riemann integrable on $[0,2\pi]$, the right side tends to $0$ as $n\rightarrow\infty$. Hence,
$$
         \lim_{n\rightarrow\infty}\frac{1}{2\pi}\int_{0}^{2\pi}f(x)g(nx)dx = f_0 g_0.
$$


text:
Q: Implementing Google search operators Google currently uses keywords such as site: or is: in searches (the second example is from Gmail). I'm trying to develop a similar system and am wondering how best to go about identifying and handling those terms. For simplicity's sake, assume an OO language is being used (Ruby, Python, Java, C#, et al).
Currently, my plan is to have a separate class for each keyword. These classes have a precedence value and three methods:

*

*isRelevant(String searchPhrase): Returns true if the search phrase matches the class's filter.

*getResults(String searchPhrase): Returns a list of results based on the search phrase.

*reviseSearch(String searchPhrase): Returns a modified version of the search phrase. This will normally be removing the match to avoid it being processed again by a lower-precedence instance, but might also add text or clear the string entirely.

The calling method will then go through these keyword filters until the search phrase is empty or there are no more filters (in the latter case it will revert to its normal search behavior).
Thus, the question: Is this the most efficient way of doing this, or is there some more appropriate method? Some of the details still need to be figured out, but is this a step in the right direction?

A: Basics
sample string:
foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end
split with regex:
/\s+(?=\w+:)/
return array:
[
  'foo:(hello world)',
  'bar:(-{bad things})',
  'email:something@email.tld',
  'another:weird characters +=2{-52!%#^',
  'final:end'
]

regex explanation:
\s+     one or more spaces
(?=     followed by (positive lookahead)
  \w+   one or more word characters
  :     literal `:' (colon character)
)

usage:
Iterate through the array, split each element at : (colon). The left side key could be used to call a function and the right side value could be passed as the function parameter. This should pretty much put you on track for whatever you want to do from here.
Example ruby usage
search.rb
# Search class
class Search

  def initialize(query)
    @query = query
  end

  def foo(input)
    "foo has #{input}"
  end

  def bar(input)
    "bar has #{input}"
  end

  def email(input)
    "email has #{input}"
  end

  def another(input)
    "another has #{input}"
  end

  def final(input)
    "final has #{input}"
  end

  def exec
    @query.split(/\s+(?=\w+:)/).each do |e|
      method, arg = e.split(/:/)
      puts send(method, arg) if respond_to? method
    end
  end

end

use search.rb
q = "foo:(hello world) bar:(-{bad things}) email:something@email.tld another:weird characters +=2{-52!%#^ final:end";
s = Search.new(q)
s.exec

output
foo has (hello world)
bar has (-{bad things})
email has something@email.tld
another has weird characters +=2{-52!%#^
final has end


text:
Q: I have a C# Multiview and everytime I click on the last menu item it gives me an error I have a C# Multiview and everytime I click on the last menu item it gives me an error and stops running in Visual Studio 2010. The error is 'ActiveViewIndex is being set to '8'.  It must be smaller than the current number of View controls '8'. For dynamically added views, make sure they are added before or in Page_PreInit event.'
CODE

<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick" Orientation="Horizontal" style="left: 0px; position: relative; top: 18px; font-family:Arial;" Height="38px" Width="800px" >
    <StaticMenuStyle HorizontalPadding="0px" VerticalPadding="0px" />
    <StaticSelectedStyle BackColor="#EAEAEA" BorderColor="#000000" />
        <Items>
            <asp:MenuItem Text="about us" Value="0" Selected="True"></asp:MenuItem>
            <asp:MenuItem Text="events" Value="1"></asp:MenuItem>
            <asp:MenuItem Text="contact us" Value="2"></asp:MenuItem>
            <asp:MenuItem Text="patio" Value="3"></asp:MenuItem>
            <asp:MenuItem Text="customers" Value="4"></asp:MenuItem>
            <asp:MenuItem Text="family" Value="5"></asp:MenuItem>
            <asp:MenuItem Text="swans" Value="6"></asp:MenuItem>
            <asp:MenuItem Text="swim" Value="7"></asp:MenuItem>
            <asp:MenuItem Text="bonus" Value="8"></asp:MenuItem>
        </Items>
    <StaticHoverStyle BackColor="Silver" />
    <StaticMenuItemStyle BorderColor="#EAEAEA" BorderStyle="Solid" BorderWidth="1px" />
</asp:Menu>

    <asp:MultiView ID="MultiView1" runat="server">
          <asp:View ID="View1" runat="server"></asp:View>
<asp:View ID="View2" runat="server"></asp:View>
<asp:View ID="View3" runat="server"></asp:View>
<asp:View ID="View4" runat="server"></asp:View>
<asp:View ID="View5" runat="server"></asp:View>
<asp:View ID="View6" runat="server"></asp:View>
<asp:View ID="View7" runat="server"></asp:View>
<asp:View ID="View8" runat="server"></asp:View>
    </asp:MultiView>

CODE BEHIND
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            MultiView1.ActiveViewIndex = 0;
     }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MultiView1.ActiveViewIndex = Int32.Parse(Menu1.SelectedValue);
    }

Any help would be super duper.

A: You have 9 menu-items and 8 views
  MultiView1.ActiveViewIndex = 8

would fail since the ActiveViewIndex is zero-based (as you correctly implemented)
you could evaluate the length of the MultiView1.Views first and then set the ActiveViewIndex
int index = Int32.Parse(Menu1.SelectedValue)

if (MultiView1.Views.Count >  index)
{
    MultiView1.ActiveViewIndex = index
}

perhaps you should check if index is not -1 and larger or equal than 0.


text:
Q: .removeClass for more than one cached selector Working on optimising some js/jQuery code by caching selectors where they're used more than once to help speed things up e.g:
var object = $("#object");
object.removeClass('class-name');

i've run into trouble chaining the cached selectors though, here's my attempt:
var object1 = $("#object1");
var object2 = $("#object2");
$(object1, object2).removeClass('class-name');

This works for the first cached element but not the second, any ideas on the correct syntax?I've searched for it but can't seem to find anything!

A: Use .add()

Create a new jQuery object with elements added to the set of matched elements.

object1.add(object2).removeClass('class-name');

A: Satpal answer is pretty straight forward but if you want an alternative(to handle more classes and not to end with a huge jquery chain) you can keep jquery objects in an array and using an iteration:

"use strict";
var arr = [];
var object1 = $("#object1");
var object2 = $("#object2");
arr.push(object1, object2)
for (var e of arr) {
  e.removeClass("class-name");
}
.class-name {
  color: red;
}

this

this

this

A: Using these two selectors together is another option that you can use:
$('#object1, #object2').removeClass('class-name');


text:
Q: Git pull is not working in my local machine I am using redhat Linux server in VMWare.
I created a repository in github. And trying to git push after cloning it to my local repository after all setup. I added and committed a file now time to push a file to remote repo.
Whenever I do git push it's showing like that, I mean I'm getting 403 error page. And showing https.github.com/reponame/repo/info/refs   (can not access the url)
Here the thing is in url info/refs added to my remote repo link that's why it's not accepting to git push. Don't know why it's added.
And here I noticed that git pull origin master working properly.

A: While I have no idea how you managed to get 'info/refs' into the url, but I know how you can fix it. You can change the origin remote url by running
`git remote set-url origin "https://github.com/<username>/<project-name>"`

Make sure to change  and  to your requirements and you should be good to go.


text:
Q: Display a sequence of images like a video? I'm experimenting with image processing algorithms on iOS. I've got an asset catalog with images test_frame1 ... test_frame100 (and the like) on which I do some processing.
Among other things I need to display the images sequentially as if they were frames of a video.
The first thing that came to my mind is sequentially change the image of a UIImage after some milliseconds delay. I'm doing this asynchronously. Here's the code:
    let imageShowQueue = dispatch_queue_create("com.grigoryptashko.ImageShowQueue",
        DISPATCH_QUEUE_SERIAL)
    let frameShowDelay = Int64(0.2 * Double(NSEC_PER_SEC)) // show images with 200 ms delay, but it doesn't actually work this way
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        var dTime = dispatch_time(DISPATCH_TIME_NOW, frameShowDelay)
        for i in 1...1000 {
            dispatch_after(dTime, self.imageShowQueue) {
                dispatch_async(dispatch_get_main_queue()) {
                    NSLog("test_frame\((i % 100) + 1)")
                    self.imgView.image = UIImage(named: "test_frame\((i % 100) + 1)")
                    self.imgView.setNeedsDisplay()
                }
            }

            dTime = dispatch_time(dTime, frameShowDelay)
        }
    }

It actually works but the FPS quickly becomes too low, like 1 FPS or even slower. Is there any other way to achieve this?
Maybe, there is some way that I don't know about. For instance, recently I've learned about Accelerate framework and Apple Metal. Ant other ideas?

A: Sounds like you want an image based animation. Here is what you would do:
In your viewDidLoad
self.<name of the UIImageView you want to animate>.animationImages = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],
                                     [UIImage imageNamed:@"Image Name"],nil];
                      /* Do this until you have all the images in the array */
self.<name of the UIImageView you want to animate>.animationDuration = 1.0f;
self.<name of the UIImageView you want to animate>.animationRepeatCount = 1;

Then you use [<name of the UIImageView you want to animate> startAnimating]; were you want the animation to start. The numbers for animationDuration and animationRepeatCount can be changed to what value you want them to be. Here is the link the the Apple Docs.
For Swift development:
<name of the UIImageView you want to animate>.animationImages = [
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!,
                                         UIImage(named: "Image Name")!
                                       ]
                          /* Do this until you have all the images in the array */
<name of the UIImageView you want to animate>.animationDuration = 1.0
<name of the UIImageView you want to animate>.animationRepeatCount = 1

A: There is a more direct way of doing this by using animatedImageNamed: on UIImage. Check this out:
UIImage *animatingImage = [UIImage animatedImageNamed:@"test_frame_" duration:1.0];
UIImageView *anImageView = [[UIImageView alloc] initWithImage:animatingImage];

A: try this, change the images in array and compile the project, in this part set de time interval
animationImageView.animationDuration = 0.5;

http://www.appcoda.com/ios-programming-animation-uiimageview/


text:
Q: Bizarre math error when doing a basic check in C For a simple program, the assignment was to create a program that accepts a ten digit phone number, and then reads it back to the user.
There were to be controls to ensure that:

*

*The first digit is not 0.

*That the number entered is ten numbers.
The error check seemed simple; I thought using a while loop to ensure that the range of the number was between 1000000000 and 9999999999 would work out, and according to independent calculations, it seems it should.
while ((MDN - valueCheck < 0) || (MDN > 9999999999)) {
  printf("Entered number is not ten digits. Please re-enter.\n");
  scanf("%d", &MDN);
}

Both MDN and valueCheck are long long type variables (so that the range can go past 2,147,483,647; IIRC long long was 64-bit), but they seem to still be listed as 32-bit integers, as entering 2147483647 comes out just fine (or any lower phone number works as well), but entering 2,147,483,648 (or anything above) causes it to be displayed as -2147483647.
Related to the above, entering a higher number, not only does the value wrap around the range of the 32-bit integer, but the phone number printed by the printf statement after the loop is always equal to the entered number minus twice the limit of a 32-bit integer.
Is there any simple way to make the program actually work in 64-bit numbers like I wanted it to? The algorithm seems solid, if I can make the math work properly.

A: Try scanf("%lld", &MDN); instead of scanf("%d", &MDN);
From man scanf:
ll (ell ell)
              Indicates that the conversion will be one of dioux or n and the
              next pointer is a pointer to a long long int (rather than int).

A: Q: Is there any simple way to make the program actually work in 64-bit numbers like I wanted it to?
A: Use int64_t and "%" SCNx64.
If you:
want 32-bit integers, use type int32_t.
want 64-bit integers, use type int64_t.
use int, the range is at least -32767 to +32767.
use long, the range is at least -2147483647 to +2147483647.
use long long, the range is at least -9223372036854775807 to +9223372036854775807.
With scanf() use the matching format specifier:
int               "%d"
long              "%ld"
long long         "%lld"
int32_t           "%" SCNx32
int64_t           "%" SCNx64

A: You could've used this:
scanf("%lld", &MDN);

but there are issues with coding and approach itself (see below)
I would advise to stick to string-regexp input-validation approach instead.
Coding issue:
scanf() in a loop is vulnerable to unprocessed-input-buffer issue, e.g if user enters a text instead of a number - scanf() will fail, stdin won't be consumed and loop will continue eternally.
See "How to clear input buffer in C?" for details. Following change should address it:
while(!scanf("%lld", &MDN)) {
    char c;
    while(c=getchar()!='\n'&& c!=EOF);
}

Approach issue:
The approach itself is vulnerable to overflow and type-trimming issues.
For example: "-9999999999999999999" will pass all MDN validations (see below).
Also there could be compiler/specific issues while comparing long long (MDN)to an integer (0 or 9999999999 instead of 0LL or 9999999999LL).
Entered number is not ten digits. Please re-enter.
-9999999999999999999
"MDN" is -9223372036854775808
"MDN > 9999999999" is false
"MDN - valueCheck < 0" is false (!) because "MDN - valueCheck" is 9223372035854775808