text:
Q: Pagination results are not shown beyond the first page The goal is to paginate my search results, but for some reason when I search and the results are more than one page, I click on the second page and nothing appears. I think the reason is because of the POST but I'm really not sure. Where I am going wrong?
<?php
include "functions.php";
error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";
$nr = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){

    $searchquery = preg_replace('#[^a-zA-Z 0-9?!]#i', '', $_POST['searchquery']);

    $sqlCommand2 = "
    (SELECT id AS id, username AS name, firstname AS admin
    FROM myMembers
    WHERE firstname LIKE '%$searchquery%' OR lastname LIKE '%$searchquery%' OR username LIKE '%$searchquery%')
    UNION (SELECT id AS id, team_name AS name, churchname AS admin
    FROM myTeams
    WHERE team_name LIKE '%$searchquery%' OR churchname LIKE '%$searchquery%' OR admin_name LIKE '%$searchquery%') ORDER BY id";

    $query = mysql_query($sqlCommand2) or die(mysql_error());
    $nr = mysql_num_rows($query);
    if($nr > 0){
        $nr = mysql_num_rows($query); // Get total of Num rows from the database query
        if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
            $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
        } else { // If the pn URL variable is not present force it to be value of page number 1
            $pn = 1;
        }
        //This is where we set how many database items to show on each page
        $itemsPerPage = 10;
        // Get the value of the last page in the pagination result set
        $lastPage = ceil($nr / $itemsPerPage);
        // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
        if ($pn < 1) { // If it is less than 1
            $pn = 1; // force if to be 1
        } else if ($pn > $lastPage) { // if it is greater than $lastpage
            $pn = $lastPage; // force it to be $lastpage's value
        }
        // This creates the numbers to click in between the next and back buttons
        $centerPages = ""; // Initialize this variable
        $sub1 = $pn - 1;
        $sub2 = $pn - 2;
        $add1 = $pn + 1;
        $add2 = $pn + 2;
        if ($pn == 1) {
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
        } else if ($pn == $lastPage) {
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
        } else if ($pn > 2 && $pn < ($lastPage - 1)) {
            $centerPages .= '  ' . $sub2 . '  ';
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
            $centerPages .= '  ' . $add2 . '  ';
        } else if ($pn > 1 && $pn < $lastPage) {
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
        }
        // This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
        $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
        // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
        // $sql2 is what we will use to fuel our while loop statement below
        $sql2 = mysql_query("
            (SELECT id AS id, username AS name, firstname AS admin
            FROM myMembers
            WHERE firstname LIKE '%$searchquery%' OR lastname LIKE '%$searchquery%' OR username LIKE '%$searchquery%')
            UNION (SELECT id AS id, team_name AS name, churchname AS admin
            FROM myTeams
            WHERE team_name LIKE '%$searchquery%' OR churchname LIKE '%$searchquery%' OR admin_name LIKE '%$searchquery%') ORDER BY id $limit");

        $paginationDisplay = ""; // Initialize the pagination output variable
        // This code runs only if the last page variable is not equal to 1, if it is only 1 page we require no paginated links to display
        if ($lastPage != "1"){
            // This shows the user what page they are on, and the total number of pages
            $paginationDisplay .= 'Page ' . $pn . ' of ' . $lastPage. '';
            // If we are not on page 1 we can place the Back button
            if ($pn != 1) {
                $previous = $pn - 1;
                $paginationDisplay .=  '    Back ';
            }
            // Lay in the clickable numbers display here between the Back and Next links
            $paginationDisplay .= '' . $centerPages . '';
            // If we are not on the very last page we can place the Next button
            if ($pn != $lastPage) {
                $nextPage = $pn + 1;
                $paginationDisplay .=  '    Next ';
            }
        }

////////////Display output/////////////////////////////////////////////////////////
    while($row = mysql_fetch_array($sql2)){
        $id = $row["id"];
        $name = $row['name'];
        $real = $row['admin'];
            $sql_if1 = mysql_query("SELECT id, username, firstname FROM myMembers");
            while($row2 = mysql_fetch_array($sql_if1)){
                $if1id = $row2['id'];
                $if1user = $row2['username'];
                $if1first = $row2['firstname'];
                $userpic1 = '
' . check_pic("members", $if1id, "50", "profile") . '
';
                if($id == $if1id && $name == $if1user){
                    $search_output .= '
' . $userpic1 . 'Username - ' . $if1user . '
First Name - '.$if1first.'

';
                }
            }
            $sql_if2 = mysql_query("SELECT id, team_name, admin_name, churchname FROM myTeams");
            while($row3 = mysql_fetch_array($sql_if2)){
                $if2id = $row3['id'];
                $if2user = $row3['team_name'];
                $if2first = $row3['admin_name'];
                $if2church = $row3['churchname'];
                $userpic2 = '
' . check_pic("teams", $if2id, "50", "team") . '
';
                if($id == $if2id && $name == $if2user){
                    $search_output .= '
' . $userpic2 . 'Team Name - ' . $if2user . '
Team Admin - '.$if2first.'

';
                }
            }
    } // close while
    } else {
    $search_output = "
0 results for $searchquery
$sqlCommand2";
    }
}
?>

A: little things first.
if(isset($_POST['searchquery']) && $_POST['searchquery'] != "") can be replaced by if(!empty($_POST['searchquery']))
you don't need the $nr = mysql_num_rows($query); inside the 'if($nr > 0)';
Are you aware that $sql_if1 and $sql_if2 have no where clause? protip, it's nice, if out of main fetch loop, with an internal method to re-conciliate rows, but that's another story...
Now, on a more conceptual level, you are probably better off querying the db once and only once. A simple option is to store the result in $_SESSION.
if (empty($_GET['pn'])) {
  ... //db query stuff
  $query = mysql_query($sqlCommand2) or die(mysql_error());
  $results = $query->to_array; // to sure if it exists, use pdo anyway ^^
  $_SESSION['usersChurchResults'] = $results;
}
else {
  $results = $_SESSION['usersChurchResults']
}

$nr = count($results);
...

then it's easy to paginate the array.
Finally, yes, it's due to the $_POST. when you click on "page 2", you get a $_GET parameter (page number), but no $_POST, as the form was not submitted. so basically, you have to end if (!empty($_POST)) block before you execute sql2, and declare the if (isset($_GET['pn'])) block outside of it, in order to be able to access $pn in your "limit" construction function.
want the full code, or it's ok like this?
EDIT: I was there, so here it is:
<?php
include "functions.php";
error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";
$nr = "";

if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}

if( ! empty($_POST['searchquery']) ) {

    $searchquery = preg_replace('#[^a-zA-Z 0-9?!]#i', '', $_POST['searchquery']);

    // TODO: use pdo, plizzz
    $_SESSION['membersTeamsSearchquery'] = $searchquery;
    $sqlCommand2 = "
    (SELECT id AS id, username AS name, firstname AS admin
    FROM myMembers
    WHERE firstname LIKE '%$searchquery%' OR lastname LIKE '%$searchquery%' OR username LIKE '%$searchquery%')
    UNION (SELECT id AS id, team_name AS name, churchname AS admin
    FROM myTeams
    WHERE team_name LIKE '%$searchquery%' OR churchname LIKE '%$searchquery%' OR admin_name LIKE '%$searchquery%') ORDER BY id";

    $query = mysql_query($sqlCommand2) or die(mysql_error());
    $nr = mysql_num_rows($query);
    if($nr > 0){
        $nr = mysql_num_rows($query); // Get total of Num rows from the database query

        //This is where we set how many database items to show on each page
        $itemsPerPage = 10;
        // Get the value of the last page in the pagination result set
        $lastPage = ceil($nr / $itemsPerPage);
        // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
        if ($pn < 1) { // If it is less than 1
            $pn = 1; // force if to be 1
        } else if ($pn > $lastPage) { // if it is greater than $lastpage
            $pn = $lastPage; // force it to be $lastpage's value
        }
        // This creates the numbers to click in between the next and back buttons
        $centerPages = ""; // Initialize this variable
        $sub1 = $pn - 1;
        $sub2 = $pn - 2;
        $add1 = $pn + 1;
        $add2 = $pn + 2;
        if ($pn == 1) {
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
        } else if ($pn == $lastPage) {
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
        } else if ($pn > 2 && $pn < ($lastPage - 1)) {
            $centerPages .= '  ' . $sub2 . '  ';
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
            $centerPages .= '  ' . $add2 . '  ';
        } else if ($pn > 1 && $pn < $lastPage) {
            $centerPages .= '  ' . $sub1 . '  ';
            $centerPages .= '  ' . $pn . '  ';
            $centerPages .= '  ' . $add1 . '  ';
        }
    }
}  // end POST
// TODO: output/echo pagination display and centerPages, maybe??????????????????????????????????????????????
if($nr > 0){ /* output pagination */ }

//// get output data //// and several more /

