text:
Q: Sorting a list of unique_ptrs The following code will not compile:
bool ptrLess(unique_ptr<int> ptr1, unique_ptr<int> ptr2)
{
   return *ptr1 < *ptr2;
}

int main()
{
   unique_ptr<int> ptr1(new int(3));
   unique_ptr<int> ptr2(new int(2));
   unique_ptr<int> ptr3(new int(5));
   list<unique_ptr<int>> list;

   list.push_back(ptr1);
   list.push_back(ptr2);
   list.push_back(ptr3);

   list.sort(ptrLess);

   for (auto &element : list) {
      cout << *element;
   }

   return 0;
}

I assume this is because unique_ptr's copy constructor is deleted. I get an error like:

error C2280:
  'std::unique_ptr>::unique_ptr(const
  std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to
  reference a deleted function

Is there any way to sort a list of unique_ptr's, perhaps by using the move constructor instead?

A: You should use const ref - after all you don't want to modify those pointers:
bool ptrLess(const unique_ptr<int>& ptr1, const unique_ptr<int>& ptr2)

If your list template is std::list, then passing arguments as r-value references won't work - list::sort would have to call std::move effectively resetting your pointers.
Edit
As for list the rest of your code: std::list has a handy method called emplace_back (and emplace_front) which allows you to construct and append an element in-place:
your_list.emplace_back(new int(2));

A: Try this:
#include <memory>
#include <list>
#include <iostream>
using namespace ::std;

bool ptrLess(unique_ptr<int>& ptr1, unique_ptr<int>& ptr2)
{
   return *ptr1 < *ptr2;
}

int main()
{
   unique_ptr<int> ptr1(new int(3));
   unique_ptr<int> ptr2(new int(2));
   unique_ptr<int> ptr3(new int(5));
   list<unique_ptr<int>> list;

   list.push_back(move(ptr1));
   list.push_back(move(ptr2));
   list.push_back(move(ptr3));

   list.sort(ptrLess);

   for (auto &element : list) {
      cout << *element;
   }

   return 0;
}

The problem here is that you need to understand what a unique_ptr actually aims to be:
When dealing with pointers/references, there are a hell lot of potential problems arising if there are several pointersrs/references referring to the same object.
unique_ptr tries to avoid precisely that.
Therefore, you cannot create 2 unique_ptr referring to the same object.
You cannot use your ptrLess() function because calling it like
   unique_ptr<int> ptr1(new int(3));
   unique_ptr<int> ptr2(new int(2));

   ptrLess(ptr1, ptr2);

because this would mean ptr1 an ptr2 would have to be copied and passed over to ptrLess() - keyword here is 'call-by-value'.
Moreover, you cannot do
   list<unique_ptr<int>> list;
   unique_ptr<int> ptr1(new int(3));

   unique_ptr<int> ptr1(new int(3));

because this too, would have to create a copy of ptr1.
The solution here is to not pass the unique_ptr s to ptrLess as values, but as reference:
bool ptrLess(unique_ptr<int>& ptr1, unique_ptr<int>& ptr2);

And you dont pass copies into the list, but move your object there:
list.push_back(move(ptr1));

keyword here is 'move-semantics'.
This will invalidate the content of your ptr1 variable - the object has been moved out of ptr1 into the list.
I recommend having a look at the Rust language if you are more deeply interested in things like these ;)
As Baum mit Augen pointed out, the parameters to ptrLess better be declared as const:
bool ptrLess(const unique_ptr<int>& ptr1, const unique_ptr<int>& ptr2);

A: Try passing by const ref so it won't copy the parameters :
bool ptrLess(const unique_ptr& ptr1, const unique_ptr& ptr2) { return *ptr1 < *ptr2; }

A: It occurs to me to suggest that if the OP uses shared_ptr instead of unique_ptr then the code as originally posted will otherwise run unchanged:
#include <memory>
#include <list>
#include <iostream>
using namespace ::std;

bool ptrLess(const shared_ptr<int>& ptr1, const shared_ptr<int>&  ptr2)
{
   return *ptr1 < *ptr2;
}

int main()
{
   shared_ptr<int> ptr1(new int(3));
   shared_ptr<int> ptr2(new int(2));
   shared_ptr<int> ptr3(new int(5));
   list<const shared_ptr<int>> list;

   list.push_back(ptr1);
   list.push_back(ptr2);
   list.push_back(ptr3);

   list.sort(ptrLess);

   for (auto &element : list) {
      cout << *element;
   }

   return 0;
}

Run it on Wandbox.
In some senses, this is a consistent way to do things.  push_back would normally copy the object being added to the list, leaving the original object still available to the caller should he or she want to use it.  Using shared_ptr has similar semantics without the overhead of copying the object itself.  Instead, just the shared_ptr is copied, which is a cheap operation.
Also, modifying the OP's original code to move the unique_ptrs into the list is inherently fragile.  They remain in scope to the caller but are no longer usable.  You will get (I assume) a nullptr dereference if you try.  Better then, to do this (note the extra set of braces):
...

list<unique_ptr<int>> list;

{
   unique_ptr<int> ptr1(new int(3));
   unique_ptr<int> ptr2(new int(2));
   unique_ptr<int> ptr3(new int(5));

   list.push_back(move(ptr1));
   list.push_back(move(ptr2));
   list.push_back(move(ptr3));
}

...

Now you are safe.
There, that's a much better post than the original version, sorry about that.


text:
Q: Tidying up the data (Remove br and slashes) I am redesigning a new website and my database table need tidying up a bit.
In the mysql table, I have a data look like this for example:
text text text text - he\'s text text text he\'s text text
text couldn\'t text text.

\"I\'m text text
text text. We\'re text

text text

I need to remove all the slashes () and remove all the . What the best way doing this?
From now on I will use mysql_real_escape_string() when adding data. To view use
nl2br()

A: Ensure that magic_quotes_gpc is off, it's good practice. You can always use parse your database and reinsert it all.
str_replace is right but don't use it if the data has been escaped, use stripslashes on the data.
<?php
    $row = array(
        1 => 'stripslashes removes any unwanted \\\\',
        2 => 'it\'s easy but annoying but we must do it!'
    );
    foreach ($row as $key=>$record) {
        $escaped[$key] = stripslashes($record);
    }
    echo $escaped[1].'
';
    echo $escaped[2];
?>

Outputs:

stripslashes removes any unwanted \
it's easy but annoying but we must do it!

Then re-insert it.

A: you can use str_replace to remove that
http://php.net/manual/en/function.str-replace.php

A: You should use stripslashes() to remove the extra slashes.
To remove the
 tags, do you want to replace them with newline characters? If you've used nl2br, all your