if($nr > 0 || empty($_POST['searchquery'])){ //  "|| $np > 1" won't work if you click on page 2, and then page 1 again
    // This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
    $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
    // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
    // $sql2 is what we will use to fuel our while loop statement below
    $searchquery = $_SESSION['membersTeamsSearchquery'];
    $sql2 = mysql_query("
        (SELECT 'member' AS type, id AS id, username AS name, firstname AS admin
        FROM myMembers
        WHERE firstname LIKE '%$searchquery%' OR lastname LIKE '%$searchquery%' OR username LIKE '%$searchquery%')
        UNION (SELECT 'team' AS type, id AS id, team_name AS name, churchname AS admin
        FROM myTeams
        WHERE team_name LIKE '%$searchquery%' OR churchname LIKE '%$searchquery%' OR admin_name LIKE '%$searchquery%') ORDER BY id $limit");

    $paginationDisplay = ""; // Initialize the pagination output variable
    // This code runs only if the last page variable is not equal to 1, if it is only 1 page we require no paginated links to display
    if ($lastPage != "1"){
        // This shows the user what page they are on, and the total number of pages
        $paginationDisplay .= 'Page ' . $pn . ' of ' . $lastPage. '';
        // If we are not on page 1 we can place the Back button
        if ($pn != 1) {
            $previous = $pn - 1;
            $paginationDisplay .=  '    Back ';
        }
        // Lay in the clickable numbers display here between the Back and Next links
        $paginationDisplay .= '' . $centerPages . '';
        // If we are not on the very last page we can place the Next button
        if ($pn != $lastPage) {
            $nextPage = $pn + 1;
            $paginationDisplay .=  '    Next ';
        }
    }

    ////////////Display output/////////////////////////////////////////////////////////
    // TODO: don't use row2 rowX, or play saint row, use $row_myMembers...
    // TODO: get the firstname, userpic, etc in in "sql2" query.
    // TODO: will only work if IDs in members and teams are different, AFTER the addition of my where clause.
    while($row = mysql_fetch_assoc($sql2)){
        $id = $row["id"];
        $name = $row['name'];
            //$sql_if1 = mysql_query("SELECT id, username, firstname FROM myMembers");
        $real = $row['admin'];
            if ( $row['type'] == 'member' ) {
                $sql_if1 = mysql_query("SELECT id, username, firstname FROM myMembers WHERE id=".$id); // if ID is an integer
                while($row2 = mysql_fetch_array($sql_if1)){
                    $if1id = $row2['id'];
                    $if1user = $row2['username'];
                    $if1first = $row2['firstname'];
                    $userpic1 = '
' . check_pic("members", $if1id, "50", "profile") . '
';
                    if($id == $if1id && $name == $if1user){
                        $search_output .= '
' . $userpic1 . 'Username - ' . $if1user . '
First Name - '.$if1first.'

';
                    }
                }
            }
            else // if team
            {
                $sql_if2 = mysql_query("SELECT id, team_name, admin_name, churchname FROM myTeams WHERE id='".$id."'");  // if ID is a string
                while($row3 = mysql_fetch_array($sql_if2)){
                    $if2id = $row3['id'];
                    $if2user = $row3['team_name'];
                    $if2first = $row3['admin_name'];
                    $if2church = $row3['churchname'];
                    $userpic2 = '
' . check_pic("teams", $if2id, "50", "team") . '
';
                    if($id == $if2id && $name == $if2user){
                        $search_output .= '
' . $userpic2 . 'Team Name - ' . $if2user . '
Team Admin - '.$if2first.'

';
                    }
                }
            }
    } // close while
} else {
    $search_output = "
0 results for $searchquery
$sqlCommand2";
} // OPEN BEER \o/
?>

still plenty to do, but it shall work.

A: It looks like your script only produces output if 'searchquery' is set.
The links you are building only answer the 'pn=' question.
Maybe add:
$centerPages .= '  ' . $add1 . '  '

To your links in the:
if($pn==1) {

section.
It's a very long script though, there could be more problems.


text:
Q: finding sql geography point within rectangular (polygon) I have an interesting/annoying issue with finding lat and long of land marks inside the rectangular boundary.
I believe my two points are inside my rectangular boundary. but as you can test yourself the result of the the first select is false instead of true!
DECLARE @boundingRect varchar(1000)
DECLARE @maxLat VARCHAR(20)
DECLARE @minLong VARCHAR(20)
DECLARE @minLat VARCHAR(20)
DECLARE @maxLong VARCHAR(20)

set @maxLat ='-36.06631759541187'
set @minLong ='125.23310677812492'
set @minLat ='-44.43329881450396'
set @maxLong='167.04707162187492'

SET @boundingRect = 'POLYGON((' +   @minLong + ' '  + @minLat + ', ' +
                                        @maxLong + ' ' + @minLat + ', ' +
                                        @maxLong + ' ' + @maxLat + ', ' +
                                        @minLong + ' ' + @maxLat + ', ' +
                                        @minLong + ' ' + @minLat + '))'

DECLARE @Bounds AS Geography =GEOGRAPHY::STPolyFromText(@boundingRect,4326)

DECLARE @point1 AS GEOGRAPHY = GEOGRAPHY::Point(-37.81502, 144.94601, 4326)
DECLARE @point2 AS GEOGRAPHY = GEOGRAPHY::Point(-38.81502, 144.94601, 4326)

SELECT @Bounds.STIntersects(@point1)
SELECT @Bounds.STIntersects(@point2)

To give you background, I have list of land marks (lat,long) that I want to load on google maps. Since the number of landmarks are too many, I cannot return all of them at once. I need to return the landmarks that are in the areas that are visible to user , in their viewing boundary. I'm getting north west (max lat,min long) and south east (min lat, max long) of google maps boundary and sending it to my stored procedure to return back the list of the land marks within that boundary. However, as I explained above I have issues and some land marks are missing in list.

A: @point1 does not intersect this can be verified by:
DECLARE @boundingRect varchar(1000)
DECLARE @maxLat VARCHAR(20)
DECLARE @minLong VARCHAR(20)
DECLARE @minLat VARCHAR(20)
DECLARE @maxLong VARCHAR(20)

set @maxLat ='-36.06631759541187'
set @minLong ='125.23310677812492'
set @minLat ='-44.43329881450396'
set @maxLong='167.04707162187492'

SET @boundingRect = 'POLYGON((' +   @minLong + ' '  + @minLat + ', ' +
                                        @maxLong + ' ' + @minLat + ', ' +
                                        @maxLong + ' ' + @maxLat + ', ' +
                                        @minLong + ' ' + @maxLat + ', ' +
                                        @minLong + ' ' + @minLat + '))'

DECLARE @Bounds AS Geography =GEOGRAPHY::STPolyFromText(@boundingRect,4326);

DECLARE @point1 AS GEOGRAPHY = GEOGRAPHY::Point(-37.81502, 144.94601, 4326);
DECLARE @point2 AS GEOGRAPHY = GEOGRAPHY::Point(-38.81502, 144.94601, 4326);

SELECT @Bounds.STIntersects(@point1);
SELECT @Bounds.STIntersects(@point2);

SELECT @point1, 'Point 1'
UNION ALL
SELECT @Point2, 'Point 2'
UNION ALL
SELECT @BoundingRect, 'Rect'

A: Actually, geography polygon isn't rectangle:

If you want rectangle, you can use geometry polygon:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot find R function in VS Code I'm using VS code and I am trying to learn the ggplot2 package in R. I installed ggplot2 in the base R console and then from the VS Code editor, as per this post's suggestion: How to install R packages in VS code
install.packages('ggplot2', repos='http://cran.us.r-project.org')

I then downloaded an external dataset to use it to learn ggplot2:
load(url('https://github.com/matloff/fasteR/blob/master/data/mlb.RData?raw=true'))

Then I tried to assign the output of ggplot2, on the mlb dataset, to a variable:
p <- ggplot2(mlb)

I get this error:
Error in ggplot2(mlb) : could not find function "ggplot2"

This is happening with other packages as well. For reference, my current directory is:
"/Users/saunok/Library/CloudStorage/Dropbox/Areas_of_Responsibility/Programming/R"
The installed packages are being installed in:
"/var/folders/hq/lbddkgmd0fbbp1r2lqsp7nkm0000gn/T//RtmpYA5gLR/downloaded_packages"
I tried: To use installed R packages in VS Code
I expected: To be able to use the package for analysis
Result: R or VS Code is failing to detect the installed packages.


text:
Q: Audio routing from multiple BT headsets on Mac, with real-time up-sampling from the mic's frequency I need to accept audio streams from multiple Bluetooth headsets, that can only sample from their microphones at low frequencies of 8KHz or 16KHz, record them to wav files while also mixing them in real-time with music playing at an acceptable sample rate of 44.1KHz or 48KHz and play that back to the users through the headset phones. Ideally, this would run on a Mac with macOS 10.14 Mojave, but I also have access to Raspberry Pi 3's and a NUC running Windows or Ubuntu Linux.
Had it not been for the need to upsample the microphone input I'd probably use Jack for this. However, Jack apparently needs to have all the audio cards at the same frequency and appears to provide no facilities for resamping.
So far the closest I got to a functioning solution is using SoX. However it creates a horrendous delay of about 1 second, and I haven't been able to control it using the --buffer option. Also, there seems to be no way on Mac to specify the audio input, essentially limiting me to a single headset.
rec -V -c 1 -r 48000 -p | play -c 1 -r 48000 -p
I've been trying to use PulseAudio's using module-loopback and module-pipe-source in conjunction with module-pipe-sink. So far I've been getting no audio or distorted audio. Also PulseAudio exits about a minute after I run it, regardless of what I do. PulseAudio's integration with macOS CoreAudio seems quite brittle.
I haven't been able to connect my headset to the Pi. According to this post microphone input from headset using the HSP BT profile is very poorly supported.
Some possibilities I've been considering but could still try:

*

*Running Pulseaudio on a Raspberry Pi or inside a Docker container and sending audio back and forth from the Mac via RTP using Roc

*Mix the audio from microphones into the built-in AUX output of the Mac. and sample it back in from an AUX input of a USB-attached sound-card.

*Use Windows or Linux instead of Mac.

*Write custom real-time code in Python.

I'd appreciate your advice on the best way to solve this audio live resampling and routing problem.

A: MAC OS X support the CoreAudio framework, the AudioToolkit framework, and the AudioUnit framework.So you can use the MAC frameworks to solve your requirement.
If you need to resample your input data, you have to use a separate AudioConverter unit.
If you need mixer, you can use audio unit for mixing different parties.
(Audio Unit)

A: The solution has been under my nose the whole time. It turns out MacOS/X can combine multiple audio devices into an "aggregate device", as explained on Roland's company blog. Care should be taken to enable drift correction for the audio channels coming from the headsets.


text:
Q: What if I suppress "override"? I remarked the compiler generates a warning if I suppress the override/new (Overloads/Shadows) keyword. Normally, I set the necessary keyword.
But what if i forget it?
// >>>> Case A - not virtual property -
class MyPoint : Point
{
    int X { get; set; } // vs new int X { get; set; }
}

// >>>> Case B - virtual property -
class Foo
{
    virtual int Value { get { return 0; } }
}

class Bar : Foo
{
    // vs override/new int Value { get { return 1; } }
    int Value { get { return 1; } }
}

A: Then you're not overriding the property, you're creating a new one, just as if you used the new keyword.
Bar x = new Bar();
Foo y = x;
Console.WriteLine(x.Value); // Uses Bar.Value
Console.WriteLine(y.Value); // Uses Foo.Value

This is usually clearer when demonstrated with methods - in this case even when you override, you're still ending up with a separate backing fields in both classes, it's just that one of the fields will be redundant. Without overriding, you've got two backing fields, and which one you access via the property will depend on the compile-time type of the expression you're using to access it.

A: If you forget override/new, Value will function just as if you put new before it.

A: It depends on your goal.  If you're creating a "new" method, you can actually leave out the "new" keyword, and just deal with the warning. "new" exists for clarity.
On the other hand, if your intention is to override the inherited virtual method, leaving out "override" will actually end up creating a "new" method instead, and the inherited method will not be overridden.


text:
Q: Angular 5 remove class from siblings I am trying to create a navbar with multiple hyper links in angular. I want to add class 'active' on click/hover of any of the hyper links and remove 'active' class from its siblings. I am trying to do this by creating a custom directive.
This is what I have achieved.
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
   selector: '[AppHighlightActiveMenu]'
})
export class HighlightMenuDirective {

constructor(private element: ElementRef, private renderer: Renderer2) { }

@HostListener('mouseenter') onMouseEnter() {
   this.activate();
}

@HostListener('mouseleave') onMouseLeave() {

}

private activate() {
  this.renderer.addClass(this.element.nativeElement, 'active');
}

private deactivate(element: ElementRef) {
  console.log("Element: ", element);
}
}

I am able to add the active class to the element but cannot remove the already existing active class from the siblings.
Thanks in advance.

A: Did you try a removeClass?
 removeClass(className: string, element: any) {
   this.renderer.removeClass(element, className);
}