s will still have their new lines characters. If you didn't use nl2br, you'd need something like this, using str_replace():
$text = str_replace("
", "\r\n", $text);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Picture will not appear I am brand new to coding and have not been able to determine why two seemingly identical pieces of code do not work the same. This exercise involves simply making a picture appear on a web page. Easy enough, but I do not see why the same code only works one out of two times.
This code works:

                img class="img-responsive" src="http://pre10.deviantart.net/1d23/th/pre/i/2013/070/1/e/grumpy_cat_by_bwcopy-d5xod2v.jpg"

While this code does not:

                img class="img-responsive" src="https://img.buzzfeed.com/buzzfeed-static/static/2015-04/21/16/enhanced/webdr05/enhanced-31550-1429646952-7.jpg"

I checked the source for the non-working photo and it is valid. (Check it yourself if you like ultra-cute puppies).
What am I not seeing? (besides the puppy picture, obviously).
Thanks.

A: You are not using the img tag, you are just writing plain text.
Change to this (notice the brackets):

First and 2nd code snippets look the same, no reason either of them should work.

A: try this

or this:


text:
Q: Convert NSManagedObjects into structs in a "generic" way (Swift) I have a CoreDataStore class which has two generic placeholders and can be used for each entity type in the model. The idea is that it fetches an NSManagedObject subclass (based on one of the generic types) from the store, converts it into the appropriate object (based on the other generic type) and returns that object.
The purpose of this behaviour is so I'm keeping the Core Data aspects encapsulated and avoiding passing NSManagedObject instances all around the app.
Example potential usage
This is purely how the usage might look to further demonstrate what I am trying to achieve.
let personStore = CoreDataStore<ManagedPerson, Person>()
let personData = personStore.fetchSomeObject() // personData is a value type Person

I have the following code, separated over several files but shown here in a modified fashion for simplicity.
import Foundation
import CoreData

// MARK: - Core Data protocol and managed object

protocol ManagedObjectProtocol { }

class ManagedPerson: NSManagedObject, ManagedObjectProtocol {
    var title: String?
}

class ManagedDepartment: NSManagedObject, ManagedObjectProtocol {
    var name: String?
}

// MARK: - Simple struct representations

protocol DataProtocol {
    typealias ManagedObjectType: ManagedObjectProtocol
    init(managedObject: ManagedObjectType)
}

struct Person {
    var title: String?
}

struct Department {
    var name: String?
}

extension Person: DataProtocol {
    typealias ManagedObjectType = ManagedPerson
    init(managedObject: ManagedPerson) {
        self.title = managedObject.title
    }
}

extension Department: DataProtocol {
    typealias ManagedObjectType = ManagedDepartment
    init(managedObject: ManagedDepartment) {
        self.name = managedObject.name
    }
}

class CoreDataStore<ManagedObject: ManagedObjectProtocol, DataObject: DataProtocol> {

    func fetchSomeObject() -> DataObject {
        var managedObject: ManagedObject // fetch an NSManagedObject

        // Error here
        return DataObject(managedObject: managedObject)
    }

}

The error I am receiving is when I try to initialise the struct in fetchSomeObject:

Cannot invoke initializer for type 'DataObject' with an argument list of type '(managedObject: ManagedObject)'

Obviously the compiler can't figure out that the DataObject (which is restricted to types conforming to DataProtocol) can be initialised with a ManagedObject (which is restricted to types conforming to ManagedObjectProtocol) despite it being declared as such in DataProtocol.
Is there any way to achieve this functionality? Additionally is this a reasonable approach or am I completely off the wall with this?
Update
After a bit of digging it seems that Swift generics are invariant which I believe is causing what I'm running into.

A: Think your CoreDataStore again, for example, CoreDataStore<ManagedPerson, Department> doesn't make any sense. Why not? Because the Department is a DataProtocol without problem, but its corresponding typealias  ManagedObjectType is not ManagedPerson.
The reason why your code won't compile is just the same. Here return DataObject(managedObject: managedObject) you can't initialize an DataObject from an armbitary ManagedObject, only a DataObject.ManagedObjectType is acceptable.
So what you need is a type constraint, add this where clause, your code should work:
class CoreDataStore<ManagedObject: ManagedObjectProtocol, DataObject: DataProtocol
    where DataObject.ManagedObjectType == ManagedObject>


text:
Q: Pack/unpack a 3 byte integer in Python with struct.pack I need to send a packet to a system, the problem is the specification states it must conform to the following:
Padding (set to zero) : 1 byte
Packet Length : 3 bytes

For the rest of the implementation, I have been using struct.pack() and struct.unpack(), but there isn't an option for a 3-byte integer.
Is there an easy way of achieving this?


text:
Q: How to have a reference to a Constant but be able to change what the reference is pointing at? I have a lot of C# Code that I have to write in C++. I don't have much experience in C++.
I am using Visual Studio 2012 to build. The project is an Static Library in C++ (not in C++/CLI).
I have a class with some static instances that I want other classes to use. I don't want anyone to be able to change the instances themselves, but I want the other classes to be able to use the different instances indistinctively.
What is the correct way to accomplish this in C++? Can I use references (&)? Do I have to use pointers? If I use Pointers, do I have to allocate my class with "new"? or can I use automatic allocation?
In case what I want is not clear, this code would theorically have what I want, but it doesnt build:
C++ MyClas.h // This is my class with static instances
class MyClass
{
private:
    std::string name;

public:
    MyClass(void);
    MyClass(string name);
    MyClass(const MyClass&);

    ~MyClass(void);
    std::string GetName(){return name;}

    static const MyClass& Instance1();
    static const MyClass& Instance2();
};

C++ MyClas.cpp
MyClas::MyClas(void)
{
}

MyClas::MyClas(string name)
{
    this->name = name;
}

MyClas::MyClas(const Unit& unit)
{
    name = unit.name;
}

MyClas::~MyClas(void)
{
}

const MyClas instance1= MyClas("Instance1");
const MyClas& MyClas::Instance1()
{
    return instance1;
}

const MyClas instance2= MyClas("Instance2");
const MyClas& MyClas::Instance2()
{
    return instance2;
}

How I would like to use it (this doesn't build though)
c++ MyOtherClass.h //This class uses MyClass instances
class MyOtherClass
{
protected:
    const MyClass& myInstance;

public:
    MyOtherClass(void);
    ~MyOtherClass(void);
    void Swap(const MyClass& myInstance);
};

c++ MyOtherClass.cpp
MyOtherClass::MyOtherClass(void): myInstance(MyClass::Instance1())
{
}

MyOtherClass::~MyOtherClass(void)
{
}

void MyOtherClass::Swap(const MyClass& instance)
{
    myInstance = instance; //Here it fails because I want to modify a const.
                            //I want to change my code so I only have 1 instance
                            //Instance1 and 1 Instance2 of MyClass, buy MyOtherClass
                            //can reference either without modifying them.
}

A:
Do I have to use pointers?

Yes.

I don't want anyone to be able to change the instances themselves

So you want a pointer to const, to prevent modification of the pointer's target object.

do I have to allocate my class with "new"?

No, pointers can point to any object of a suitable type.

or can I use automatic allocation?

Of course:
thing t1, t2;
thing const * p = &t1;  // points to t1
p = &t2;                // points to t2

A: Yes, you have to use pointers.  No, you don't need dynamic allocation, or even automatic allocation.  Your current objects using static allocation have addresses too, which you get using the & address-of operator.
const MyClass* myInstance;

MyOtherClass::MyOtherClass(void): myInstance(&MyClass::Instance1())

void MyOtherClass::Swap(const MyClass& instance)
{
    myInstance = &instance;
}


text:
Q: Strange position when dragging I found a function on this website (http://www.authorcode.com/swap-elements-when-drag-one-onto-another-using-jquery-ui/) for drag and swap, I made some modifications, but I am having a problem, when I drag the item A or D them aper in a strange position, because I change the margin, how can I change those items positions when draging?
The code is this:

$(function() {
        $("#dragdiv li,#dropdiv li").draggable({
            appendTo: "body",
            helper: "clone",
            revert: "invalid"
        });

        initDroppable($("#dropdiv li,#dragdiv li"));
        function initDroppable($elements) {
            $elements.droppable({
                activeClass: "ui-state-default",
                hoverClass: "ui-drop-hover",
                accept: ":not(.ui-sortable-helper)",

                over: function(event, ui) {
                    var $this = $(this);
                },
                drop: function(event, ui) {
                    var $this = $(this);
                    var linew1 = $(this)

                    var li1 = $('
' + ui.draggable.text() + '
')
                     linew1 = $(this).after(li1);

                    var linew2 = $(ui.draggable)
                    var li2 = $('
' + $(this).text() + '
')
                     linew2 = $(ui.draggable).after(li2);

                    $(ui.draggable).remove();
                    $(this).remove();

                    initDroppable($("#dropdiv li,#dragdiv li"));
                    $("#dragdiv li,#dropdiv li").draggable({
                        appendTo: "body",
                        helper: "clone",
                        revert: "invalid"
                    });
                }
            });
        }
      });
.ui-draggable-dragging{
      text-align: center;
      width:200px;
      height: 15px;
      color:black;
    }
    .ui-draggable, .ui-droppable{
      list-style:none;
    }
    #dragdiv li,#dropdiv li{
      border: 2px solid rgb(0,0,0);
      text-align: center;
      color: black;
      width:180px;
      height: 15px;
    }
    #dragdiv li{
      margin-bottom: 40px;
    }
    #dropdiv li{
      display: inline-block;
    }
    #allItems, #Ul1{
      padding: 0px;
      margin: 0;
    }
    #dragdiv{
      position: absolute;
      left: 50%;
      top: 50%;
      margin-top:-187px;
      margin-left:-90px;
      width:204px;
      height:374px;
    }
    #dropdiv{
      position: absolute;
      left: 50%;
      top: 50%;
      width:500px;
      height:19px;
      margin-left: -250px;
      margin-top: -9.5px;
    }
    #item_d{
      margin-top:100px;
    }
    #item_h{
      margin-left: 125px;
    }
    #dragdiv li:hover, #dropdiv li:hover{
      border:2px solid #fff;
    }

Item A

Item B

Item C

Item D

Item E

Item F

Item G

Item H


text:
Q: javascript event not registered I get a strange behaviour. In a web page i import some script and i define some js function.

When i click on a button i display a dialog (this block)
I took some info from the server... and insert it in the bookInfoBlock area
Finally i got

  <button type="button" id="addBook1">+</button>

        <button type="button" id="addBook2">+</button>

$('[id^=addBook]').click(function() {
  alert("book test");
});

When i click on button with addBook1, i see the alert... but not when i click on addBook2.
It's like this last one don't know the event and javscript

A: It looks like you're loading addBook2 dynamically via ajax. In that case use event delegation using .on(). If the div bookInfoBlock is static & is present in DOM all the time, use this.
$('#bookInfoBlock').on('click', '[id^=addBook]'), function() {
  alert("book test");
});

or if you're not sure about the static parent, use this
$(document.body).on('click', '[id^=addBook]'), function() {
  alert("book test");
});

As of jQuery 1.7, the .live() method is deprecated and removed completely in version 1.9. For older versions use .live() instead of on()
$('[id^=addBook]').live('click', function() {
  alert("book test");
});

A: You can use delegate instead of click .
live isn't more used, there is delegate :
$(document).delegate('[id^=addBook]','click', function() {
  alert("book test");
});


text:
Q: put vertical scrollbar in luwit form how can we put vertical scroll bar in lwuit form.
I have tried setScrollableY(true) method but it doesn't work.
My Code is here.
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionListener;

public class ChangePWD extends Form {

    private Label lblold,  lblnew1,  lblnew2;
    private TextField txtOldPwd,  txtNewpwd1,  txtNewpwd2;
    private Command cmdClose,  cmdSave;

    ChangePWD() {
        super("Change Password");
        setScrollableY(true);
        lblold = new Label("Enter Old Password");
        txtOldPwd = new TextField("");
        txtOldPwd.setConstraint(TextField.PASSWORD);

        lblnew1 = new Label("Enter New Password");
        txtNewpwd1 = new TextField("");
        txtNewpwd1.setConstraint(TextField.PASSWORD);

        lblnew2 = new Label("Confirm New Password");
        txtNewpwd2 = new TextField("");
        txtNewpwd2.setConstraint(TextField.PASSWORD);

        cmdClose = new Command("Close");
        cmdSave = new Command("Save");

        addCommand(cmdSave);
        addCommand(cmdClose);
        addComponent(lblold);
        addComponent(txtOldPwd);
        addComponent(lblnew1);
        addComponent(txtNewpwd1);
        addComponent(lblnew2);
        addComponent(txtNewpwd2);

    }

    public static ChangePWD createChangePWD(ActionListener l) {
        ChangePWD p = new ChangePWD();
        p.addCommandListener(l);
        return p;
    }

    public Command getSave() {
        return cmdSave;
    }

    public Command getClose() {
        return cmdClose;
    }

    public String getTxtOldpwd(){
        return txtOldPwd.getText();
    }

    public String getTxtNewpwd1(){
        return txtNewpwd1.getText();
    }
    public String getTxtNewpwd2(){
        return txtNewpwd2.getText();
    }
}

If you have any idea then suggest me.
Thank You.

A: Add
setHeigth(1) ;

before
setScrollableY(true) ;

This worked for me. I still don't understand why actually.
Yannik


text:
Q: Compiling SuiteSparse in Ubuntu, breaks when installing CHOLMOD I've downloaded the .zip for SuiteSparse from the following GitHub. I'm trying to install/compile the C/C++ libraries in Ubuntu. I'm using the Windows Subsystem for Linux and installed Ubuntu from the Microsoft Store.
The SuiteSparse instructions say to cd to the SuiteSparse-5.5.0 directory and just type make. Makefile here. The readme suggests that I need make, g++, gcc, and cmake, so I've installed those using sudo apt install <package name>. Here's the error message I get from make 2>error:
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/csr.c: In function 'gk_csr_Normalize':
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/csr.c:1344:9: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
    else if (norm == 1)
         ^~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/csr.c:1346:11: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'
           for (j=ptr[i]; j<ptr[i+1]; j++)
           ^~~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/csr.c:1371:9: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
    else if (norm == 1)
         ^~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/csr.c:1373:11: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'
           for (j=ptr[i]; j<ptr[i+1]; j++)
           ^~~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/getopt.c: In function 'gk_getopt_internal':
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/getopt.c:343:5: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
     if (gk_optind == 0)
     ^~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/getopt.c:345:7: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'
       optstring = gk_getopt_initialize (argc, argv, optstring);
       ^~~~~~~~~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/getopt.c:700:2: warning: this 'else' clause does not guard... [-Wmisleading-indentation]
  else
  ^~~~
/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/metis-5.1.0/GKlib/getopt.c:703:4: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'else'
    nextchar = NULL;
    ^~~~~~~~
ar: creating libsuitesparseconfig.a
cc1: warning: command line option '-Woverloaded-virtual' is valid for C++/ObjC++ but not for C
ar: creating libamd.a
ar: creating libbtf.a
ar: creating libcamd.a
ar: creating libccolamd.a
ar: creating libcolamd.a
ar: creating libcholmod.a
/usr/bin/ld: cannot find -llapack
/usr/bin/ld: cannot find -lopenblas
collect2: error: ld returned 1 exit status
make[3]: *** [/mnt/c/Users/Anshu/path/to/SuiteSparse-5.5.0/lib/libcholmod.so.3.0.13] Error 1
make[3]: *** Waiting for unfinished jobs....
make[2]: *** [library] Error 2
make[1]: *** [all] Error 2
make: *** [go] Error 2

I've turned off my antivirus, which had been preventing the makefile from writing in some folders. What might be going wrong? It seems like the makefile tries to install a bunch of libraries starting with CHOLMOD, and gets stalled while doing that. I've read some related questions. The first one doesn't seem to apply here since I didn't change PATH, and the second one suggests using Metis which I'm already doing.

A: Install LLAPACK and OpenBLAS development libraries. On Ubuntu the command is:
sudo apt install liblapack-dev  libopenblas-dev


text:
Q: Explain please the following statement from Naive Set Theory Here is a statement that I can't understand:

Ordered triples, ordered quadruples, etc., may be defined as families whose
  index sets are unordered triples, quadruples, etc.

For now, let's stick with the ordered triples. First of all I can't understand whether the index set is a set of unordered triples like $\{ \{a, b, c\}, \{d, e, f\}\}$ or it is itself an unordered triple?
Also, I just can't imagine how having any of such sets as the index set can help me to build a set of ordered triples. Maybe some example will make things clear. I will be very grateful if you help. Thanks in advance.

A: Yes, this is a bit unclear.
Halmos' goal is to define the notion of an arbitrary Cartesian product. This should generalize the usual Cartesian product of two sets, $A\times B$, but should "work for any number of sets." Before diving into his description, let me point out that this really is nontrivial: how should we think of the Cartesian product of "$\mathbb{R}$-many" sets?
Halmos is about to tell us, essentially, that the Cartesian product of an indexed family $\{X_i\}_{i\in I}$ of sets is just the set of all indexed families $\{x_i\}_{i\in I}$ of objects with $x_i\in X_i$. Maybe more clearly, an element of the Cartesian product is a function with domain $I$; it sends $i\in I$ to the "$i$th coordinate," which must be in $X_i$.

To motivate this, Halmos has us go back to the idea of a Cartesian product. We can rethink Cartesian products as follows:

*

*Fix any two distinct sets, $a$ and $b$. We'll think of the first as "LEFT" and the second as "RIGHT."

*Now an ordered pair has two "coordinates," a left coordinate and a right coordinate. We're going to match these up with $a$ and $b$ above: if I have a function $z$ with domain $\{a, b\}$ such that $z(a)=x\in X$ and $z(b)=y\in Y$ (here I write "$z(i)$" for Halmos's "$z_i$"), we want to think of the object $z$ as being the ordered pair $(x, y)$. Informally, $z$ says
$$\mbox{My left coordinate is $x$, and my right coordinate is $y$.}$$
Put another way:

We can think of the ordered pair $(x, y)$ as the function with domain $\{a, b\}$ (which is an unordered pair) mapping $a$ to $x$ and $b$ to $y$.

This is easiest to think about if $a=0$ and $b=1$, or something similar, but Halmos's point is that all we need is that the index set has two distinct elements. Now here's the key linguistic step Halmos makes which I think is confusing at first:

An ordered pair is an indexed set! And the indexing set is $\{a, b\}$, which is an unordered pair.


text:
Q: Accessing class members on a NULL pointer I was experimenting with C++ and found the below code as very strange.
class Foo{
public:
    virtual void say_virtual_hi(){
        std::cout << "Virtual Hi";
    }

    void say_hi()
    {
        std::cout << "Hi";
    }
};

int main(int argc, char** argv)
{
    Foo* foo = 0;
    foo->say_hi(); // works well
    foo->say_virtual_hi(); // will crash the app
    return 0;
}

I know that the virtual method call crashes because it requires a vtable lookup and can only work with valid objects.
I have the following questions

*

*How does the non virtual method say_hi work on a NULL pointer?

*Where does the object foo get allocated?

Any thoughts?

A: The object foo is a local variable with type Foo*. That variable likely gets allocated on the stack for the main function, just like any other local variable. But the value stored in foo is a null pointer. It doesn't point anywhere. There is no instance of type Foo represented anywhere.
To call a virtual function, the caller needs to know which object the function is being called on. That's because the object itself is what tells which function should really be called. (That's frequently implemented by giving the object a pointer to a vtable, a list of function-pointers, and the caller just knows it's supposed to call the first function on the list, without knowing in advance where that pointer points.)
But to call a non-virtual function, the caller doesn't need to know all that. The compiler knows exactly which function will get called, so it can generate a CALL machine-code instruction to go directly to the desired function. It simply passes a pointer to the object the function was called on as a hidden parameter to the function. In other words, the compiler translates your function call into this:
void Foo_say_hi(Foo* this);

Foo_say_hi(foo);

Now, since the implementation of that function never makes reference to any members of the object pointed to by its this argument, you effectively dodge the bullet of dereferencing a null pointer because you never dereference one.
Formally, calling any function — even a non-virtual one — on a null pointer is undefined behavior. One of the allowed results of undefined behavior is that your code appears to run exactly as you intended. You shouldn't rely on that, although you will sometimes find libraries from your compiler vendor that do rely on that. But the compiler vendor has the advantage of being able to add further definition to what would otherwise be undefined behavior. Don't do it yourself.

A: Dereferencing a NULL pointer causes "undefined behaviour", This means that anything could happen - your code may even appear to work correctly. You must not depend on this however - if you run the same code on a different platform (or even possibly on the same platform) it will probably crash.
In your code there is no Foo object, only a pointer which is initalised with the value NULL.

A: It is undefined behaviour, but most compilers generate instructions which will handle this situation correctly if you access neither member variables nor the virtual table.
Let's see the disassembly generated by Visual Studio to understand what happens:
   Foo* foo = 0;
004114BE  mov         dword ptr [foo],0
    foo->say_hi(); // works well
004114C5  mov         ecx,dword ptr [foo]
004114C8  call        Foo::say_hi (411091h)
    foo->say_virtual_hi(); // will crash the app
004114CD  mov         eax,dword ptr [foo]
004114D0  mov         edx,dword ptr [eax]
004114D2  mov         esi,esp
004114D4  mov         ecx,dword ptr [foo]
004114D7  mov         eax,dword ptr [edx]
004114D9  call        eax

As you can see Foo:say_hi is called as a normal function, but with this in the ecx register. To simplify you can assume that this is passed as implicit parameter, which is never used in your example.
But in the second case the address of the function must be calculated, due to the virtual table - this requires that the address of foo is valid and causes a crash.

A: a) It works because it does not dereference anything through the implicit "this" pointer. As soon as you do that, boom. I'm not 100% sure, but I think null pointer dereferences are done by RW protecting first 1K of memory space, so there is a small chance of nullreferencing not getting caught if you only dereference it past 1K line (ie. some instance variable that would get allocated very far, like:
 class A {
     char foo[2048];
     int i;
 }

then a->i would possibly be uncaught when A is null.
b) Nowhere, you only declared a pointer, which is allocated on main():s stack.

A: It's important to realize that both calls produce undefined behavior, and that behavior may manifest in unexpected ways. Even if the call appears to work, it may be laying down a minefield.
Consider this small change to your example:
Foo* foo = 0;
foo->say_hi(); // appears to work
if (foo != 0)
    foo->say_virtual_hi(); // why does it still crash?

Since the first call to foo enables undefined behavior if foo is null, the compiler is now free to assume that foo is not null. That makes the if (foo != 0) redundant, and the compiler can optimize it out! You might think this is a very senseless optimization, but the compiler writers have been getting very aggressive, and something like this has happened in actual code.

A: The call to say_hi is statically bound. So the computer actually simply does a standard call to a function. The function doesn't use any fields, so there is no problem.
The call to virtual_say_hi is dynamically bound, so the processor goes to the virtual table, and since there is no virtual table there, it jumps somewhere random and crashes the program.

A: The say_hi() member function is usually implemented by the compiler as
void say_hi(Foo *this);

Since you don't access any members, your call succeeds (even though you are entering undefined behaviour according to the standard).
Foo doesn't get allocated at all.

A: In the original days of C++, the C++ code was converted to C. Object methods are converted to non-object methods like this (in your case):
foo_say_hi(Foo* thisPtr, /* other args */)
{
}

Of course, the name foo_say_hi is simplified. For more details, look up C++ name mangling.
As you can see, if the thisPtr is never dereferenced, then the code is fine and succeeds. In your case, no instance variables or anything that depends on the thisPtr was used.
However, virtual functions are different. There's a lot of object lookups to make sure the right object pointer is passed as the paramter to the function. This will dereference the thisPtr and cause the exception.