But for a navbar  why do you not use a <router-outlet> with routerLinkActive="active" for your links, where is the default builtin directive for that use in Angular.


text:
Q: How to compress 14 GB of csv files with 7zip (minimizing space)? I have to compress 14 GB of csv files with 7zip. What options should I use to achieve the highest compression?
I have tried Ultra Level with both LZMA and PPMd compression method, obtaining results between 5% and 7%, but since I don't know how Dictionary and Word sizes work I was wondering if a better combination of options exists to reduce the compressed size around 500Mb.

A: You should use the "Ultra" setting. and leave the rest to defaults.


text:
Q: Filter only working when data is synchronous The filter seems to be waiting for two words to be present before matching the string. Here's the code:

    <input type="text" class="form-control rounded"  placeholder="Search all documents" ng-model="filter.all">

            {{ file.values.title }}
        {{ file.values.description }}

So, for instance, there's a file whose file.values.title is conference policy, and no other file matches close to that, either in the title or description.
The filter works when I type conference p, but only when the p is hit, yet this file is unique with just con.
I think that this is something to do with the data coming in asynchronously, because if I just specify the data in the conroller then it works fine. My controller code to pull it in asynchronously is like this:
activate();
function activate() {
    var contenttype = 'files';
    var order = 'title';
    var limit = 500;
    var page = 1;

    return Bolt.getRecords(contenttype, order, limit, page)
        .then(function(data){
            $scope.files = data.data.data;
            console.log($scope.files);
        });
    }


text:
Q: Is it safe to assign nullptr to a function pointer variable? I created a function that accepts a function pointer, e.g.
typedef CString(*GetLabelFunc)(const CSomeObject* const pObject);

void DoSomething(GetLabelFunc funcGetLabel);

The function may receive a null pointer and will return an empty string in that case. This works perfectly fine in MSVC++ 2010 when using NULL and nullptr as parameter as well - but I do not consider a successful compilation a safe harbor in such special cases ...
Now I wondered if passing nullptr is equivalent to NULL for function pointers. The reason why I am asking is that for instance void* does not accept function pointers (or it least it should not be used). So maybe there is a similar reason that nullptr should not be used for function pointers - meaning is it designed to work for object pointers only?

A: Yes, nullptr is specified to be convertible to the null pointer value for all pointer types, including function pointer types.
See [conv.ptr] 4.10/1 and [basic.compound] 3.9.2/3.


text:
Q: Jensen's inequality and conditional expectation Denote $(\Omega,\mathcal{F},P)$ to be our probability space and $X:\Omega\to\mathbb{R}$ a random variable. Suppose we have a measurable convex function $f:\mathbb{R}\to\mathbb{R}$. From Jensen's inequality, we know
that for all sub-sigma-algebra $\mathcal{G}\subset\mathcal{F}$:
$$
E[f(X):\mathcal{G}] \geq f(E[X:\mathcal{G}]).
$$
Now let us denote a partition of $\mathbb{R}$ by $\mathbb{R}^{(n)} = \{\mathbb{R}^{(n)}(k) \subset \mathbb{R}: k=1,..,n\}$ such that $P(X \in \mathbb{R}^{(n)}(k)) = 1/n$ for all $k =1,...,n$. Define a finer partition $\mathbb{R}^{(2n)} = \{\mathbb{R}^{(2n)}(k) \subset \mathbb{R}: k=1,..,2n\}$ such that each component in $\mathbb{R}^{(n)}$ is a proper superset of 2 components in $\mathbb{R}^{(2n)}$ and such that $P(X \in \mathbb{R}^{(2n)}(k)) = \frac{1}{2n}$ for all $k =1,...,2n$
Now define random variable $X^{(n)} = E[X:X\in\mathbb{R}^{(n)}]$. From Jensen's, we know that
$$
E[f(X):X^{(n)}] \geq f(E[X:X^{(n)}]).
$$
I want to show that as $n\to\infty$, the above holds with equality, i.e.
I want to show that in the limit
$$
\lim_{n\to\infty}E[f(X):X^{(2n)}] = \lim_{n\to\infty}f(E[X:X^{(2n)}]) = f(X)
$$
almost surely. Is this possible??? Do I even need convexity?
Thank you.

A: We may as well assume the first partition occurs for $n=1$, so we have partitions at $n=2^k$ for every $k\ge0$. Let $\mathcal F_k=\sigma\{[X\in A]:A\in\mathbb R^{(2^k)}\}$, the $\sigma$-field generated by these partitions.  If we assume both $X$ and $f(X)$ are integrable, then $X^{(2^k)}=E[X|\mathcal F_k]$ and $Y^{(2^k)}=E[f(X)|\mathcal F_k]$ both define martingales. The martingale convergence theorem implies that
$$X^{(2^k)}\to E[X|\mathcal F_\infty],\qquad Y^{(2^k)}\to E[f(X)|\mathcal F_\infty]$$
as $k\to\infty$ almost surely, where $\mathcal F_\infty:=\sigma\left(\bigcup_k\mathcal F_k\right)$. Thus, your desired result will follow for any continuous $f$ if we can show that $X$ is $\mathcal F_\infty$-measurable, no convexity required. (If $f$ is injective, this is if and only if.)
However, this isn't always true. Assume $X$ is uniformly distributed on $(0,1)$. Define
$$\mathbb R^{(2^k)}(j)=\left[\frac{j-1}{2^{k+1}},\frac{j}{2^{k+1}}\right)\cup\left[\frac{j-1+2^k}{2^{k+1}},\frac{j+2^k}{2^{k+1}}\right)$$
for $2\le j\le2^k-1$, and
$$\mathbb R^{(2^k)}(1)=(-\infty,2^{-{k+1}}),\qquad\mathbb R^{(2^k)}(2^k)=[1-2^{-(k+1)},\infty).$$
Note that $P(X\in\mathbb R^{(2^k)}(j))=2^{-k}$ for all $j$, so this partition meets your conditions. However, if $A\in\mathbb R^{(2^k)}$ for some $k$, then $A\cap[0,1)$ is closed under the map $\varphi:x\mapsto x+\frac12\mod1$, hence $[X\in B]\in\mathcal F_\infty$ implies $B\cap[0,1)$ is also closed under $\varphi$. In particular, this implies that $[\frac12\le X<1)\notin\mathcal F_\infty$, so $X$ is not $\mathcal F_\infty$-measurable.


text:
Q: Property or field 'isLPG' cannot be found on object of type 'com.rentautosofia.rentacar.bindingModel.CarBindingModel' - maybe not public? I have an MVC logic like this one.
CarBindingModel
package com.rentautosofia.rentacar.bindingModel

import javax.validation.constraints.Size

class CarBindingModel(@Size(min = 1)
                      var name: String = "",
                      @Size(min = 1)
                      var price: Int = 0,
                      @Size(min = 1)
                      var imgURL: String = "",
                      var isLPG: Boolean? = false)

CarController
package com.rentautosofia.rentacar.controller.admin

import ...

const val PATH_ADMIN_CAR = "admin/car"
const val PATH_ADMIN_ALL_CARS = "$PATH_ADMIN_CAR/all"

@RequestMapping("/$PATH_ADMIN_CAR")
@Controller
class CarController @Autowired
constructor(private val carRepository: CarRepository) {

    @GetMapping("/create")
    fun create(model: Model): String {
        model.addAttribute("car", CarBindingModel())
        model.addAttribute("view", "$PATH_ADMIN_CAR/create")
        return "base-layout"
    }

    @PostMapping("/create")
    fun createProcess(model: Model, @Valid carBindingModel:
CarBindingModel, bindingResult: BindingResult): String {
        if (bindingResult.hasErrors()) {
            model.addAttribute("view", "$PATH_ADMIN_CAR/create")
            model.addAttribute("message", "Invalid data.")
            model.addAttribute("car", carBindingModel)
            return "base-layout"
        }

        val car = car {
            name = carBindingModel.name
            price = carBindingModel.price
            imgURL = carBindingModel.imgURL
            isLPG = carBindingModel.isLPG
        }

        this.carRepository.saveAndFlush(car)
        return "redirect:/$PATH_ADMIN_ALL_CARS"
    }
...
}

CarView
The important one is this one (this is where I get an error)
<input  id="isLPG" type="checkbox" name="isLPG" th:checked="${car.isLPG}"/>

The problem is that I get a SpEL in my view. It says that It cannot find property isLPG in CarBindingModel.
The Error:
An error happened during template parsing (template: "class path resource [templates/base-layout.html]")
Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "car.isLPG" (template: "admin/car/create" - line 16, col 65)
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "car.isLPG" (template: "admin/car/create" - line 16, col 65)
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:
Property or field 'isLPG' cannot be found on object of type 'com.rentautosofia.rentacar.bindingModel.CarBindingModel' - maybe not public?
org.springframework.expression.spel.SpelEvaluationException: EL1008E:
Property or field 'isLPG' cannot be found on object of type 'com.rentautosofia.rentacar.bindingModel.CarBindingModel' - maybe not public?

I am basically trying to bind a boolean value from this checkbox.
If you need additional details, I will happily add them.

A: It looks like SpEL is confused by the is prefix.
This works
package foo

class CarBindingModel(
                  var name: String = "",

                  var price: Int = 0,

                  var imgURL: String = "",

                  var LPG: Boolean? = false)

and
public class So49863132Application {

    public static void main(String[] args) {
        CarBindingModel car = new CarBindingModel("Lexus", 42, "img.png", true);
        Expression exp = new SpelExpressionParser().parseExpression("name + ' ' + price + ' ' + LPG");
        System.out.println(exp.getValue(car));
    }

}

and
Lexus 42 true

EDIT
It's due to the way Kotlin creates the getter; for isLPG, kotlin generates isLPG().
SpEL is expecting isIsLPG().


text:
Q: Textchanged event is not firing when using jscript In my asp.net application, i am using a lookup to enter data to a textbox.For making lookup i have used jscript.I have a button for this lookup from which i am entering data to this textbox.so, i am not entering values directly to the textbox.After entering values to textbox, the textchanged event is not working.What could be the reason?

A: Could it simply be that the textbox is not receiving, and more importantly not losing focus? The textchanged event will only fire when the textbox loses focus.


text:
Q: How to load a js file after loading html? After i load this :
$('#buy-div').load('../buyBar/buyBar.html',function() {
 //do some things here
 });

I would like to include this :
<script src="../buyBar/BuyBar.js"></script> //access some html that does not exist