text:
Q: Animate Train in iphone I want to animate a 20 wagon train in iphone. The train will move left to right. Each wagon will have a different animation. I was confused how to do it. Because the images are large and 20 images at one time would cause memory warnings.
Can anyone suggest how to go about it. Should I use cocos2d for this?
Thanks!

A: I would do that in cocos2d.
I would create a 'Wagon'-class and then start by initiate two of them (just because I think that two wagons will fill the screen). And then start moving the wagons. Each time a wagon is completely out of the screen I would release it. When it's time for the next wagon I would initiate that and so on.
How many frames does the animations have, and how big are they? Maybe you'll have to make one atlas per wagon. You can always call:
[[CCTextureCache sharedTextureCache] removeUnusedTextures];

and:
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];

A: Cocos2D is best!
Create sprites, set actions to it and IMHO!!!
If you want to do using UIImageViews, look for
UIImageView.animationImages
UIImageView.animationDuration
UIImageView.animationRepeatCount

and
[UIView beginAnimations:(NSString *)animationID context:(void *)context];
[UIView setAnimationDuration:(NSTimeInterval)duration]

// make the changes in your view which you want to occur in given duration

[UIView commitAnimations];

But again, this will definitely give you a hard time, better go for Cocos2D.


text:
Q: jQuery: How can i replace some text by another text in a $('#myId').attr('value') of a textarea? How can i replace some text by another text in a $('#myId').attr('value') of a textarea ?
I tried something like this :
$(function() {
    var selection;
    var replaceStr;

    var prependStr = "";
    var appendStr = "";

    var temp = "";

    $('input[type="button"]').click(function() {
        if($(this).attr('id') == 'underline')
        {
            prependStr = "";
            appendStr = "";
        }
        else if($(this).attr('id') == 'italic')
        {
            prependStr = "";
            appendStr = "";
        }
        else if($(this).attr('id') == 'bold')
        {
            prependStr = "";
            appendStr = "";
        }
        else if($(this).attr('id') == 'center')
        {
            prependStr = "";
            appendStr = "";
        }
        else if($(this).attr('id') == 'link')
        {
            prependStr = "";
            appendStr = "";
        }
        else if($(this).attr('id') == 'img')
        {
            prependStr = "";
        }
        else if($(this).attr('id') == 'h1')
        {
            prependStr = "
";
            appendStr = "
";
        }
        else if($(this).attr('id') == 'h2')
        {
            prependStr = "
";
            appendStr = "
";
        }
        else if($(this).attr('id') == 'h3')
        {
            prependStr = "
";
            appendStr = "
";
        }

        $('#page').focus();
        selection = window.getSelection();

        if(selection != '')
        {
            replaceStr = prependStr+selection+appendStr;

            temp = $('#page').attr('value');
            temp.replace(selection, replaceStr);//Not working

            $('#page').attr('value', temp);
        }
    });

});

The whole code is working, exept the function .replace(). I googled a lot of things, but i didn't found a function to do this on a $('#page').attr('value').

A: Have a look at this link.
temp.replace(selection, replaceStr) does not change the variable "temp". It returns a new string.
Do sth like this:
temp = temp.replace(selection, replaceStr);
$('#page').attr('value', temp);

A: $('#page').attr('value'); returns a string, and strings are inmutable, that means when you do temp.replace(selection, replaceStr); it doesn't actually change the string object, all it does is create another string object, so it doesn't change the value of the textarea.
Yo could get what you want with
var textarea = $('#page');
textarea.val(textarea.val().replace(selection, replaceStr));

By the way, jqueryElement.val(value) is the equivalent to jqueryElement.attr('value', value) wich is used to set the value.


text:
Q: Pandas - using isin to return if column contains any values in a list, rather than all Sorry for a somewhat basic question, pretty new to python / pandas.
I'm trying to create a column from my database that returns True or False as to whether another column contains any (not all) string from a list of strings. Currently my code looks like this:
keywords_list = ["foo, bar, ..etc]

df['relevant'] = df['Description'].isin(keywords_list)

I know that my 'Description' column contains some of the values in the list, but it is returning all as false. I've looked at similar stackoverflow questions (see below), and they all say to do what I am doing. But the pandas documentation (also below) says that isin only works if it contains all the values in the list. Is there a function I can use that will return if the column includes any of the values in the list? Please help!
Filter out rows based on list of strings in Pandas
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html

A: Use pandas.Series.str.contains
df['Description'].str.contains('|'.join(keywords_list))

A: You may have to separate the words using split and then use isin
df = pd.DataFrame({'Description': ['foo bar blah', 'new foo', 'newfoo', 'bar']})
keywords_list = ["foo", "bar"]

df['Description'].str.split(expand = True).isin(keywords_list).any(1)

0     True
1     True
2    False
3     True


text:
Q: Added method to a concern, but getting undefined method errors I have the following code in a rails concern:
module DestroyExclusion
  extend ActiveSupport::Concern

  def self.destroy_exclusion_on_category_deletion(academy_id,product_id,category_id)
    if(category_id == nil)
      if exists?(:academy_id => academy_id, :product_id => product_id)
        where(:academy_id => academy_id, :product_id => product_id).first.destroy
      end
    elsif(product_id == nil)
      if exists?(:academy_id => academy_id, :category_id => category_id)
        where(:academy_id => academy_id, :category_id => category_id).first.destroy
      end
    end

  end
end

which is used in these classes:
class ExcludeProduct < ActiveRecord::Base
  include DestroyExclusion
  belongs_to :academy
  belongs_to :product

end

class ExcludeCategory < ActiveRecord::Base
  include DestroyExclusion
  belongs_to :academy
  belongs_to :category

end

However, when I try to call the method, I get an undefined method error.
Any ideas why this may be? Here is an example of where I am calling the method:
  def destroy_exclusions
    category_record = Category.find(self.category_id)
    if !self.product_id.blank?
      academies = category_record.parent_academies
      academies.each do |academy|
        ExcludeProduct.destroy_exclusion_on_category_deletion(academy.id, self.product_id,nil)
      end
    else
      products = category_record.child_products
      products.each do |product|
        ExcludeProduct.destroy_exclusion_on_category_deletion(self.academy_id, product.id,nil)
      end
    end
  end

here is an example of the error I am getting (from running my specs):
 1) AcademyCategoryProduct successfully destroys exclusions
     Failure/Error: category_product.destroy_exclusions
     NoMethodError:
       undefined method `destroy_exclusion_on_category_deletion' for #<Class:0x007fc532c0ae50>
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.6/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
     # ./app/models/academy_category_product.rb:13:in `block in destroy_exclusions'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.6/lib/active_record/relation/delegation.rb:46:in `each'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.6/lib/active_record/relation/delegation.rb:46:in `each'
     # ./app/models/academy_category_product.rb:12:in `destroy_exclusions'
     # ./spec/models/academy_category_product_spec.rb:25:in `block (2 levels) in <top (required)>'

The specfile in question:
require 'rails_helper'

describe AcademyCategoryProduct do

  let(:product) { FactoryGirl.create(:academy_product) }
  let(:category) { FactoryGirl.create(:category) }
  let(:subcategory) {FactoryGirl.create(:category, :parent_id => category.id)}
  let(:academy) { FactoryGirl.create(:academy) }
  let(:category_product) { FactoryGirl.create(:academy_category_product, :category_id => subcategory.id, :product_id => product.id, :academy_id => nil) }
  let(:academy_category) { FactoryGirl.create(:academy_category_product, :category_id => category.id, :academy_id => academy.id, :product_id => nil ) }
  let(:exclude_product) { FactoryGirl.create(:exclude_product, :product_id => product.id, :academy_id => academy.id) }
  let(:exclude_category) { FactoryGirl.create(:exclude_category, :category_id => subcategory.id, :academy_id => academy.id) }

  before(:each) do
    category.reload
    academy.reload
    exclude_category.reload
    exclude_product.reload
    category_product.reload
    academy_category.reload
    exclude_product.reload
  end

  it "successfully destroys exclusions" do
    category_product.destroy_exclusions
    expect(ExcludeProduct.first).to eql(nil)
  end

  it "successfully destroys category exclusions" do
    academy_category.destroy_category_exclusions
    expect(ExcludeCategory.first).to eql(nil)
  end
end

EDIT - I made the following changes to my concern as per goddamnyouryan's answer:
require 'active_support/concern'
module DestroyExclusion
  extend ActiveSupport::Concern

  class_methods do

    def self.destroy_exclusion_on_category_deletion(academy_id,product_id,category_id)
      if(category_id == nil)
        if exists?(:academy_id => academy_id, :product_id => product_id)
          where(:academy_id => academy_id, :product_id => product_id).first.destroy
        end
      elsif(product_id == nil)
        if exists?(:academy_id => academy_id, :category_id => category_id)
          where(:academy_id => academy_id, :category_id => category_id).first.destroy
        end
      end
    end
  end
end

but I get the following error:
Users/karuna/Documents/Projects/catalog/app/models/concerns/destroy_exclusion.rb:5:in `<module:DestroyExclusion>': undefined method `class_methods' for DestroyExclusion:Module (NoMethodError)

A: You need to nest these methods in a class_methods do block.  See the documentation for ActiveSupport::Concern
Something like:
module DestroyExclusion
  extend ActiveSupport::Concern

  class_methods do
    def destroy_exclusion_on_category_deletion(etc)
      # omitted
    end
  end
end

A: If you want to define class methods inside your concern:
For Rails version < 4.2.0,
module DestroyExclusion
  extend ActiveSupport::Concern

  module ClassMethods
    def destroy_exclusion_on_category_deletion(etc)
      # some code
    end
  end
end

For Rails version >= 4.2.0
module DestroyExclusion
  extend ActiveSupport::Concern

  class_methods do
    def destroy_exclusion_on_category_deletion(etc)
      # some code
    end
  end
end

Ruby way of doing thing
module DestroyExclusion
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def destroy_exclusion_on_category_deletion(etc)
      # some code
    end
  end
end

A: In Rails 4 (and Rails 5), if you want to define a class method inside your concern, then you have to just define that method inside a:
module ClassMethods
 . . .
end