Beacuse in this js i am looking for some html that does not exist only after the .load function is done. (such as getElementById or $('input').keyup(function() { that happens before the .load was finished.

A: Just put the code that you want to run after the html is loaded in a function. Then call that function in the callback function of the .load('../buyBar/buyBar.html')
Assume "../buyBar/BuyBar.js" originally contains
document.getElementByID("#someElement").innerHTML = "...";

You can change it to
function someFunction(){document.getElementByID("#someElement").innerHTML = "...";}

Now just put <script src="../buyBar/BuyBar.js"></script> in the <head> as usual. Then do this:
$('#buy-div').load('../buyBar/buyBar.html',function() {
    someFunction();
    //do other stuff
});

A: I figure out i can do it by loading it when .load is done :
     let script = document.createElement('script');
      script.src = "../buyBar/Pay.js";
      document.body.append(script);

This works but i am not sure is the best solution.


text:
Q: Support of Radon measures I am reading Folland's Real Analysis. The following is the exercise 7.2.b.
Let $X$ be a locally compact Hausdorff space with a Radon measure $\mu$. Show $x\in\text{supp}(\mu)$ iff $\int f \text {d}\mu >0$ for every $f\in C_c(X, [0,1]) $ such that $f (x)>0.$
The support of a Radon measure is defined as the minimal closed set of full measure(the complement of the union of all open sets with zero measure). I proved $\rightarrow $, but the converse seems harder. Could you give me a hint?


text:
Q: Simple socket server that can send raw messages that I type in? Does a simple socket server exists that sends any message I want to send to all clients? I need to do this to test a socket client. And FAFAIK Putty can't do this.

A: I am not exactly sure what you want, but maybe have a look at netcat (there are ports for nearly any platform just search for netcat).
For an overview of netcat's functions look at the man page of it.

A: you can use "telnet portno" if its a tcp socket


text:
Q: How do I remove validation duplication from a model? Short of extracting shipping and billing addresses into an Address model, how can I remove this validation duplication?
I only want to validate the billing address if it's not the same as the shipping address. How would I go about extracting it into a module? An example would be really helpful as I never know what to include in modules, or self refers to.
  validates :shipping_name, :shipping_address1, :shipping_street_number, :shipping_city, presence: true
  validates :shipping_state, inclusion: { in: Address.states.values }
  validates :shipping_post_code, length: { is: 5 }, numericality: { only_integer: true }

  validates :billing_name, :billing_address1, :billing_street_number, :billing_city, presence: true, unless: -> { self.bill_to_shipping_address? }
  validates :billing_state, inclusion: { in: Address.states.values }, unless: -> { self.bill_to_shipping_address? }
  validates :billing_post_code, length: { is: 5 }, numericality: { only_integer: true }, unless: -> { self.bill_to_shipping_address? }

A: You can make a method and then pass in the bits that are different between the two types of addresses. In this case, the difference is the prefix word for the fields and the ability to pass in extra options.
module AddressValidator
  def validates_address(type, options = {})
    validates :"#{type}_name", :"#{type}_address1", :"#{type}_street_number", :"#{type}_city", {presence: true}.merge(options)
    validates :"#{type}_state", {inclusion: { in: Address.states.values }}.merge(options)
    validates :"#{type}_post_code", {length: { is: 5 }, numericality: { only_integer: true }}.merge(options)
  end
end

class MyModel < ActiveRecord::Base
  extend AddressValidator
  validates_address(:shipping)
  validates_address(:billing, unless: -> { self.bill_to_shipping_address? })
end


text:
Q: Simple htaccess conversion I am a novice to htaccess
I want to translate
http://localhost/hawaii/index.php?city=arizona
to
http://localhost/hawaii/arizona
Any instant help will be very great for me

A: Add this to your .htaccess file in your site's root directory.
RewriteEngine On

RewriteCond %{THE_REQUEST} \ /([^/]+)/index\.php\?city=([^\s&]+) [NC]
RewriteRule ^ /%1/%2 [R=301,L]

RewriteRule ^([^/]+)/([^/]+)/?$ /$1/index.php?city=$2 [QSA,L]


text:
Q: Redirecting to third party link after clicking on Place Order in magento2.3
I am all new to magento2.I am stuck in from where to start for linking third party url after clicking on PlaceOrder button on checkout.I referred many links,but could not find anything helpful.It would be great if anyone can help me out.Below is the screenshot about my scenario.

A: Inside your payment method js implement afterPlaceOrder method. Which is responsible to redirect page. Ex:
afterPlaceOrder: function () {
    window.location.replace(url.build('oxipay/checkout/index'));
},

Check this example method


text:
Q: How to store image path of storage\app\public in laravel-5.4 I am using laravel-5.4 make:auth. In register.blade.php ,added one extra field Profile picture for user .
<form class="form-horizontal" role="form" method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
    {{ csrf_field() }}

has('image') ? ' has-error' : '' }}">
         Profile picture

            <input id="image" type="file" class="form-control" name="image">

            @if ($errors->has('image'))

                    {{ $errors->first('image') }}

            @endif

I want to store the image path in database. Also I have executed:
 php artisan storage:link and the [public/storage] directory has been linked.
app\Http\Controllers\Auth\RegisterController.php:
public function store(Request $request)
{
    if($request->hasFile('image')) {
        $image_name = $request->file('image')->getClientOriginalName();
        $image_path = $request->file('image')->store('public');
        $image = Image::make(Storage::get($image_path))->resize(320,240)->encode();
        Storage::put($image_path,$image);
        $image_path = explode('/',$image_path);
        $user->image = $image_path;
        $user->save();
    } else{
        return "No file selected";
    }

}

web.php
Route::post('/store', 'RegisterController@store');
Route::get('/show', 'RegisterController@show');

In database,in user table under image is stored as a temporary path :

C:\xampp\tmp\phpC762.tmp.

How to store image path of storage\app\public.

A: Change this code in your controller
$user->image = $image_path;

to
$user->image = Storage::url($image_name);

Docs: https://laravel.com/docs/5.4/filesystem#file-urls


text:
Q: In 2023, how to invite Facebook friends in Game via API? I've read tons of articles on Facebook friends integration, tested several things, but clearly, I'm still not able today to tell if it can be at least achieved through the facebook api (which is a shame....).
I have a website, main content is related to games.
I'm using "Facebook Login for Gaming" to authenticate a user.
Everything works fine.
I saw a lots of things that no longer work in 2023...
The only little success I got is when using the Friend Finder dialog.
https://www.facebook.com/gaming/me/friendfinder/myAppId
Unfortunately, it tells me that it only works on mobile....
My website is for both mobile and desktop.
So, what could be the best way to offer a panel to a user of my website so that he can invite the desired friends of him, once connected to the my website ?
Many thanks.


text:
Q: best simplest code to move a UIImage View from point A to point B @IBOutlet weak var imageView: UIImageView!

override func viewWillAppear(animated: Bool) {
    self.imageView.center.y -= view.bounds.height
}
override func viewDidAppear(animated: Bool) {
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y += self.view.bounds.height
    }, completion: nil)
}

This code does successfully move the image view across the screen, but I'm not sure how to make it stop where I want it to. It just slides off the screen. The goal is to move the image from point A to point B. If there is another easier way to do this I would be happy to know. Thanks!

A: Add this in viewWillAppear,you will get your animation,you problem is autoLayout
override func viewWillAppear(animated: Bool) {
        self.imageview.setTranslatesAutoresizingMaskIntoConstraints(true)
        self.imageview.center.y -= self.view.bounds.height
    }

When you move a view frame,it is better use animate antoLayout Constraint
Drag the red Constraint into outlet then

Example Code
class ViewController: UIViewController{
    @IBOutlet weak var imageview: UIImageView!
    @IBOutlet weak var yConstraint: NSLayoutConstraint!

    override func viewWillAppear(animated: Bool) {
        yConstraint.constant -= self.view.bounds.height;
        self.view.updateConstraintsIfNeeded()
        self.view.layoutIfNeeded()
    }
    override func viewDidAppear(animated: Bool) {
        yConstraint.constant += self.view.bounds.height;

        UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
            self.view.layoutIfNeeded()
            }, completion: nil)
    }
}

A: override func viewDidAppear(animated: Bool) {
    var destinationY:CGFloat = self.view.bounds.height / 2 // Your destination Y
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y = destinationY
    }, completion: nil)
}

Just moving it too far, that'll put the center in the middle of the screen.

A: override func
viewDidAppear(animated: Bool) {
    super.viewDidAppear( animated )
    let orgY = self.imageView.center.y
    self.imageView.center.y -= view.bounds.height
    UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: {
        self.imageView.center.y = orgY
    }, completion: nil)
}

Save original point and go!

A: For this line: self.imageView.center.y += self.view.bounds.height
Maybe make it move less? self.imageView.center.y += self.view.bounds.height - 200

A: Your implementation is fine, you just have to understand the amount you are changing y by.  self.view.bounds.height refers to the height of the view controllers view.  That's probably pretty big, in fact, likely the entire height of the screen you're looking at.  So you need to decide what point you want to move it to and do some math.  Say you want to stop it when it hits the top edge of the screen.  You might do something very simple like:
self.imageView.center.y += (self.view.frame.origin.y - self.imageView.frame.origin.y)

I did not test this, please implement in the way that works best for your situation.


text:
Q: How to add a class to father element when it's child is clicked I'm trying to add class with jQuery to an li when a span selector inside it is getting clicked.
What I've done so far:
jQuery(document).ready(function() {
  jQuery('li span').click(function() {
    jQuery(this).toggleClass('active');

  });
});

Hello World

This of course adds the class to the span itself.
I can't figure out how to reach his father -> the li
Any suggestions?

A: Just use .parent() to access parent element
jQuery(this).parent().toggleClass('active');

A: Use .parent() to select the parent element like so
jQuery(document).ready(function() {
  jQuery('li span').click(function() {
    jQuery(this).parent().toggleClass('active');
  });
});

Hello World


text:
Q: Multiplying two columns in sql and obtain as a result in the column and it should be in descending order I want to add a result to the column by multiplying two columns and obtain the result in descending order.
Here is my query :
SELECT whid, max_pallets, cost_per_pallet, (max_pallets * cost_per_pallet) as maximum cost
FROM WAREHOUSE
ORDER BY maximum cost Desc;

whenever I execute this statement it's getting error like:

Error at line 1: ORA-00923: FROM keyword not found where expected

A: You missed double quotes around maximum cost
SELECT whid, max_pallets, cost_per_pallet, (max_pallets * cost_per_pallet)
as "maximum cost" FROM WAREHOUSE ORDER BY "maximum cost" Desc


text:
Q: blogger api jquery retrieve blog not post I am able to pull one post at a time from a blog using Jquery:

When I change the call to retrieve the entire BLOG I get "undefined"...

I just want the NEWEST blog post to show up on the page automatically instead of having to go and switch out the blogID every time.
-->
--thanks

A: This is due to an "undocumented" change in the Blogger API that has still not been updated in their API documentation (Example, this page still lists the "content" property as part of the default result set when calling /posts). This was likely done at some point to reduce the response size on a default call; they just haven't done a great job of letting developers know that.
The solution is to simply append fetchBodies=true to your API call; this will ensure the content property is returned for each post. Example:


text:
Q: Retrieve values from Google Sheet to Web App inputs I have a code that searches for a value entered in an INPUT field, and it looks for it on a Google sheet, and if the value exists, it returns a "correct" message, if the value does not exist, it returns an "incorrect" message ". What I am looking for is that the value entered in the INPUT field is searched on a Google sheet range of values, if the value entered in the INPUT field matches a value in the Google sheet range (column A), then show the "correct" message, and populate the fallowing INPUTS that correspond to the entered value. Example: If the name "Peter" is entered, when pressing "VALIDATE", the message "correct" should appear, and in the fields: ITEM, QUANTITY and AMOUNT, the values corresponding to the name entered in the INPUT should appear, in In this case, the name "Peter" was entered so: ITEM = Item 1, QUANTITY = 25 and AMOUNT = $55.00, in the corresponding INPUT fields.
I know the line:
var user_name = sheetNames .getRange("A2").getValue();, should include the search range, in this case it would be "A2:D6", and change "getValue" to "getValues", but there I'm stuck. I don't know how to request that it search for a single value in the entire range of the google sheet and how to make it extract the values from the line to which the entered name corresponds, and then pass them to the corresponding INPUTS on the Web App. All of this, using only JavaScript.
GS
 function doGet() {
  var template = HtmlService.createTemplateFromFile("page1")
  return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
  }

function fetchUserValues1(){
    var ss = SpreadsheetApp.openByUrl("GOOGLE SHEET URL");
     var sheetNames = ss.getSheetByName("Sheet 1");
     var user_name  =  sheetNames .getRange("A2").getValue();
    return user_name;
}

HTML
<!DOCTYPE html>

    <base target="_top">

NAME:

<input type="text" id="name">

<input type='button' value='VALIDATE' onclick="handleButton()">

ITEM:

<input type="text" id="Item">

QUANTITY:

<input type="text" id="Quantity">

AMOUNT:

<input type="text" id="Amount">

A: In your script, how about the following modification?
Google Apps Script side:
function fetchUserValues1(v) {
  var ss = SpreadsheetApp.openByUrl("GOOGLE SHEET URL");
  var sheetNames = ss.getSheetByName("Sheet 1");
  var r = sheet.getRange("A2:A" + sheet.getLastRow()).createTextFinder(v).matchEntireCell(true).findNext();
  var col = sheet.getLastColumn();
  return r ? r.offset(0, 0, 1, col).getValues()[0] : Array(col).fill("");
}

HTML & Javascript side:
<!DOCTYPE html>

  <base target="_top">

NAME:

  <input type="text" id="name">

  <input type='button' value='VALIDATE' onclick="handleButton()">

ITEM:

  <input type="text" id="Item">

QUANTITY:

  <input type="text" id="Quantity">

AMOUNT:

  <input type="text" id="Amount">

*

*In this script, when the value of name is found, the values from column "B" to "D" are put into the input tags. When the value of name is not found, the empty values from column "B" to "D" are put into the input tags.

Note:

*

*When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.

*You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:

*

*Web Apps

*Taking advantage of Web Apps with Google Apps Script (Author: me)


text:
Q: htaccess url rewrite bootstrap Im looking to create a htaccess rewrite rule to push everything through a single file:
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /index.php/$1 [L]

Nice and simple.
What I'm struggling with is also redirecting none www. to www. whilst still keeping the above redirect rule working.
Please note that the host would be unknown as multiple domains/site will be pushed through this htaccess.
Thanks!
Following the comments
Options   FollowSymLinks
RewriteEngine On

RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /index.php/$1 [L]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Does work in redirecting none www to www but doesn pull through the rest of the url:
test.com/2 should redirect to www.test.com/2 and be redirected through to the index.php, but its being redirected to www.test.com.

A: Add below your above rules these lines:
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


text:
Q: Flask Class Based Views - Polymorphism I've a class-based view as follow:-
class MoviesList(MethodView):

    def get(self):
        return 'MoviesList'

    def get(self,pk):
        return pk

movies.add_url_rule('/movies/', view_func=MoviesList.as_view('movies_by_title'))
movies.add_url_rule('/movie/<pk>/', view_func=MoviesList.as_view('movie_details_by_id'))

When I hit /movie/pk/ endpoint it says,
TypeError: get() got an unexpected keyword argument 'pk'. As per the polymorphism concept, it should automatically detect which function to route.
Why is this happening? Also, how can I achieve the same functionality, ie without making another class, how can I do it?

A: Python does not support method/function overloading. You can only define one get method and provide defaults for optional arguments:
class MoviesList(MethodView):

    def get(self, pk=None):
        if pk is None:
            return 'MoviesList'
        return pk


text:
Q: Create Mini/Sub Data Frames Using a Big Pandas DataFrame's Column Values I posted a question earlier in this post. I thought I would ask this question separate as this is just one operation to divide a big data frame into separate mini/sub dataframes.
Say, I have this df:
    245           245   245           867               867
0   Reddit        NaN   NaN           Facebook          NaN
1   ColumnNeeded  NaN   ColumnValue   ColumnNeeded      ColumnValue
2   RedditInsight NaN   C             FacbookInsights   A
3   RedditText    NaN   H             FacbookText       L

Now, I want two different data frames like this,
df1:
    245           245   245
0   Reddit        NaN   NaN
1   ColumnNeeded  NaN   ColumnValue
2   RedditInsight NaN   C
3   RedditText    NaN   H

df2:
    867               867
0   Facebook          NaN
1   ColumnNeeded      ColumnValue
2   FacbookInsights   A
3   FacbookText       L

Basically, I want to create sub data frames by it's unique values of headers.
I was trying to create a list like this:
list_of_dfs = [set(i) for i in df.columns]

This returns just column values,
[{245}, {245}, {245}, {867}, {867}]

Any ideas how I can do this?

A: Since you need to reset index and get sub dataframes for each unique name of columns, you need:
[df[i].reset_index(drop=True) for i in df.columns.unique()]

Output:
[
              245 245          245
 0         Reddit NaN          NaN
 1   ColumnNeeded NaN  ColumnValue
 2  RedditInsight NaN            C
 3     RedditText NaN            H,

                867          867
 0         Facebook          NaN
 1     ColumnNeeded  ColumnValue
 2  FacbookInsights            A
 3      FacbookText            L
]


text:
Q: How to get session driver Laravel 5 How I can get current session driver used for session in Laravel 5?
I want to know where my session is written.
I can get session ID using
Session::getId();

but driver can't

A: Hello you can get next
Session::getDefaultDriver();

For more info about methods visit Laravel API

A: Or simply in a controller:
dd(session()->getDefaultDriver());


text:
Q: Wordpress - Vimeo frame stills On my website i'm doing a portfolio with vimeo videos and I want to know if there's a plugin that make automatic frame stills from the video to the post, or if there's any way to do something like thumbnail creator on vimeo (you know, when you upload a video and you watch it and define this exact frame).
I want to end up with something like this when i have the video, then stills pictures from the video (automatic generator) and then the description.
Is there any plugin that can make this work?

A: You can actually grab the generated poster frame using a bit of PHP
<?php
    $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/" . get_field('vimeo_url') . '.php' ));
?>
<a rel="lightbox" href="<?php echo "https://vimeo.com/" . get_field('vimeo_url'); ?>">
    <img src="<?php echo $hash[0]['thumbnail_large']; ?>" alt="">

just replace the get_field('vimeo_url') with your video ID and you're good.. this doesn't handle the download/writing to wordpress database.


text:
Q: Can not use `cut -c` (`--characters`) with UTF-8? The command cut has an option -c to work on characters, instead of bytes with the option -b. But that does not seem to work, in en_US.UTF-8 locale:
The second byte gives the second ASCII character (which is encoded just the same in UTF-8):
$ printf 'ABC' | cut -b 2
B

but does not give the second of three greek non-ASCII characters in UTF-8 locale:
$ printf 'αβγ' | cut -b 2
�

That's alright - it's the second byte.
So we look at the second character instead:
$ printf 'αβγ' | cut -c 2
�

That looks broken.
With some experiments, it turns out that the range 3-4 shows the second character:
$ printf 'αβγ' | cut -c 3-4
β

But that's just the same as the bytes 3 to 4:
$ printf 'αβγ' | cut -b 3-4
β

So the -c does not more than the -b for UTF-8.
I'd expect the locale setup is not right for UTF-8, but in comparison, wc works as expected;
It is often used to count bytes, with option -c (--bytes).
 (Note the confusing option names.)
$ printf 'αβγ' | wc -c
6

But it can also count characters with option -m (--chars), which just works:
$ printf 'αβγ' | wc -m
3

So my configuration seems to be ok - but something is special about cut.
Maybe it does not support UTF-8 at all? But it does seem to support multi-byte characters, otherwise it would not need to support -b and -c.
So, what's wrong? And why?

The locale setup looks right for utf8, as far as I can tell:
$ locale
LANG=en_US.UTF-8
LANGUAGE=en_US
LC_CTYPE=en_US.UTF-8
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

The input, byte by byte:
$ printf 'αβγ' | hd
00000000  ce b1 ce b2 ce b3                                 |......|
00000006

A: Since many grep implementations are multibyte-aware, you can also use grep -o to simulate some uses of cut -c.
First two characters:
$ echo Τηεοδ29 | grep -o '^..'
Τη

Last two characters:
$ echo Τηεοδ29 | grep -o '...$'
δ29

Second character:
$ echo Τηεοδ29 | grep -o '^..' | grep -o '.$'
η

Adjust the number of periods, or use {x,y} syntax, to simulate cut ranges.

A: You haven't said which cut you're using, but since you've mentioned the GNU long option --characters I'll assume it's that one. In that case, note this passage from info coreutils 'cut invocation':

'-c character-list'
'--characters=character-list'

Select for printing only the characters in positions listed in character-list. The same as -b for now, but internationalization will change that.

(emphasis added)
For the moment, GNU cut always works in terms of single-byte "characters", so the behaviour you see is expected.

Supporting both the -b and -c options is required by POSIX — they weren't added to GNU cut because it had multi-byte support and they worked properly, but to avoid giving errors on POSIX-compliant input. The same -c has been done in some other cut implementations, although not FreeBSD's and OS X's at least.
This is the historic behaviour of -c. -b was newly added to take over the byte role so that -c can work with multi-byte characters. Maybe in a few years it will work as desired consistently, although progress hasn't exactly been quick (it's been over a decade already). GNU cut doesn't even implement the -n option yet, even though it is orthogonal and intended to help the transition. There are potential compatibility problems with old scripts, which may be a concern, although I don't know definitively what the reason is.

A: colrm (part of util-linux, should be already installed on most distributions) seems to handle internationalization much better :
$ echo 'αβγ' | colrm 3
αβ
$ echo 'αβγ' | colrm 2
α

Beware of the numbering : colrm N will remove columns from N, printing characters up to N-1.
(credits)


text:
Q: nginx password protect directory code that works for all domains I am new to nginx.
I have followed the tutorial at
http://kbeezie.com/protecting-folders-with-nginx/
to password protect a directory using nginx.
I have many domains in the nginx configuration file and all those have 'admin' directory like
/home/domain.com/public_html/admin
I have this code in each of the domain server block.
server {
        server_name domain.com www.domain.com;
        listen xxx.xx.xx.xxx;
        root /home/domain.com/public_html;

    location ~/admin {
        auth_basic "Admin Login";
        auth_basic_user_file /home/domain.com/public_html/admin/.htpasswd;
    }

    # This will deny access to any hidden file (beginning with a .period)
    location ~ /\. { deny  all; }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
    }

    }