which is what you are looking for. The code contained within this module ClassMethods block will be added to the Class itself.
So, your modified concern code should look like this:
module DestroyExclusion
  extend ActiveSupport::Concern

  module ClassMethods
    def destroy_exclusion_on_category_deletion(academy_id,product_id,category_id)
      if(category_id == nil)
        if exists?(:academy_id => academy_id, :product_id => product_id)
          where(:academy_id => academy_id, :product_id => product_id).first.destroy
        end
      elsif(product_id == nil)
        if exists?(:academy_id => academy_id, :category_id => category_id)
          where(:academy_id => academy_id, :category_id => category_id).first.destroy
        end
      end

    end
  end
end

This tutorial has a simple and nice explanation about concerns in Rails 4!

A: I had a similar issue, and K M Rakibul Islam's answer was 99% right, but I had to include the following method in my model concern to get ClassMethod working for me.
def self.included(base)
   base.extend(ClassMethods)
end

Thanks @K-M-Rakibul-Islam, this was a big headache for me!


text: Q: My cutscenes on black ops 3 are pixelated with graphic content enabled So my graphic content is enabled but I my cutcenes become pixelated at times when things get "graphic". Does anyone know why, and how to fix it?


text:
Q: how to properly format checkboxes. (best for jquery and crossbrowser) I've seen lots of ways. And I remember I had some problems make it crossbrowser and retrieve checkbox state with jQuery.
from html checked to checked="true" and checked="1" and even checked=checked or checked="yes"
now... once for always. What is the best way for crossbr. check/uncheck and make jquery finally work
getting/changing state?

A: The checked attribute is a boolean attribute. It takes one value, and one value only: checked. This has not changed in HTML 5.
checked="checked"

If you are writing HTML (as opposed to XHTML) then you may provide just the value.
         checked

In JavaScript, the checked property can be assigned the values true or false. Any other value will be converted (e.g. "checked" is a string, so it converted according to the rules for converting strings and becomes true).

A: I usually do this to check if it's checked and i never had problems:
$('#chk').click(function(){
    $('#show').toggle($(this).is(':checked'));
});

and this to check/uncheck it (jquery 1.6 or higher):
$('#button').click(function(){
    var chk = $('#chk')
    if(chk.is(':checked')){
        chk.prop('checked', false);
    }else{
        chk.prop('checked', true);
    }

});

To check or uncheck with jquery you should always use prop() since it's specifically targeted at properties.
in pure html the correct way i think is (of course omit checked if you don't want the checkbox to be checked):
 <input id='chk' type='checkbox' checked value='1'>

fiddle: http://jsfiddle.net/TTWVd/2/

A: This is actually very simple and jQuery has just confused everyone.

*

*In HTML use either checked with no value or checked="checked".

*In XHTML (although it's very unlikely you should actually use it), use checked="checked".

In JavaScript, the checkedness of a checkbox is represented in every scriptable browser in the simplest possible way: a Boolean property. So, given the HTML
<input id="foo" type="checkbox" checked>

... you can get its checked state as follows:
var checkbox = document.getElementById("foo");
alert(checkbox.checked);

... and set it as follows:
checkbox.checked = false;

That's it.
jQuery provides the advantage of being able to handle multiple elements in one call. In jQuery 1.6 and later you do this with prop(). In earlier versions, use attr().
$("#foo").prop("checked", false);

Don't try and deal with the attribute directly: simply use the checked property and you'll never go wrong. This goes for pretty much all attributes when dealing with HTML.

A: As far as I'm concerned, so long as the checked attribute exists the box should be ticked, even if you proceed to set the value as false, checked="false", example.
However, I usually use checked="checked", and I've never had an issue with cross browser inconsistencies.
However, the MDN documentation suggests using boolean values as strings (it that makes sense). However with my above example, in FireFox 5 checked="false" still checked the element.

A: In JavaScript, the property is a boolean. In HTML, the property will be "checked" (this can also be shown in W3 standards -- note the (checked) (booleans in HTML will generally be their property names can't find the W3 ref. on that one, but it is true)).


text:
Q: What is the best way to restrict access to adult content? I bought my kids a PC and installed 12.04 (Unity) on it.  The bottom line is, I want my children to use the computer unsupervised while I have confidence they cannot access anything inappropriate.
What I have looked at:
I was looking at Scrubit a tool which allows me configure my wifi router to block content and this solution would also protect my other PC and mobile devices.  This may be overkill as I just want the solution to work on one PC.
I also did some Google searches and came across the application called Nanny (it seems to look the part).  My experience of OSS is that the best solutions frequently never appear first on a Google search list and in this case I need to trust the methods therefore my question is very specific.
I want to leverage your knowledge and experience to understand What is the best way to restrict adult content on 12.04 LTS as this is important to me.  It maybe a combination of things so please don't answer this question "try this or that", then give me some PPA unless you can share your experience of how good it is and of course if there are any constraints.

A: I took the advice of the selected answer to this question and used OpenDNS on my Ubuntu computer but I wanted to share more information to be helpful to others.
What is OpenDNS, and how to get OpenDNS?
OpenDNS is a free DNS service that can not only speed up your internet but also provide you options like...

*

*Web content filtering

*anti-phishing,

*malware protection

*smart cache and much more.
The bottom line is OpenDNS servers have a huge collection IP addresses of millions of web pages. When you look for a website, it immediately finds the corresponding IP address and hence gets it to load faster.   It's intuitive and literally takes less than 10 minutes to set up (no software installation required)
To utilize all its features, all you need to do is sign-up with them here.  Basic OpenDNS is suitable for your household devices is free of cost. (For business solutions there is a nominal annual fee)
Once you have signed up, you'll get a confirmation link in your mailbox. Click on the link and it will redirect you to dashboard settings on the main website.
It will automatically detect your IP address. Click on Add this network button given below your IP address  All you need to now is to follow the Instructions provided on the website and add these IP addresses to your router.
Preferred DNS server: 208.67.222.222
Alternate DNS server: 208.67.220.220

That's it! You're done
OpenDNS features
By default, nothing is blocked. You have FULL control to select one of 3 pre-sets 1: Low 2: Moderate or 3: High filtering levels
Example: If you choose "Low" filtering level then all the porn sites will be blocked . You increase the filter level to apply more restrictions.  There is also a custom filtering levels that allows you to be specific or tweak one of the pre-sets.
You can block or allow any domain of your choice by entering the domain name. It also gives you the ability to add an extra layer of security as it provides malware and botnet protection as well as phishing protection. You may also block internal IP addresses.
Important note of caution:
I have been using OpenDNS for a couple of weeks now and I created a Bookmark in Firefox. Stupidly I clicked on "Remember my Password" which means anybody can click on the bookmark get into OpenDNS and make changes.  I have since rectified.

A: *

*Check your Internet history files.
This will tell you if your children are visiting any inappropriate sites. In your web browser, click on the history tab. It should open up as a sidebar. Once this happens, you can check to see what sites your children are visiting. Take note of any that you want to block.

*Adjust your privacy settings.
In most browsers, the privacy tab is located under Internet options (or options), which is located under the tools tab. Once in the website section, copy the sites that you want to block from the history page, and enter them into the block site space. You can block one site at a time this way. However, in order to block sites that your children have never visited before, you will need to take other steps.

*Purchase a site-blocking software package.
This will give you the additional security option of blocking any site that may have potentially harmful content from your children. Many of these programs not only block harmful sites, but also are used as a way to see exactly what your children are doing online or on the computer in general. Install the program and set the level of security you want. Usually these programs can be customized to fit your needs.

*Check the software and your Internet history after your child uses the computer.
If any inappropriate activity is going on, talk to your children about it in a calm manner. If you freak out, your child will try to hide things from you even more.

*Place the computer in a well-used area where you can visually keep track of what the children are doing.
If the computer is in the same room as you, your children are much less likely to do anything inappropriate. Limit Internet time as much as possible and set clear boundaries for appropriate use.

A: One easy and great way of doing it is going straight to the source and use DNS filtering for that purpose.
Let's face it, you cannot protect your children all the time from all the internet risks, but using some sort of filtering you can at least force it in your home.
One of the advantages of filtering using DNS is that even if you have a smart ass kid that knows he can bypass blocking software installed in his system using the Ubuntu LiveCD, DNS usage can be enforced in the system that use DHCP via your router.
Have a look at a DNS parental control option like OpenDSN Family Shield or Cloudflare 1.1.1.1 for Familiesfor an example on how a DNS filter would work for your computers at home. Many other DNS servers will allow you to do it, OpenDNS is just one that I use normally.
Set up an account, make the changes in your router to use the DNS servers from OpenDNS, activate parental filtering and no matter what OS your kids are using that obtain an IP via the router will be blocked from accessing issue sites.
Of course if your kids are smart enough and know how to spoof that it will be easy for them to bypass it, that again, as said before, you won't be able to protect your children all the time from all the dangers the internet presents.

A: The Internet is not a safe place for kids
We all know of content we don't want our kids to be exposed to, be it either accidentally or on purpose. We therefore have to do something about it. There are different approaches to gain some security but all fail when it comes to the details. Let me explain why:
Allow list / Whitelists
Whitelists securely block unwanted content and can be generated by a variety of browser plugins or parental control software but they will not last for long. We want our kids to discover the world, to learn how to operate the Internet, to learn how to find information, and to learn how to play games that are safe for them. They will not learn how to do this if they only have access to a small list of sites granted by Daddy where the next click on a button leads to the "BANNED" page. Only very young kids may be happy for some months with a whitelist.
Deny list / Blacklists
Blacklists such as offered e.g. by DNS services are meant to contain all known bad sites and block them. This task is ridiculous. We can not possibly know of all bad sites. They pop up everyday in thousands. The makers of Dansguardian filters put it like that:

The web is a fast changing place and even large web search engines such as Google or Altavista or Yahoo don't even know of half of it. This makes filtering by web address (URL) difficult as sites change and new ones come up all the time.

Content Filters
To overcome limitations of a blacklist we additionally need some sort of content filtering but it is tedious to maintain the filters. This may be good for schools when a full time employee does all the work but it is unlikely we find the time at home to do so. Using pre-made filters is likely a bad idea as the bad sites know about them and avoid those suspicious phrases to appear on their pages (look at the spam mail you get and you have an idea on how they do it).
Smart Kids
As already mentioned kids become smart, and we desperately want them to become so. Unortunately then they will also learn how to overcome most of our filters. They will (yes, they will, no matter what we do)  gain access to anything they want by the time they are smart. All our blocking efforts will fail by then. Before that however they may not be interested in all that adult stuff at all. So there would in reality not be a need to block anything. By the time they are smart they need to be smart enough to know what is a bad site, and they should be smart enough to be interested in other things rather than visits on adult pages.
Smart Parents
We all are or will be smart parents. We want to teach our kids how to operate Ubuntu and how to discover the Internet. Smart parents watch what their kids do and they talk to them about what they do. We should provide them with the knowledge on what to do when they come to sites that are different or may be harmful. We want our kids to tell us what they do. Smart parents spent the time they would need to set up and maintain a parental control rather with their kids. We also should not leave the kids alone. Put the computer to a place where you can pass by and have a short look what is displayed on the screen.
In summary the "best" way to refrain our kids from visiting unwanted sites is to become a smart parent educating their kids to become smart. But I know from my own experience that this also may fail, has inconsistencies, and may likely not achieve 100% safety. It still is the best.

Note after seven years: We never had any content filters in all those years. I can see now how important all I said above was to our kids.

A: In addition to OpenDNS there are Parental Control Systems that are an easy way to control what your kids are doing in the computer.

*

*You can limit how much time a day each one of them is browsing the
web,  chatting or doing email.

*You can decide at which times of the day they can do this things as
well.

*You can block all undesirable webs and have your kids  enjoy the
internet with ease of mind, no more worries!

The Binary package "Nanny" for ubuntu Precise (12.04) can be found here
OR
You can install the debs package from here
Note:
Experienced Linux users can also try DansGuardian along with content caching using squid3
.

A: Depending on your religious persuasion maybe try Christian Ubuntu flavour which when I was researching Ubuntu flavours had this as an inbuilt feature which they advertise.

A: An alternative solution would be to setup a Pie Hole server at home, here is a complete tutorial on how to do just that.
http://www.ubuntuboss.com/how-to-install-piehole-on-ubuntu-16-04/
Pi Hole is a nifty open source project that allows you to offload the task of blocking advertisements and annoying (and often malicious) trackers to a Raspberry Pi or in this case an Ubuntu Server. The installation is really simple and it is basically a dns server that can be configured via a simple Web Interface with multiple block lists from around the Web.

A: Use MoralDNS (https://github.com/RoelVdP/MoralDNS).
Full disclosure; I am the maintainer.


text:
Q: How to disable terminal fullscreen padding When I run vim at full screen mode in gnome-terminal, actually it is not really full screen.
There is a little padding on the right and bottom, with the terminal background color.
You can reach the original image to see it more clearly.

How to fix this?

A: You can't make vim inside the terminal actually full screen, unless you're lucky enough that both the width and the height are multiples of the cell size (plus the fixed UI chrome taken into account).
The terminal is a text grid, and if you force it to a maximized size which doesn't match this grid then there's necessarily a margin which is inaccessible to vim.
You probably don't realize it with xterm because xterm's background color is the same black as vim's background color; whereas gnome-terminal's is different.

A: I don't know about the CLI version, but there's the gVim VullScreen addon on Github that's pretty nice.
Before:

After:

There's still the problem of the right scrolling bar.
Alternatively you can use xTerm but you'll have to patch it and compile it yourself, here's the link.
Another option yet would be to use a tty terminal by using the CTRL+ALT+F1 to F6 shortcut, but that's not probably what you were looking for.

A: A partial solution.
This will fix the right side padding issue, possibly only for some versions of Gnome.
In a custom theme create tweak the gtk style  gtk-3.0/gtk.css with the following:
/**
 * Fixes some padding issues in Vim + Terminal
 * -----------------------------------------------------------------------------
 */

VteTerminal,
TerminalScreen {
    border: none;
    padding: 0 0 0 0;
    margin: 0 0 0 0;
    -VteTerminal-inner-border: 0 0 0 0;
}

Full guide

*

*Install gnome-tweak-tool: sudo apt-get install gnome-tweak-tool

*Create a file named .themes/galactica/gtk-3.0/gtk.css put the css shown above in it.

*Open the Tweak Tool and set the shell theme to "Galactica".

*Restart


text:
Q: Escape HTML tags in XAML code How can escape html tags into a xaml code?
For example, if i want to show text in an xaml content to put into a RichTextBox as following:
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        string mystring = "test";
        MyRTB.Blocks.Add(Convert(@"<Bold>" + mystring + "</Bold>"));
    }

        static public Paragraph Convert(string text)
    {
        String formattedText = ParaHead + text + ParaTail;
        Paragraph p = (Paragraph)XamlReader.Load(formattedText);
        return p;
    }

I tried with multiple combinations of {} and {} and etc but doesnt work, and I dont want use hexa scape if i can do it.
Thanks in advance

A: You just need to XML-escape it by replacing < with <.
The built-in SecurityElement.Escape or WebUtility.HtmlEncode functions will do that for you.


text:
Q: Evenly space for x-ticks in Matplotlib I need to plot a graph like this style, where the x-ticks have evenly space in the range of [0.1, 1, 10, 100, 1000].

My code looks like this:
x = np.array([0.3081, 1.2, 29.4, 29.4, 54.7, 29.4, 14.7, 7.8, 54.7, 68.0])
y =np.array( [94.92, 94.85, 92.61, 93.44, 94.86, 92.57, 94.88, 93.64, 94.99, 95.40])

plt.plot(x, y, 'b.')
plt.xticks(np.array([0.1, 1, 10, 100]))
plt.grid(True)
plt.show()

which generates a plot like this:

Any help or suggestions would be greatly appreciated!

A: You can use a matplotlib.pyplot method xscale and pass 'log' as an argument:
import numpy as np
import matplotlib.pyplot as plt

x = np.array([0.3081, 1.2, 29.4, 29.4, 54.7, 29.4, 14.7, 7.8, 54.7, 68.0])
y = np.array([94.92, 94.85, 92.61, 93.44, 94.86, 92.57, 94.88, 93.64, 94.99, 95.40])

plt.plot(x, y, 'b.')
plt.xticks(np.array([0.1, 1, 10, 100]))
plt.xscale('log')
plt.grid(True)
plt.show()


text:
Q: React-router: how to obtain a reference to the router in a rendered component? React-router is rendering my component 'App'. (This is version 1.0.0 of react-router).
I need to get a reference to the router from inside 'App'. Is this possible?
The reason that I need to do this is because 'App' is rendering Breadcrumbs - which is an instance of react-breadcrumbs v. 1.0.2 - and react-breadcrumbs expects the router to be on this.content. (It looks like react-breadcrumbs is expecting Router to have done this). Anyhow; I've figured out how I can set context from App (using childContextTypes and getChildContext) but I can't see how I can get a reference to the router in the component it is rendering.

A: You can use contexts (a currently undocumented feature of React, but one that seems likely to stay for the time being):
module.exports = React.createClass({
  displayName: 'App',
  contextTypes: {
    router: React.propTypes.func
  },
  render: function() {
    var { router } = this.context;

    // Do things with the router. Ex: getting a parameter
    var userId = router.getCurrentParams().userId;
  }
});

A: You can add Router.History mixin to your App and then access the routes through this.props.routes.
Here is an example:
var React = require("react");
var Router = require("react-router");
var Breadcrumb = require("react-breadcrumbs");

var App = React.createClass({
   mixins: [
      Router.History
   ],

   render: function () {
      "use strict";

      return (

          <Breadcrumb routes={this.props.routes}></Breadcrumb>

              {this.props.children}

);
   }
});

module.exports = App;


text:
Q: Proof of Wilson's theorem via finite fields? $(p-1)! = -1 \bmod p$ where $p$ is prime.
I know that there are a lot of ways to prove it with all beauty of different sides of math:
1) Elementary way (to divide in pairs where $x_1 x_2 = \pm 1$)
2) To use Fermat's little theorem and Lagrange theorem with try to prove $x^{p-1} - 1 = (x-1)\dots(x-(p-1)))$
But my teacher wants me to prove it using theory of the finite Galois Fields. He wants me to use material which we study now.
We studied on our last lectures:

*

*A set of residue classes

*The decomposition field of the polynomial $x^{p^m} - x$

*Cyclicity of the multiplicative group of the field

*Giving the field by the root of an irreducible polynomial

*Structure of finite fields

*Isomorphism of the Galois fields

*Automorphism of the Galois field

*Representation of the Galois field by matrices

Maybe this proof is on this site, but I can't find it. And I can't think of proof based on things that I mentioned.
Sorry if it is some kind off-topic.
But does anybody know other proof based on mentioned material?
Hint from teacher: consider constant term of $x^{p-1} -  1 $, but it can't be the second proof, because it is based on theory of groups at all,  the previous chapter of our lectures, not the theory of the finite Galois field, current chapter of our lectures.

A: By Vieta's Formulas we know that the constant term of a polynomial is equal to the product of the roots of the polynomial when the degree is even, and the negative of that when the degree is odd. Since $\mathbb{F}_p^\times$ is cyclic of order $p-1$, any non-zero element of $\mathbb{F}_p$ satisfies $x^{p-1}-1=0$. Handling the $p=2$ case separately, we see that $p$ is odd so $p-1$ is even, so $-1$ is the product of all the roots of $x^{p-1}-1$. We have already observed $p-1$ unique roots to this equation, and since $\mathbb{F}_p$ is a field, it has exactly $p-1$ roots and so the roots are precisely the the non-zero elements with no repeats and we are done.
In the comments, it is mentioned that this holds not just in $\mathbb{F}_p$ but generally in $\mathbb{F}_q$. This proof generalizes because, by construction, the elements of $\mathbb{F}_q$ satisfy $x^q-x=0$. Dividing both sides by $x$ and continuing as stated in the above proof yields the result. In the general theorem, the $p=2$ case still needs to be handled separately and is less trivial.
NB: This is the same concept as your proof 2, but justified using language of Field Theory. In general, the boundary between "Galois Theory Concepts" and "number theory concepts" is pretty loose when it comes to Modular Arithmetic.

A: My guess is that you may be expected to use cyclicity of $\Bbb{F}_p^*$. Let $g$ be a generator of this cyclic group of order $p-1$. Then there are two ways of listing the elements of the multiplicative group (in different orders):
$$
\Bbb{F}_p^*=\{1,2,3,\ldots,p-1\}=\{1,g,g^2,\cdots,g^{p-2}\}.
$$
This implies that in $\Bbb{F}_p$ we have
$$
\begin{aligned}
(p-1)!&=1\cdot2\cdot3\cdots(p-1)\\
&=1\cdot g\cdot g^2\cdots g^{p-2}\\
&=g^{0+1+2+3+\cdots+(p-2)}.
\end{aligned}
$$
In the last form the exponent is
$$
E=\sum_{j=0}^{p-2}j=\frac12(p-2)(p-1).
$$
Because $p$ is odd, we see that $E$ is an odd multiple of $(p-1)/2$.
On the other hand, by cyclicity, $g^{(p-1)/2}$ is of order two. As $-1$ is the only element of order two, we thus have
$$
W:=g^{(p-1)/2}=-1,
$$
and
$$
g^E=W^{p-2}=(-1)^{p-2}=-1.
$$


text:
Q: NodeJS - how to make a process to auto restart when issue occurs? I am running some application in NodeJS that retrieves data from a database and serve at port 3000.
It is running fine most of the time but sometimes it just errors out (it could be too many connections or network issue or some sql injection etc.). This happens every 2-3 days randomly.
While I am figuring out root cause - what is the best way to have NodeJS always 'ON' - meaning if it stops running - some process kicks it and it starts again?

A: You can use forever as stated by the previous answer, but as I've worked with forever before, I'd suggest using the pm2 process manager. It has, on top of what you need, some more advanced functionalities and is well-documented.

A: Try this:
forever start -w <filename>
-w is for watch. it watches the file changes and restarts if any changes found.
Also, if the script is unexpectedly stopped, it will try to restart it.
forever list for details of the process.
you will see the PID, filename, log filename.
in the log file, you can see the log of your script.
Hope it helps. :)


text:
Q: Java connecting JDBC to Dynamic Web App I have run into a problem that I have been trying to figure out for days:
I added my driver: mysql-connector-java-5.1.40.jar to build path.
web-inf lib folder, apache tomcat lib folder. And also I have it in web app libaries.
However when I just run a main class and run it works, it is something to do with the web app?
This is my code:
This is the servlet class, that I use to connect to my database
package sql;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private DbUtil sql = new DbUtil();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String email = request.getParameter("email");

        String username = request.getParameter("username");

        String password = request.getParameter("password");

        if (sql.addToAccountToDatabase(username, password, email)) {

            System.out.println("Gongratz");

        } else {

            System.out.println("mhhh ?");
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */

}

this is the second class how i make connection
package sql;

import java.sql.*;

public class DbUtil {

    public Connection getConnection() {

        Connection connect = null;

        try {

            String url = "jdbc:mysql://hidden:3306/hidden";

            connect = DriverManager.getConnection(url, "hidden", "hidden");
            return connect;

        } catch (Exception e) {

            System.out.println("Cannot connect to database");
            e.printStackTrace();

        }

        return connect;

    }

    public boolean addToAccountToDatabase(String username, String password, String email) {

        try {

            String query = "INSERT INTO Account (username, password, email) VALUES (?, ?,?)";
            PreparedStatement pStat = getConnection().prepareStatement(query);
            pStat.setString(1, username);
            pStat.setString(2, password);
            pStat.setString(3, email);
            pStat.executeUpdate();
            return true;

        } catch (Exception e) {

            System.out.println("User already exists");

            e.printStackTrace();
            return false;

        }

    }

}

And I get this error:
Cannot connect to database
java.sql.SQLException: No suitable driver found for jdbc:mysql://192.185.227.214:3306/ratekas9_illegalminds
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at sql.DbUtil.getConnection(DbUtil.java:15)
    at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
    at sql.RegisterServlet.doPost(RegisterServlet.java:40)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
User already exists
java.lang.NullPointerException
    at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
    at sql.RegisterServlet.doPost(RegisterServlet.java:40)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
mhhh ?

A: Because the String "jdbc:mysql" doesn't declare the driver Class itself, but only the name registered by a potential driver. You have to force the JVM to load the Driver class with a :
Class.forName("com.mysql.jdbc.Driver").newInstance();

before starting the JDBC connection.

A: You need 3 steps to solve your problem:

*

*Add this code before connection Class.forName("com.mysql.jdbc.Driver");

*Add 'JConnector.jar' into your project and build path.

*Don't try enter same person because there is error in stack trace "User all ready exist ".

A: Adding the JAR file into your CLASSPATH (for compilation needs) / project's BUILDPATH and also under your project's WEB-INF/lib folder (for runtime references, i.e., when you deploy your application to an application server). For further reference, please go through this link
Class.forName("com.mysql.jdbc.Driver");

This is no longer required as per Official Java documentation here, but it is a mandatory step if you are using prior versions of JDBC 4.0.
This question can provide you lot many details on this regards.
Hope all these details help you resolve your issue!


text:
Q: Relative path of image not working in angular cli First of all I am new to Angular, and I have never faced this kind of issue in simple MVC. I am working on it from last 4 hours and still not resolved.

I want to use below marked image in my HTML.

my angularcli.json file looks like this.

and this is how I am accessing the image.

any kind of help appreciated.

A: Change your angular-cli.json to
"assets": [
    "assets",
    "favicon.ico"
  ],

and use the following


text:
Q: HTML-formatted emailing in Codeigniter How can I send a formatted email in codeigniter? I have this code which is sending email fine, but it is not formatting it as it should. You can see the picture which displays email received:

function email_sender()
        {
            //      $this->load->helper('form');
            // $this->load->helper('url');
            $config = Array(
                    'protocol' => 'sendmail',
                    'smtp_host' => 'ssl://smtp.gmail.com',
                    'smtp_port' => '465',
                    'smtp_timeout' => '7',
                    'smtp_user' => '****@****.com',
                    'smtp_pass' => '*******',
                    'charset' =>'utf-8',
                    'newline' => "\r\n",
                    'MIME-Version' => '1.0',
                    'mailtype' => 'html',
                    'header' => 'MIME-Version: 1.0',
                    'header' => 'Content-type:text/html;charset=UTF-8'
                );//initializing mail headers and information
            if ($this->input->post('submit')==true)
            {
            $data['name']=$this->input->post('contact-name');
            $data['email']=$this->input->post('contact-email');
            $data['phone']=$this->input->post('contact-tel');
            $data['country']=$this->input->post('contact-country');
            $data['message']=$this->input->post('exampleTextarea');
            }//input from form
            $html_formattedEmail = $this->load->view('includes/email_template', $data, TRUE);//variable that loads view and save it as string
            $this->load->library('email', $config);
            // $this->email-> set_newline("\r\n");
            $this->email->from('abc@abc.com');
            $this->email->to($data['email']);
            $this->email->subject('Contact form submitted');
            $this->email->message($html_formattedEmail);

            if($this->email->send()){
                $data['main_content'] = 'thankyou_page';
                 $data['meta_title'] = 'abc';
                    $data['meta_description'] = 'abc2';
                     $data['meta_author'] = 'abc3';
            $this->load->view('includes/template', $data);

            }
            else{
                show_error($this->email->print_debugger());
            }
        }

A: Try this
// load email library
$this->load->library('email');

// prepare email
$this->email
    ->from('ex@example.com', 'Example Test.')
    ->to('toex@example.com')
    ->subject('Hello Sample Test.')
    ->message('Hello, We are Htl content')
    ->set_mailtype('html');

// send email
$this->email->send();

You can also use a view file
$this->email
    ->from('ex@example.com', 'Example Test.')
    ->to('toex@example.com')
    ->subject('Hello Sample Test.')
    ->message($this->load->view('email_template-name', $dynamic-data, true))
    ->set_mailtype('html');

A: You can try this line of code, which will set mail type to HTML:
$this->email->set_mailtype("html");

A: $config = Array(
    'mailtype' => 'html'
);

Add this to your mail config and recheck.

A: In CodeIgniter 4.1.1
This should work, but is completely ignored:
$email_config = [
  'mailType' => 'html'
];
$email->initialize($config);

So after you've loaded the Altmessage in you can use this completely undocumented function:
$email->setMailType("html");

and then load your html version message in as you normally would - which I'd not have been able to guess without the other answers provided on this page.


text:
Q: SQL Developer bind variables prompt: force string values I'm trying to use SQL Developer bind variables prompt to speed up query execution, but I'm not getting the desired output: looks like the values I put in get converted in number.
Table description:
Nome               Null     Type
------------------ -------- ------------
NUM                NOT NULL VARCHAR2(13)
IS_OK                       NUMBER(1)

initial situation:

select NUM, IS_OK from numbers_table where NUM = cast(:dn as varchar2(13));

NUM         |IS_OK |
------------|------|
08331930078 |1     |

working updates:
1.
update numbers_table set IS_OK = 0 where NUM = 08331930078;

*

update numbers_table set IS_OK = 0 where NUM = '08331930078';

ouput:
'1 row updated'

non-working updates:
1.
update numbers_table set IS_OK = 0 where NUM = :dn;

*

update numbers_table set IS_OK = 0 where NUM = cast(:dn as varchar2(13));

output:
'0 rows updated'

Don't know what else can I do to force the value being parsed as a string.
SQL Developer version 4.1.3.20

A: That's interesting, and looks like a bug. You don't actually need to cast, the value from the 'enter binds' window is a string anyway, so this works:
update numbers_table set IS_OK = 0 where NUM = :dn;

when the zero-padded string 08331930078 is entered in the dialog.
The cast is not needed but ought to still work. If you run as a script instead, with a defined bind variable, then both forms do work:
var dn varchar2(13);
exec :dn := '08331930078';
update numbers_table set IS_OK = 0 where NUM = :dn;
rollback;
update numbers_table set IS_OK = 0 where NUM = cast(:dn as varchar2(13));
rollback;

You get 1 row updated for both statements. Going back to running as a statement still prompts and still has the same (odd) behaviour even when the bind variable has been defined in a script in the same session.
Incidentally, when you do:
update numbers_table set IS_OK = 0 where NUM = 08331930078;

what you're actually doing, as you can see form the execution plan's predicate section, is:
update numbers_table set IS_OK = 0 where to_number(NUM) = 8331930078;

which will stop any index on the num column being used, and may result in unexpected results - in this case, if these are e.g. UK phone numbers you probably won't have the same value with and without the leading zero, but it's something to be wary of generally.


text:
Q: How to combine weak classfiers to get a strong one? Let as assume that we have a binary classification problem. We also have several classifiers. Instead of assigning a vector to a class (0 or 1) each classifier returns a probability that a given vector belongs to class 1. It means that for each input vector, that has to be classified we get a vector of real number between 0 and 1. For example:
(0.81, 0.67, 0.43, 0.99, 0.53)

where the number of components (probabilities) is equal to the number of classifiers. Now we want to "combine" these "weak" classifiers to get on "strong" classifier. In other words we need to find a way to map a given vector of probabilities into one number (probability).
So, my questions is: What is the "correct" way to do it? Of course I can train another classifier that uses the vector of probabilities and returns one probability. In other words we can find out how to combine the "weak" probabilities in an empirical way. However, I assume, that we can use the fact that the components of the vector are not just "some numbers" (or features) they are probabilities, they are already predictions and, as a consequence, they have to be combined in a corresponding appropriate way.
ADDED
In comments it has been proposed to average the "weak" probabilities. But what if it is possible to estimate quality (power) of each "weak" classifier (and it should be possible), doesn't it make sense to suppress "bad" classifier (for example by using their predictions (probabilities) with smaller weights or by ignoring them completely)? Does it makes sense to use just one (the best) weak classifier? Does it make sense to check correlation between the weak classifiers. For example what should we do if two "weak" classifiers always give the same result. Shouldn't we through one of them out as not having any additional value?

A: Practically speaking bagging, boosting, and stacking all constitute reasonable ways to combine the weak predictions, as others have mentioned.  Taking that one step further though, trying as many of them as possible and seeing what performs best is common the context of competitive machine learning too (e.g. You might try a stacked classifier as well as well as a simple average ensembler and choose the better of the two as per performance on some hold-out data).
In fact, if accuracy is your only goal then you're likely better off having a few different ensembling techniques in mind like this and focusing on the diversity of the classifiers being ensembled rather than how they're combined.  Since the best ensemble technique will depend on your problem and and data and there is no approach that's always best, your time is better spent just making the ensemble choice another part of the training process rather than worrying about making a single correct choice.
Theoretically speaking though, and as an attempt to answer the question more directly, I think there are some probabilistic arguments that could be used to justify the best way to "suppress" the weak classifiers.  IMO the reasoning behind Bayesian Model Averaging and Information-Criteria-Based Averaging is pretty enlightening and has ties to some of the approaches in Machine Learning like weighting classifiers via binomial deviance.  For example, here's a process for combining classifiers through the use of akaike weights (as an example of information-criteria based model averaging):
** Note this is all assuming the classifiers are pretty well calibrated and that actual out-of-sample deviance is used in cross-validation rather than an estimate of it like AIC
Suppose you have $K$ classifiers fit to training data and each of those classifiers then makes $N$ predictions on test data.  You could then compute the "likelihood" of each models predictions as follows:
$$ L_k = \Pi_{i=1}^n{ P_{M_k}(y_i)}$$
where:

*

*$L_k$ = Likelihood of predictions from model $k$

*$y_i$ = Response $i$ in the test data

*$P_{M_k}(y_i)$ = The probability that classifier $k$ attributes to $y_i$

Given the likelihood of the predicted data, the weight or relative likelihood of each classifier, $w_{M_k}$ could then be defined as:
$$L_{max} = \max{L_k} $$
$$w_{M_k} = \frac{e^{2log(L_{max}/L_k)}}{\sum_{j=1}^{k}{e^{2log(L_{max}/L_k)}}}$$
The weights for each model, $w_{M_k}$, can then be interpreted as the probability that classifier $M_k$ is the true model and an expected outcome coming from an ensemble of all $k$ classifiers would have an expected value equal to the sum of the probability of each classifier times its prediction:
$$ y_{new} = \sum_{j=1}^k { w_{M_k} \cdot M_k(X_{new}) }.$$
I hope the notation doesn't bog you down but the point is that there are theoretical ways (the Bayesian ones are especially interesting) to determine what probability each model in an ensemble should have and then use that to make predictions, rather than some more heuristic weighting or equal-voting scheme.  These more intuitive averaging strategies don't generally perform better in empirical studies (or so it seems), but I thought throwing the notion of them into the mix might help you like they helped me.

A: As you might surmise from the diversity of comments, combining weak learners into strong ones isn't a task with a single, "correct" approach, but a field of approaches with varying levels of known strengths and drawbacks. For a brief introduction, the wikipedia entry for ensemble learning is a reasonable place to start. There you'll find reference to many of the methods discussed in comments, such as averaging predictions or combining them using logistic regression. In particular, here's an excerpt from the section on stacking:

Stacking (sometimes called stacked generalization) involves training a learning algorithm to combine the predictions of several other learning algorithms. First, all of the other algorithms are trained using the available data, then a combiner algorithm is trained to make a final prediction using all the predictions of the other algorithms as additional inputs. If an arbitrary combiner algorithm is used, then stacking can theoretically represent any of the ensemble techniques described in this article, although in practice, a single-layer logistic regression model is often used as the combiner.

The of questions in your edit seem to me best answered in individual cases using cross-validation. Whether @Tim's suggestion of inverse-error-weighted mean performs better than @yasin.yazici's logistic regression will, I suspect, vary depending on the algorithms and dataset. Will a single-layer neural net using the classifications features produce good results? Could be, as neural nets can learn non-linear functions. Maybe it will learn that when two of the probabilities agree, they're nearly always right, and produce a hidden layer node that weights these two very highly.
But until you try those and compare them, who knows? Thankfully, cross-validation provides a means of comparing each of those approaches for a given, practical problem.

A: Combining weak learners into a strong one is exactly what boosting is designed for.
Boosting is a specific example of ensemble method.
"Improved Boosting Algorithms Using Confidence-rated Predictions" is a popular algorithm (over 3000 citations) that uses the confidence of the weak  learner.
Note that there is a big difference between the regular use of boosting and your problem. In regular boosting, you have the ability to train a weak learner on the data set of your choice. The boosting algorithm deals with building the proper data sets and combining the data set.
Here, you are already given the weak learners. If you can train new learners, you can ignore those you already have and use boosting in the regular way.
Otherwise, since the weak learners are known, you might be able to aggregate them in a better way by treating them as regular features and build a classifier on top of them.


text:
Q: Online lectures for a first course in mathematical logic I have a friend who is interested in learning math. I suggested that he learns mathematical logic. He has never learnt mathematical logic before, however I believe he has all the necessary prerequisites for a first course in mathematical logic.
I'd like to find good online lectures for a first course in mathematical logic. The lectures should form a complete course.  It would be great if someone can help me.
Thanks a lot.

A:
"I have a friend who is interested in learning math. I suggested that he learns mathematical logic."

I do think that most mathematical logic courses presuppose some "mathematical maturity" (or at least the background knowledge you get from a good introductory logic course). So I rather doubt that math logic, properly so called, would be a good way in to "learning math".
If however you do want some suggestions of introductory logic books, some freely available online, look at early sections of the annotated Guide which can be obtained from http://www.logicmatters.net/tyl/ [And for beginners working by themselves, books will always trump online notes, let alone video courses, as they can be more expansive and detailed in a way beginners need. For example, Stephen Simpson online notes on mathematical logic are predictably excellent, but they are surely too terse as for stand-alone learning -- though they no doubt serve hist student brilliantly to back up his lectures, and will serve others very well as snappy revision material. See http://www.personal.psu.edu/t20/notes/logic.pdf ]
I leave it others to suggest other routes into mathematics.

A: This is a very popular & free Stanford course from Coursera (a MOOC site). Suggested background is only high school mathematics and it consists of not only lectures, but assignments and practice to reinforce the skills you gain.

The goal of the course is to help you develop a valuable mental
ability – a powerful way of thinking that our ancestors have developed
over three thousand years.
Mathematical thinking is not the same as
doing mathematics – at least not as mathematics is typically presented
in our school system. School math typically focuses on learning
procedures to solve highly stereotyped problems. Professional
mathematicians think a certain way to solve real problems, problems
that can arise from the everyday world, or from science, or from
within mathematics itself. The key to success in school math is to
learn to think inside-the-box. In contrast, a key feature of
mathematical thinking is thinking outside-the-box – a valuable ability
in today's world. This course helps to develop that crucial way of
thinking.
The course is offered in two versions. The eight-week-long
Basic Course is designed for people who want to develop or improve
mathematics-based, analytic thinking for professional or general life
purposes. The ten-week-long Extended Course is aimed primarily at
first-year students at college or university who are thinking of
majoring in mathematics or a mathematically-dependent subject, or high
school seniors who have such a college career in mind. The final two
weeks are more intensive and require more mathematical background than
the Basic Course. There is no need to make a formal election between
the two. Simply skip or drop out of the final two weeks if you decide
you want to complete only the Basic Course.

https://www.coursera.org/course/maththink

A: There is "introduction to logic" (https://www.coursera.org/course/intrologic) on Coursera. I have taken this course. It was one of the best courses I have participated in on Coursera.
From the course page:

What should I know to take this class?
The course has no prerequisites beyond high school mathematics. You
  should be comfortable with symbolic manipulation techniques, as used,
  for example, in solving simple algebra problems. And you need to
  understand sets, functions, and relations. However, that's all. If you
  have this background, you should be fine.


text:
Q: Force connection on specific USB port/symlink I am planning to use Dump1090 and I want to have 2 RTLSDR dongles on the same computer, always plugged into the same USB port. I am planning to assign a symlink "adsb" to the port for the RTL dongle that has an ADS-B antenna connected to it. Is there a way to force the connection on this specific USB port?
By default, the code takes the first device available.
Thank you
https://github.com/antirez/dump1090/blob/master/dump1090.c