Is it possible to keep this code in the top server block so that it applies to all the admin directories for all domains ? (without keeping this code in each of the domain server blocks ?)
   server {
        listen       80;
        server_name  localhost;
        root         /usr/share/nginx/html;

# code to password protect all admin directories in all domains
}

I don't mind using the same password for all admin directories.
Please suggest.

A: You can separate the config you want to reuse into a new file and then use the
include [file];

pattern to inject the settings where ever you want them.


text:
Q: Pandas или openpyxl? Хочу написать скрипт, который структурирует экселевские данные , и размещает их опять в экселе но по-другому (по др. ячейкам).  Что-то вроде сводной таблицы, но с некоторыми дополнениями, т.к. свод. таблица, не совсем выполняет необходимую задачу. К какой библиотеке лучше обратиться к pandas или openpyxl? И какая между ними разница?

A: Начать реализацию вашей задачи можно так:
import pandas as pd  #  pip install pandas

# читаем Excel в Pandas DataFrame
df = pd.read_excel(r'D:\download\исходник.xls', skiprows=1)

# разворачиваем столбцы в строки
d = df.set_index('Ф.И.О.').stack()

...

Получилось:
In [34]: d.reset_index()
Out[34]:
          Ф.И.О.                   level_1         0
0    Иванов М.Е.                        кв         1
1    Иванов М.Е.                    пропис         4
2    Иванов М.Е.                      прож         4
3    Иванов М.Е.             Полез площадь      73.5
4    Иванов М.Е.           Отопление тариф   1936.54
5    Иванов М.Е.           Отопление ГгКал   1.66185
6    Иванов М.Е.           Отопление ИТОГО   3218.24
7    Иванов М.Е.    ГВС(горячая вода м.куб        23
8    Иванов М.Е.                ГВС начисл   2689.16
9    Иванов М.Е.  ХВС(холодная вода) м.куб         7
10   Иванов М.Е.                ХВС начисл    125.23
11   Иванов М.Е.              Стоки м. куб        30
12   Иванов М.Е.              Стоки начисл     682.5
13   Иванов М.Е.                     мусор    169.05
14   Иванов М.Е.                  ТО жилья      1617
15   Иванов М.Е.                   ОДН ГВС   0.84735
16   Иванов М.Е.               одн гвс руб   99.0721
17   Иванов М.Е.                   ОДН ХВС  0.766097
18   Иванов М.Е.               одн хвс руб   13.7055
19   Иванов М.Е.                 ОДН СТОКИ   1.61345
..           ...                       ...       ...
165        итого             Полез площадь     397.8
166        итого           Отопление тариф         0
167        итого           Отопление ГгКал   8.99433
168        итого           Отопление ИТОГО   17417.9
169        итого    ГВС(горячая вода м.куб        36
170        итого                ГВС начисл   4209.12
171        итого  ХВС(холодная вода) м.куб        61
172        итого                ХВС начисл   1091.29
173        итого              Стоки начисл   2206.75
174        итого                     мусор    914.94
175        итого                  ТО жилья      7956
176        итого                   ОДН ГВС   4.58607
177        итого               одн гвс руб   536.203
178        итого                   ОДН ХВС    4.1463
179        итого               одн хвс руб   74.1773
180        итого                 ОДН СТОКИ   8.73236
181        итого              однстоки руб   198.661
182        итого                   Кап.рем   2864.16
183        итого                     ИТОГО   37455.7
184        итого                  пени  за         0

[185 rows x 3 columns]

Далее после фильтрации нудная и кропотливая работа по формированию нужной вам выходной формы... Для этого возможно придется прибегнуть к низкоуровневому программированию на уровне отдельных ячеек Excel - для этого можно воспользоваться openpyxl или xlsxwriter.


text:
Q: OpenCV: contourArea assertion failed when I try to start my application it crashes unexpectedly while executing contourArea.
Here is the error:
OpenCV Error: Assertion Failed (contour.checkVector(2) >= 0 && (contour.depth() ==CV_32F || contour.depth() == CV_32S)) in unknown function, file ..\..\..\src\opencv\modules\imgproc\src\contours.cpp, line 1904

My program is simple:
1.catch frame from camera,
2. gaussian and median filtering,
3. morphological opening,
4. threshold,
5. findContours,
6. draw the contourn with bigger area
Here is my code:
#include <opencv2/opencv.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;

Mat mask(480,640, CV_8UC1);
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
vector<Point> my_contourn;

int main(){
VideoCapture camera(0);

if(!camera.isOpened()){
    return -1;
}

while(1){
    Mat cameraframe,filtered_img,mask2;
    camera >> cameraframe;

    GaussianBlur(cameraframe,filtered_img,Size(11,11),0,0);
    medianBlur(filtered_img,filtered_img,11);
    cvtColor(filtered_img,filtered_img,CV_BGR2HSV);
    inRange(filtered_img, Scalar(0, 76, 97), Scalar(20, 143, 205), mask);
    morphologyEx(mask,mask,MORPH_OPEN,getStructuringElement(MORPH_RECT,Size(9,9),Point(4,4)));
    GaussianBlur(mask,mask,Size(3,3),0,0);
    dilate(mask,mask,getStructuringElement(MORPH_ELLIPSE,Size(7, 7),Point(0, 0) ));

    mask.copyTo(mask2);
    findContours(mask2,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,Point(0, 0));

    double area,max_area=0.0;

    for(int i=0;i<contours.size();i++){

        area = fabs(contourArea(contours[i]));
        if (area>max_area)
        {
            max_area=area;
            my_contourn=contours[i];
        }
    }

    drawContours( mask, my_contourn, 10, Scalar(255,0,0), 2, 8);

    imshow("my cont",mask);

    if(waitKey(30)>=0)
        break;
}
return 0;
}

How I can fix it??

A: I confirm that is a VS2012 problem. On VS2010 everythings is fine.

A: This wierd bug also occurs on VS2013.
Try converting the type of contours[i] from vector to CV::Mat before pass it to contourArea.
Mat conMat(contours[i].size(), 2, CV_32FC1);
for(int i = 0; i < contours[i].size(); i ++)
{
     conMat.at<float>(i, 0) = contours[i].x;
     conMat.at<float>(i, 1) = contours[i].y;
}
area = fabs(contourArea(conMat));

That works for me.


text:
Q: Finding the entity with the most relationships in JPQL I have a teacher entity, which has a ManytoMany with semesters.
So many teachers can have many semesters.
I'm trying to write a JPQL query, where I can get the teacher, that has the most amount of semesters.
  public TeacherEntity teacherWithMostSemesters(){
    EntityManager em = emf.createEntityManager();
    em.createQuery("SELECT te from TeacherEntity te").getResultList();
    return null;
}

My issue is that I have generated my database from a database scheme,
and it has created a weird entity with the FK for both the teacher's table and the semester table
package com.tvestergaard.start.data.entities;

import javax.persistence.*;
import java.util.Objects;

@Entity
@Table(name = "teacher_semester", schema = "student", catalog = "")
@IdClass(TeacherSemesterEntityPK.class)
public class TeacherSemesterEntity {
    private long teachingId;
    private long teachersId;

    @Id
    @Column(name = "teaching_ID")
    public long getTeachingId() {
        return teachingId;
    }

    public void setTeachingId(long teachingId) {
        this.teachingId = teachingId;
    }

    @Id
    @Column(name = "teachers_ID")
    public long getTeachersId() {
        return teachersId;
    }

    public void setTeachersId(long teachersId) {
        this.teachersId = teachersId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TeacherSemesterEntity that = (TeacherSemesterEntity) o;
        return teachingId == that.teachingId &&
                teachersId == that.teachersId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(teachingId, teachersId);
    }
}

It should have created a relationship between the two, but instead, it generated a table of the table with the two foreign keys...
How can I fix this, and make a JPQL query, who finds the teacher with the most semesters taught?


text:
Q: VBA Excel : run-time error -2127417848 automation error the object invoked has disconnected from its client Backstory and pertinent info:
I am not a professional coder. I used to do Oracle pl/sql a long, long, long time ago. Back then I would tinker with VB, I am by no means an expert. As far as Excel, this is my first attempt at using macros. I created this file/form so that myself and others can track issues/trends over time.
This is a spreadsheet sitting on a network drive that many users will access. It has a macro data entry form that will open automatically when the file is opened. Also, the form can be manually opened (Ctrl+Shift+H) if the user happens to close the form without closing the file.
The file was created using Excel 2010 and all users machines are running Excel 2010. All machines are Running Windows 7 Enterprise SP1.
All users can open and add/edit the file...except one (the main user that will use this form the most!) **Note: The machine in question has no issues opening ANY other Excel file...just this one.
When the spreadsheet is opened, it is protected so that if the form is closed, the data cannot be accidentally deleted. Within the code right before the insert it is unprotected, activated, then inserted. After the insert it is protected again.
There are two main errors.

*

*When clicking on the File itself from Explorer, Excel hangs, crashes, and attempts a restart.

*When opening Excel and clicking on repair the file, the spreadsheet will open, the form will show. The user will enter the data, Click the "Record Entry" button. The data is not inserted and the following message appears:

"run-time error -2127417848 automation error the object invoked has
  disconnected from its client"

Things that I have tried with no success (from ideas brought forth with other similar problems):
I have added a blank module, added the "Activate" verbiage, and run the compatibility troubleshooter, with no success.
I have supplied the code for the following:
Microsoft Excel Objects : ThisWorkBook
Forms : usrfrm_HC
Modules : Module1 and Module2

ThisWorkBook Code:
    Private Sub Workbook_Open()

    Dim wks As Worksheet

    Set wks = ActiveSheet
    ThisWorkbook.Activate

    Set wks = ThisWorkbook.Worksheets("DATA")

    For Each wks In ThisWorkbook.Worksheets
        wks.Protect , UserInterfaceOnly:=True
        'wks.Unprotect
    Next wks

    usrfrm_HC.Show

    End Sub

There is one Module1 that is empty
Then I have the following in Module2
    Sub displayUserForm()
        usrfrm_HC.Show
    End Sub

Then I have a form called: usrfrm_HC  Here is the code:
    Private Sub cmd_CloseForm_Click()
        Unload Me
    End Sub
    __________________________________________________________________
    'ties the spin button control to the textbox, shows attempts number
    Private Sub spb_Attempt_Change()
        tbx_Attempt.Value = Me.spb_Attempt.Value
    End Sub
    ___________________________________________________________________
    Private Sub UserForm_Initialize()

    Dim cReset As Control
    For Each cReset In Me.Controls
        If TypeName(cReset) = "CheckBox" Then
            With cReset
                .Value = "False"
            End With
        End If
    Next cReset

    Dim tReset As Control
    For Each tReset In Me.Controls
        If TypeName(tReset) = "TextBox" Then
            With tReset
                .Text = ""
            End With
         End If
    Next tReset

    With Me
        .tbx_Date.Text = Format(Date, "mm/dd/yyyy")
        .tbx_TNumber.Text = ""
        .tbx_LRate.Text = ""
        .tbx_Attempt.Value = 0
        .spb_Attempt.Value = 0
        .cbx_PType.Text = "Select Type"
        .cbx_PType.List = Array("Value1", "Value2")
        .chk_FA1.Value = False
        .chk_FA2.Value = False
        .chk_FA3.Value = False
        .chk_FMA1.Value = False
        .chk_FMA2.Value = False
        .chk_FMA3.Value = False
        .chk_CMA1.Value = False
        .chk_CMA2.Value = False
        .chk_CMA3.Value = False
        .chk_AMA1.Value = False
        .chk_AMA2.Value = False
        .chk_AMA3.Value = False
        .chk_AMA4.Value = False
        .chk_AA1.Value = False
        .chk_AA2.Value = False
        .chk_AA3.Value = False
    End With

    End Sub
    _______________________________________________________________________
    Private Sub cmd_RecordEntry_Click()

    Dim MyWorksheet As Worksheet
    Dim myFirstBlankRow As Long

    Set MyWorksheet = ActiveSheet
    ThisWorkbook.Activate

    Set MyWorksheet = ThisWorkbook.Worksheets("DATA")

    With MyWorksheet

        'looks for first blank row
        myFirstBlankRow = .Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1

        'ensures mandatory field entered or gives error
        If (Me.tbx_Date.Value <> "") And (Me.tbx_TNumber.Value <> "") And (Me.cbx_PType.Text <> "Select Type") And (Me.tbx_Attempt.Value > 0) And (Me.tbx_LRate.Value <> "") Then

            MyWorksheet.Unprotect

            .Cells(myFirstBlankRow, 1) = Me.tbx_Date.Value
            .Cells(myFirstBlankRow, 2) = Me.tbx_TNumber.Value
            .Cells(myFirstBlankRow, 3) = Me.cbx_PType.Value
            .Cells(myFirstBlankRow, 4) = Me.tbx_Attempt.Value
            .Cells(myFirstBlankRow, 5) = Me.tbx_LRate.Value

            If Me.chk_FLHSWLink.Value = "True" Then .Cells(myFirstBlankRow, 6) = "X"
            If Me.chk_FRHSWLink.Value = "True" Then .Cells(myFirstBlankRow, 7) = "X"
            If Me.chk_FTROV.Value = "True" Then .Cells(myFirstBlankRow, 8) = "X"
            If Me.chk_FPRV.Value = "True" Then .Cells(myFirstBlankRow, 9) = "X"
            If Me.chk_FExtPBox.Value = "True" Then .Cells(myFirstBlankRow, 10) = "X"
            If Me.chk_FEMED.Value = "True" Then .Cells(myFirstBlankRow, 13) = "X"
            If Me.chk_FLHSCPnl.Value = "True" Then .Cells(myFirstBlankRow, 12) = "X"
            If Me.chk_FRHSCPnl.Value = "True" Then .Cells(myFirstBlankRow, 11) = "X"
            If Me.chk_FNWW.Value = "True" Then .Cells(myFirstBlankRow, 14) = "X"

            If Me.chk_FA1.Value = "True" Then .Cells(myFirstBlankRow, 15) = Me.tbx_FA1.Value
            If Me.chk_FA2.Value = "True" Then .Cells(myFirstBlankRow, 16) = Me.tbx_FA2.Value
            If Me.chk_FA3.Value = "True" Then .Cells(myFirstBlankRow, 17) = Me.tbx_FA3.Value

            If Me.chk_FMDHFthru.Value = "True" Then .Cells(myFirstBlankRow, 18) = "X"
            If Me.chk_FMACDCPwrBox.Value = "True" Then .Cells(myFirstBlankRow, 19) = "X"
            If Me.chk_FMDnuts.Value = "True" Then .Cells(myFirstBlankRow, 20) = "X"

            If Me.chk_FMA1.Value = "True" Then .Cells(myFirstBlankRow, 21) = Me.tbx_FMA1.Value
            If Me.chk_FMA2.Value = "True" Then .Cells(myFirstBlankRow, 22) = Me.tbx_FMA2.Value
            If Me.chk_FMA3.Value = "True" Then .Cells(myFirstBlankRow, 23) = Me.tbx_FMA3.Value

            If Me.chk_CMLHSMframes.Value = "True" Then .Cells(myFirstBlankRow, 24) = "X"
            If Me.chk_CMRHSMframes.Value = "True" Then .Cells(myFirstBlankRow, 25) = "X"
            If Me.chk_CMLHSMWW.Value = "True" Then .Cells(myFirstBlankRow, 26) = "X"
            If Me.chk_CMRHSMWW.Value = "True" Then .Cells(myFirstBlankRow, 27) = "X"

            If Me.chk_CMA1.Value = "True" Then .Cells(myFirstBlankRow, 28) = Me.tbx_CMA1.Value
            If Me.chk_CMA2.Value = "True" Then .Cells(myFirstBlankRow, 29) = Me.tbx_CMA2.Value
            If Me.chk_CMA3.Value = "True" Then .Cells(myFirstBlankRow, 30) = Me.tbx_CMA3.Value

            If Me.chk_AMBB.Value = "True" Then .Cells(myFirstBlankRow, 31) = "X"
            If Me.chk_AMFthru.Value = "True" Then .Cells(myFirstBlankRow, 32) = "X"
            If Me.chk_AMDnuts.Value = "True" Then .Cells(myFirstBlankRow, 35) = "X"
            If Me.chk_AMLHSFBrd.Value = "True" Then .Cells(myFirstBlankRow, 33) = "X"
            If Me.chk_AMRHSFBrd.Value = "True" Then .Cells(myFirstBlankRow, 34) = "X"
            If Me.chk_AMBDoor.Value = "True" Then .Cells(myFirstBlankRow, 36) = "X"
            If Me.chk_AMWTBF22.Value = "True" Then .Cells(myFirstBlankRow, 37) = "X"
            If Me.chk_AMO2SPnl.Value = "True" Then .Cells(myFirstBlankRow, 38) = "X"

            If Me.chk_AMA1.Value = "True" Then .Cells(myFirstBlankRow, 39) = Me.tbx_AMA1.Value
            If Me.chk_AMA2.Value = "True" Then .Cells(myFirstBlankRow, 40) = Me.tbx_AMA2.Value
            If Me.chk_AMA3.Value = "True" Then .Cells(myFirstBlankRow, 41) = Me.tbx_AMA3.Value
            If Me.chk_AMA4.Value = "True" Then .Cells(myFirstBlankRow, 42) = Me.tbx_AMA4.Value

            If Me.chk_AA1.Value = "True" Then .Cells(myFirstBlankRow, 43) = Me.tbx_AA1.Value
            If Me.chk_AA2.Value = "True" Then .Cells(myFirstBlankRow, 44) = Me.tbx_AA2.Value
            If Me.chk_AA3.Value = "True" Then .Cells(myFirstBlankRow, 45) = Me.tbx_AA3.Value

            If Me.tbx_Comments.Value <> "" Then .Cells(myFirstBlankRow, 46) = Me.tbx_Comments.Value

            MyWorksheet.Protect , UserInterfaceOnly:=True

            'reset color if there had been an error
            Me.lbl_Date.ForeColor = RGB(0, 0, 0)
            Me.lbl_AC.ForeColor = RGB(0, 0, 0)
            Me.lbl_PType.ForeColor = RGB(0, 0, 0)
            Me.lbl_Attempt.ForeColor = RGB(0, 0, 0)
            Me.lbl_LRate.ForeColor = RGB(0, 0, 0)

            'resets form after entry submit
            UserForm_Initialize
        Else
            'displays red error if not filled out correctly
            If (Me.tbx_Date.Text = "") Then Me.lbl_Date.ForeColor = RGB(255, 0, 0) Else Me.lbl_Date.ForeColor = RGB(0, 0, 0)

            If (Me.tbx_TNumber.Text = "") Then Me.lbl_AC.ForeColor = RGB(255, 0, 0) Else Me.lbl_AC.ForeColor = RGB(0, 0, 0)

            If (Me.cbx_PType.Text = "Select Type") Then Me.lbl_PType.ForeColor = RGB(255, 0, 0) Else Me.lbl_PType.ForeColor = RGB(0, 0, 0)

            If (Me.tbx_Attempt.Value = 0) Then Me.lbl_Attempt.ForeColor = RGB(255, 0, 0) Else Me.lbl_Attempt.ForeColor = RGB(0, 0, 0)

            If (Me.tbx_LRate.Text = "") Then Me.lbl_LRate.ForeColor = RGB(255, 0, 0) Else Me.lbl_LRate.ForeColor = RGB(0, 0, 0)
        End If
    End With

    End Sub
    ________________________________________________________________________
    'checks the checkboxes if additional locations are added
    Private Sub tbx_AA1_Change()
        chk_AA1.Value = True
    End Sub

    Private Sub tbx_AA2_Change()
        chk_AA2.Value = True
    End Sub

    Private Sub tbx_AA3_Change()
        chk_AA3.Value = True
    End Sub

    Private Sub tbx_AMA1_Change()
        chk_AMA1.Value = True
    End Sub

    Private Sub tbx_AMA2_Change()
        chk_AMA2.Value = True
    End Sub

    Private Sub tbx_AMA3_Change()
        chk_AMA3.Value = True
    End Sub

    Private Sub tbx_AMA4_Change()
        chk_AMA4.Value = True
    End Sub

    Private Sub tbx_CMA1_Change()
        chk_CMA1.Value = True
    End Sub

    Private Sub tbx_CMA2_Change()
        chk_CMA2.Value = True
    End Sub

    Private Sub tbx_CMA3_Change()
        chk_CMA3.Value = True
    End Sub

    Private Sub tbx_FMA1_Change()
        chk_FMA1.Value = True
    End Sub

    Private Sub tbx_FMA2_Change()
        chk_FMA2.Value = True
    End Sub

    Private Sub tbx_FMA3_Change()
        chk_FMA3.Value = True
    End Sub

    Private Sub tbx_FA1_Change()
        chk_FA1.Value = True
    End Sub

    Private Sub tbx_FA2_Change()
        chk_FA2.Value = True
    End Sub

    Private Sub tbx_FA3_Change()
        chk_FA3.Value = True
    End Sub

Any help would be greatly appreciated.


text:
Q: Simplex Method issues solving this problem I have an exam coming up so I have been going over math questions in my textbook to practice the simplex method. I ran into an issue with questions like this one, and also any that have more constraints then variables. we haven't gone over the DUAL problem (if that would even help in these cases) so I would like some guidance in solving this problem, thanks.
The Problem
$$
Maximize\: P = 2x_1 - 3x_2 + 4x_3
$$
subject to
$$
    x_1 + x_3 ≤ 4
$$
$$
    x_2 + x_3 ≤ 3
$$
$$
    x_1, x_2, x_3 ≥ 0
$$
The Correct Solution
My solution below is not correct as the book tells me the results should be
$$Max\: P = 17\: at\: x_1 = 4,\: x2 = 3,\: and\: x3 = 0$$
My Solution
My attempted Solution was
$$Max\: P = 14\: at\: x1 = 1,\: x2 = 0,\: x3 = 3$$
How I Tackled the Problem
The steps I took to solve the problem, step one forming the tableau and choosing the pivot point, the pivot point I chose is encircled in ()
$$
\begin{bmatrix}
1 & 0 & 1 & 1 & 0 & 0 & 4 \\
0 & 1 & (1) & 0 & 1 & 0 & 3 \\
-2 & 3 & -4 & 0 & 0 & 1 & 0
\end{bmatrix}
$$
I reduced the rows as I did not need to reduce the pivot point using these functions
-R2 + R1 -> R1
4R2 + R3 -> R3
And then I selected a new pivot point
$$
\begin{bmatrix}
(1) & -1 & 0 & 1 & -1 & 0 & 1 \\
0 & 1 & 1 & 0 & 1 & 0 & 3 \\
-2 & 7 & 0 & 0 & 4 & 1 & 12
\end{bmatrix}
$$
Next I reduced the rows based on the newly selected pivot point using this calculation
2R1 + R3 -> R3
$$
\begin{bmatrix}
1 & -1 & 0 & 1 & -1 & 0 & 1 \\
0 & 1 & 1 & 0 & 1 & 0 & 3 \\
0 & 5 & 0 & 2 & 2 & 1 & 14
\end{bmatrix}
$$
Any help clarifying what could be causing my issues or where I am going wrong would be greatly appreciated, and sorry for the formatting, this was the best I could do given that the html on the site is limited.
Thanks!

A: I don´t see any wrong calculation. But if the optimal value in the textbook is 17, then  objective function should be
$\texttt{Maximize} \  P = 2x_1 \color{red}{+} 3x_2 + 4x_3$
Inserting the optimal value for $x_1, x_2$ and $x_3$:
$2\cdot 4+3\cdot 3+4 \cdot 0=17$
There is, almost sure, a typo in the objective function.


text:
Q: Arrange $16$ bit binary digits into a circle How to arrange $16$ binary digits into a circle, such that the $16$ 4-bit binary numbers will only be present once?

A: Create a directed graph where the nodes are all of the 3-bit binary numbers and an arc goes from a vertex labeled $abc$ to a vertex labeled $xyz$ if $b=x$ and $c=y$.  Label that arc $z$.

This directed graph is strongly connected and every node in this directed graph has the same indegree and outdegree. Therefore, there is a directed Euler circuit in this directed graph. Every such circuit corresponds to a De Bruijn sequence in a pretty obvious way.


text:
Q: Re-use Array to Save Memory I'm working on a C# application that must graph extremely large amounts of data (data set sizes range between a million data points to 30 million data points).
Before graphing, I do linear interpolation to space the points evenly (interpolation is a part of the requirements of the software, so I can't avoid that).  This results in even more data points than the original set (e.g., 1 million points can easily become 1.5 million or more).
In a (foolish?) attempt to conserve memory, I've been interpolating and graphing in chunks.  For example, I set a chunk size of 100,000, so I interpolate the first 100,000 points and graph them, interpolate the second 100,000 points and graph them, so on and so on until all interpolated points have been graphed.
I use two arrays in parallel (representing the x and y values).  The arrays are reallocated before the start of the next chunk.  Unfortunately, for the largest data sets (around 30 million), the program throws an OutOfMemory error.
I was wondering if it's possible to simply reuse the same two parallel arrays, overwriting old values with new values for each chunk?  Is this even a good idea?
Read more on linear interpolation: http://en.wikipedia.org/wiki/Interpolation#Linear_interpolation


text:
Q: NSDate dateFromString returning null when pulling from RSS feed I am parsing a RSS feed in my app and putting each item into a table view cell. One of the pieces I am grabbing is the pubDate, which is a string that looks like this:
Fri, 23 May 2014 10:00:00 GMT
I am using the following code, but the NSDate continues to return null. However, if I manually enter the string (see commented out line) instead of trying to grab the pubDate, it works fine. Any idea what I am doing wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReadingsCell *cell = (ReadingsCell *)[tableView dequeueReusableCellWithIdentifier:@"ReadingsCell"];

    cell.readingLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];
    dateString = [[feeds objectAtIndex:indexPath.row] objectForKey: @"pubDate"];
    //dateString = @"Mon, 19 May 2014 10:00:00 GMT";
    NSLog(@"dateString: %@", dateString);
    //the above logs out perfectly

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

    NSDate *postDate = [[NSDate alloc] init];

    postDate = [dateFormat dateFromString:dateString];

    NSLog(@"pubdate: %@", postDate);
    //this logs out as null

    [dateFormat setDateFormat:@"MMM"];
    NSString *theMonth = [dateFormat stringFromDate:postDate];
    cell.monthLabel.text = theMonth;

    return cell;
}


text:
Q: Spring Data JPA with a custom RepositoryFactory and Multiple EntityManagers I'm currently trying to get Spring Data JPA to work with two DataSources and thus two EntityManagers. My Repositories all inherit from a custom base class "BaseRepositoryImpl".
Problem:
I always get the following exception:
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [javax.persistence.EntityManagerFactory] is defined:
expected single bean but found 2: entityManagerFactory1,entityManagerFactory2

Question:
How can I tell my custom RepositoryFactory which EntityManagerFactory to use?
Here's my Spring configuration:
<jpa:repositories base-package="package1" transaction-manager-ref="..."
  factory-class="MyFactoryBean"
  entity-manager-factory-ref="entityManagerFactory1"/>

<bean id="dataSource1" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="..." />
</bean>

<bean id="entityManagerFactory1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource1" />
  <property name="persistenceUnitName" value="unit1" />
  ...
</bean>

<jpa:repositories base-package="package2" transaction-manager-ref="..."
  factory-class="MyFactoryBean"
  entity-manager-factory-ref="entityManagerFactory2"/>

<bean id="dataSource2" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="..." />
</bean>

<bean id="entityManagerFactory2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource2" />
  <property name="persistenceUnitName" value="unit2" />
  ...
</bean>

The class "MyFactoryBean" is implemented exactly as described at http://docs.spring.io/spring-data/jpa/docs/1.4.x/reference/htmlsingle/#repositories.custom-behaviour-for-all-repositories.
The configuration "entity-manager-factory-ref" seems to be ignored by Spring, at least when using a custom RepositoryFactory.
Any hints?

A: Entity manager factory is used to create entity managers for different persistence units. You declare your entity manager bean and then give entity manager factory bean as it's class.
This is what worked for me:
<tx:annotation-driven transaction-manager="transactionManager" />

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="defaultEntityManager"/>
</bean>

<bean id="defaultDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${hibernate.connection.driver_class}"/>
    <property name="url" value="${db.default.url}"/>
    <property name="username" value="${db.default.username}"/>
    <property name="password" value="${db.default.password}"/>
</bean>

<bean id="defaultEntityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="defaultDataSource"/>
    <property name="persistenceUnitName" value="defaultPersistenceUnit"/>
</bean>

<bean id="otherDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${hibernate.connection.driver_class}"/>
    <property name="url" value="${db.other.url}"/>
    <property name="username" value="${db.other.username}"/>
    <property name="password" value="${db.other.password}"/>
</bean>

<bean id="otherEntityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="otherDataSource"/>
    <property name="persistenceUnitName" value="otherPersistenceUnit"></property>
</bean>

Then when you are implementing your data access classes just declare:
@Repository
@Transactional
public class MyDAOImpl implements MyDAO
{
    @PersistenceContext(unitName = "defaultPersistenceUnit")
    private EntityManager entityManager;
}

and for DAO that uses other persistence unit:
@Repository
@Transactional
public class MyOtherDAOImpl implements MyOtherDAO
{
    @PersistenceContext(unitName = "otherPersistenceUnit")
    private EntityManager entityManager;
}


text:
Q: Calculations and update results in Python data frames I'm a recent convert from excel to python. I think that what I'm trying to here would be traditionally done with a Vlookup of sorts. But I might be struggling with the terminology and not being able to find the python solution. I have been using the pandas library for most of my data analysis framework.
I have two different data frames. One with the weight changes (DF1), and other with the weights(DF2). I want to go line by line (changes are chronological) and:

*

*create a new column in DF1 with the weight before the change
(basically extracted from DF2).

*update the results in DF2 where Weight = Weight + WeightChange

Note: The data frames do not  have the same dimension, an individual has several weight changes(DF1) but only one weight (DF2):
    Name  WeightChange
1   John  5
2   Peter 10
3   John  7
4   Mary  -20
5   Gary  -3

DF2:
    Name  Weight
1   John  180
2   Peter 160
3   Mary  120
4   Gary  150

A: Firstly I'd merge df1 and df2 on the 'Name' column to add the weight column to df1.
Then I'd groupby df1 on name and apply a transform to calculate the total weight change for each person. transform returns a Series aligned to the orig df so you can add an aggregated column back to the df.
Then I'd merge this column to df2 and then it's a simple case of adding this total weight change to the existing weight column:
In [242]:
df1 = df1.merge(df2, on='Name', how='left')
df1['WeightChangeTotal'] = df1.groupby('Name')['WeightChange'].transform('sum')
df1

Out[242]:
    Name  WeightChange  Weight  WeightChangeTotal
0   John             5     180                 12
1  Peter            10     160                 10
2   John             7     180                 12
3   Mary           -20     120                -20
4   Gary            -3     150                 -3

In [243]:
df2 = df2.merge(df1[['Name','WeightChangeTotal']], on='Name')
df2

Out[243]:
    Name  Weight  WeightChangeTotal
0   John     180                 12
1   John     180                 12
2  Peter     160                 10
3   Mary     120                -20
4   Gary     150                 -3

In [244]:
df2['Weight'] = df2['Weight'] + df2['WeightChangeTotal']
df2

Out[244]:
    Name  Weight  WeightChangeTotal
0   John     192                 12
1   John     192                 12
2  Peter     170                 10
3   Mary     100                -20
4   Gary     147                 -3

EDIT
To address your desired behaviour for the 'WeightBefore' column:
In [267]:
df1['WeightBefore'] = df1['Weight']  + df1.groupby('Name')['WeightChange'].shift().cumsum().fillna(0)
df1

Out[267]:
    Name  WeightChange  Weight  WeightBefore
0   John             5     180           180
1  Peter            10     160           160
2   John             7     180           185
3   Mary           -20     120           120
4   Gary            -3     150           150

So the above groups on 'Name', applies a shift to the column and then cumsum so we add the incremental differences, we have to call fillna as this will produce NaN values where we have only a single weight change per Name.