How do I get the list of nodes of a specific content type and their titles?

Question: A call to field_attach_load should be loading node titles, but they are not being loaded.  Perhaps I am missing something simple, since this my first Drupal hook.
This is the code I am using to query all the published Event nodes and their associated fields.
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'event')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

  // Attach the field values to the nodes.
  $nodes = $results['node'];

  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT);
  var_dump($nodes);

Unfortunately, this code doesn't work for me.
How do I get the list of nodes of a specific content type and their titles?
Comment: May check this link out, has good stuff in it. http://drupal.stackexchange.com/questions/18093/get-only-some-fields-with-entityfieldquery
Comment: Take a step back, what information do you need?  If you are using EntityFieldQuery, why would you want to use field_attach_load?  The point of EntityFieldQuery is to get out of the slow drupal loading process.  What are you trying to achieve?
Comment: I want a list of "event" node ids and their corresponding title.  That is my end goal.
Comment: Also, could you use views to display this?
Answer: PLease try this-
This will load all published nodes of type event.
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
$nids = array_keys($result['node']);

foreach ($nids as $nid) {
$node = node_load($nid, NULL, TRUE);
// do something awesome
 }
}

Comment: Was I misusing field_attach_load?
Comment: No that was not a misuse, actually you need to debug your code for checking out results.
Answer: From the field_attach_load documentation page:

$entities: An array of entities for which to load fields, keyed by entity ID. Each entity needs to have its 'bundle', 'id' and (if applicable) 'revision' keys filled in.

While your array has the required id and is keyed by id, it is missing the bundle for those nodes (in your case 'event').
So you'd either manually add this key to every array item, or use the answer provided by 'Rahul Mishra'. While abit more hard on the database, it highly depends on your use case (row count, frequency, etc.).
Comment: An entity defines which keys contain the entity bundle in [`hook_entity_info()`](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_info/7.x). `field_attach_load()` and every Drupal core functions handling entities don't assume the bundle name is contained in the *bundle* key, so there isn't any need to add a *bundle* key in the array returned from `EntityFieldQuery::execute()`.
Answer: field_attach_load() doesn't load the node title, as that isn't an entity field. It loads the body field and every field created with the Field UI module.
In a Drupal 7 test site, I created two Article nodes and one Page node. I then executed the following code.
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

if (!empty($result['nodes'])) {
  $nodes = $result['node'];
  field_attach_load('node', $nodes);
}

echo '
', print_r($nodes, TRUE), '
';

The output has been the following one.
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 1, before test 2.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 1, before test 2.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 2: the test before Test 3 and Test 4.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 2: the test before Test 3 and Test 4.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
        )
)

The code to get the node title should be similar to the following one.
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

if (!empty($result['nodes'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);
}

In my test site, I get the following output.
Array
(
    [1] => stdClass Object
        (
            [vid] => 1
            [uid] => 1
            [title] => Test 1
            [log] =>
            [status] => 1
            [comment] => 2
            [promote] => 1
            [sticky] => 0
            [nid] => 1
            [type] => article
            [language] => und
            [created] => 1556873868
            [changed] => 1556873868
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1556873868
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 1, before test 2.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 1, before test 2.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
            [rdf_mapping] => Array
                (
                    [field_image] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => og:image
                                    [1] => rdfs:seeAlso
                                )
                            [type] => rel
                        )
                    [field_tags] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:subject
                                )
                            [type] => rel
                        )
                    [rdftype] => Array
                        (
                            [0] => sioc:Item
                            [1] => foaf:Document
                        )
                    [title] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:title
                                )
                        )
                    [created] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:date
                                    [1] => dc:created
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [changed] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:modified
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [body] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => content:encoded
                                )
                        )
                    [uid] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:has_creator
                                )
                            [type] => rel
                        )
                    [name] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => foaf:name
                                )
                        )
                    [comment_count] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:num_replies
                                )
                            [datatype] => xsd:integer
                        )
                    [last_activity] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:last_activity_date
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                )
            [cid] => 0
            [last_comment_timestamp] => 1556873868
            [last_comment_name] =>
            [last_comment_uid] => 1
            [comment_count] => 0
            [name] => admin
            [picture] => 0
            [data] => b:0;
        )
    [2] => stdClass Object
        (
            [vid] => 2
            [uid] => 1
            [title] => Test 2
            [log] =>
            [status] => 1
            [comment] => 2
            [promote] => 1
            [sticky] => 0
            [nid] => 2
            [type] => article
            [language] => und
            [created] => 1556873931
            [changed] => 1556873931
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1556873931
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 2: the test before Test 3 and Test 4.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 2: the test before Test 3 and Test 4.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
            [rdf_mapping] => Array
                (
                    [field_image] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => og:image
                                    [1] => rdfs:seeAlso
                                )
                            [type] => rel
                        )
                    [field_tags] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:subject
                                )
                            [type] => rel
                        )
                    [rdftype] => Array
                        (
                            [0] => sioc:Item
                            [1] => foaf:Document
                        )
                    [title] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:title
                                )
                        )
                    [created] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:date
                                    [1] => dc:created
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [changed] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:modified
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [body] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => content:encoded
                                )
                        )
                    [uid] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:has_creator
                                )
                            [type] => rel
                        )
                    [name] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => foaf:name
                                )
                        )
                    [comment_count] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:num_replies
                                )
                            [datatype] => xsd:integer
                        )
                    [last_activity] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:last_activity_date
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                )
            [cid] => 0
            [last_comment_timestamp] => 1556873931
            [last_comment_name] =>
            [last_comment_uid] => 1
            [comment_count] => 0
            [name] => admin
            [picture] => 0
            [data] => b:0;
        )
)

As side note, for nodes, the following snippets return the same value, in $result['node'].
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

In my test site, in both the cases, echo '
', print_r($result['node'], TRUE), '
'; outputs the following.
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
        )
)

The second snippet is always valid for any entity type (and it is then preferable); the first snippet works only for those entities for which the entity type is stored in a type database field.
For nodes, don't use the following code.
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

It would throw the following exception.

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node.bundle' in 'where clause': SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type AS entity_type FROM {node} node WHERE (node.bundle = :db_condition_placeholder_0) AND (node.status = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => article [:db_condition_placeholder_1] => 1 [:entity_type] => node )

Don't even use the following code.
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('type', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

It would return every node (entity), independently from its content type (bundle). In my test site, the content of $result['node'] with that code is the following.
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
        )
    [3] => stdClass Object
        (
            [nid] => 3
            [vid] => 3
            [type] => page
        )
)


How to have multiple values inside a hidden div in JQuery

Question: I found an example about show/hide methods and I arranged them in a way that the parent div is present in a row with another element. The HTML Code is as follows

Search Results

Youtube Video Scraping

        <select id="inspectionAssignmentSearchForm:assignedSeverityLabel" name="inspectionAssignmentSearchForm:assignedSeverityLabel" class="test-field-styles" size="1">
                <option value="">-- Select Lane --</option>
                <option value="1">Red</option>
                <option value="2">Yellow</option>
        </select>

        <select id="inspectionAssignmentSearchForm:assignedSeverityLabel" name="inspectionAssignmentSearchForm:assignedSeverityLabel" class="test-field-styles" size="1">
                <option value="">-- Select Lane --</option>
                <option value="1">Red</option>
                <option value="2">Yellow</option>
        </select>

JS:
    $(document).ready(function() {
    $("li").click(function(){
        $(this).toggleClass("active");
        $(this).next("div").stop('true','true').slideToggle("fast");
    //li:hover{background:#FFFFE0}
    //li div:hover{text-decoration:none !important;}
    });
});

And style sheet.
     body{font-family:Tahoma;}
    ul{width:450px;}

    li{list-style-type:none; cursor:pointer; -moz-border-radius:0 10px 0 10px;  solid #666666; margin:2px; padding:5px 5px 5px 5px;}
    ul div{color: #666666; cursor: auto; display: none; font-size: 13px; padding: 5px 0 5px 20px; text-decoration: none; }
    ul div a{color:#000000; font-weight:bold;}
    li:after {content: "+"; padding:10px 10px 10px 0; color:red; font-weight:bold;}
    li.active:after {content: "-"; padding:10px 10px 10px 0; color:red; font-weight:bold;}
    #toggle{width:500px; margin:0 auto;}

Now the problem is that when I click the Parent Div, I am getting only one one drop drop box but the other drop down box is not coming.
And also I have to keep the child in such a way that it covers the whole div below, not only below parent div. Can anybody tell me how to proceed further
Comment: Can you create a fiddle because the html seems to be incorrect? There are unclosed tags.
Answer: Just wrap both select with a div and dont make it inside ul since it's invalid.
$(this).next("div") in li.click function is meant to find the div after li. But i suggested to put the div outside of ul so you need to do
$(this).parent().next("div")

Which is gonna find the div after ul
FIDDLE


How to count the total non-distinct many-to-many relationships across objects of a model?

Question: Assume I have the following models:
class Tag(Model):
  name = CharField()

class Book(Model):
  title = CharField()
  tags = ManyToManyField(Tag)

Now suppose I have 3 books, and each book has 3 tags. Some of the tags might be the same for some of the books, it doesn't matter.
Book 1 (Tags = "tag1", "tag2", "tag3")
Book 2 (Tags = "tag1", "tag4", "tag5")
Book 3 (Tags = "tag4", "tag5", "tag6")

How can I count all non-distinct tags in a Django ORM query so that I get 9 as a result?
Answer: You can count with:
Book.tags.through.objects.count()
This will count the number of tags for all Books. If you have a set of Books, you can count with:
Tag.objects.filter(book__in=[1, 2, 3]).count()


IBM System x3500 M3 refuses to boot from LSI SAS card if blank SATA drive is connected on mainboard

Question: Have an IBM System x3500 M3 that refuses to boot from the IBM branded LSI SAS card if any SATA drive is also connected to the mainboard.  The system restarts itself over and over.  No error messages.  Just sits there with a blinking cursor until it restarts, and the process repeats.
Tried changing the boot order, resetting the BIOS to defaults, and nothing helps.  Tried different SATA drive models from IBM/Hitachi and Seagate, blank/without operating systems, and the same thing happens.  If we add a SATA drive with an OS, for example Linux, it boots off the SATA drive and does not boot off the SAS.  (Want it to boot off the SAS.)
Remove the SATA drive(s) and the SAS RAID1 array boots fine.  The SAS drive array is running VMWare ESXi.
Any suggestions?
Answer: After talking with IBM, we found we had an unsupported configuration.  The only drives supported to hang directly off the mainboard are a CD/DVD drive and a tape drive.
IBM recommended we buy an IBM ServeRAID-BR10IL SAS/SATA Controller Card for the SATA drives and make sure the drives are setup within a hot-swap cage (which didn't come with the server) - and that's what we're doing.
Then the BIOS should let us select which controller to boot from.
Comment: We went through the IBM technical sales rep at the distributor we bought the server from.  He wasn't really supposed to give us support like this but went above and beyond to help out, post-sale.  You could try asking for an IBM rep at the company you bought the server from, or google "IBM X series support".  HTH.
Comment: can u tell me where i can ask same question to IBM (or u can give me IBM email?) but my server is IBM series X 3200 M3, i got same problem when try attach sata drive (500gb) to our system it cannot boot from SAS hardrive. Already change all bios configuration same problem ...thanks for advice


React Private Routes are not being redirected and they don't exist

Question: I'm having those troubles about the private route and not being redirected. I'd like to know how to fix this code, please.
This is my App.js
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Switch, Routes, Route, Swit } from 'react-router-dom';
import MasterLayout from '../src/layouts/admin/MasterLayout'

import { Navigate } from 'react-router-dom';

import Dashboard from './components/admin/Dashboard';
import Profile from './components/admin/Profiles';
import Login from './components/frontend/frontend/Auth/Login';
import Register from './components/frontend/frontend/Auth/Register';
import Home from './components/frontend/Home';
import AdminPrivateRoute from './AdminPrivateRoute';

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8000';
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.defaults.headers.post['Accept'] = 'application/json';
axios.defaults.withCredentials = true;

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('auth_token');
  config.headers.Authorization = token ? `Bearer ${token}` : ''
  return config;
}
)

function App() {
  return (

      <Router>

        <Routes>
          <Route path="/" element={<Home />} />

          <Route path="/login" element={localStorage.getItem('auth_token') ? <Navigate to="/" /> : <Login />} >

          </Route>

          <Route path="/register" element={localStorage.getItem('auth_token') ? <Navigate to="/" /> : <Register />} >

          </Route>

              <Route path="/admin/*" element={<AdminPrivateRoute />} >
              </Route>

        </Routes>

      </Router>

  );
}

export default App;

This is my AdminPrivateRoute.js file
import React from 'react'
import { BrowserRouter as Router, Switch, Routes, Route, Swit } from 'react-router-dom';
import MasterLayout from './layouts/admin/MasterLayout';
import { Navigate,Outlet  } from 'react-router-dom';

function AdminPrivateRoute({ ...rest }) {

    return (

            <Routes>

                <Route {...rest}
                    render={({ props, location }) =>
                        localStorage.getItem('auth_token') ?
                            (<MasterLayout  {...props} />) :
                            (<Navigate to={{ pathname: '/login', state: { from: location } }} />)

                    }
                />

            </Routes>

    );
}
export default AdminPrivateRoute;

This is my route.js
import Dashboard from '../components/admin/Dashboard';
import Profile from '../components/admin/Profiles';
import Login from '../components/frontend/frontend/Auth/Login';
import Register from '../components/frontend/frontend/Auth/Register';

const routes = [
{path:'/admin',exact:true,name:'Admin'},
{path:'/admin/dashboard',exact:true,name:'Dashboard',component: Dashboard},
{path:'/admin/profile',exact:true,name:'Profile',component: Profile},
{path:'/admin/login',exact:true,name:'Login',component: Login},
{path:'/admin/register',exact:true,name:'Register',component: Register},

];

export default routes;

I'm following a tutorial about React ( older version) and I'm trying to change to React V6.
Finally, What for is  ...rest, render, locations, state from location? Can someone explain that block of code, in general, to understand what is happening.
Can you guide me, please?
Answer: Your AdminPrivateRoute component is certainly mixing up the older react-router-dom v5 syntax. In RRDv6 private "routes" are written to be wrapper components that render an Outlet (or children if wrapping a single component) or the Navigate component for redirection.
import { Navigate, Outlet, useLocation } from 'react-router-dom';

function AdminPrivateRoute() {
  const location = useLocation();
  return localStorage.getItem('auth_token')
    ? <Outlet /> // <-- nested routes rendered here
    : <Navigate to="/login" replace state={{ from: location }} />;
}

Usage:
<Router>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/login" element={localStorage.getItem('auth_token') ? <Navigate to="/" /> : <Login />}  />
    <Route path="/register" element={localStorage.getItem('auth_token') ? <Navigate to="/" /> : <Register />} />
    <Route element={<AdminPrivateRoute />} >
      {routes.map(({ path, component: Component }) => (
        <Route key={path} path={path} element={<Component />} />
      ))}
    </Route>
  </Routes>
</Router>

Note that the AdminPrivateRoute no longer spreads the rest of the passed props into a rest prop since passing props is no longer necessary. Similarly, the render prop is gone and we don't need to render a Route with the auth wrapper. Lastly, the location is the current location the user is attempting to access. The location is passed in route state to the authentication route so upon successful authentication the user can be redirected back to the original route they were trying access.
Comment: I got an error message when I added that code
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `App`."
 .I'm checking the export of the PrivateAdminRoute and the import of this component in App.Js and It seems ok.   The error is here : "} />" , please, what is missing ?
Comment: @gian I didn't call it out, but when I destructured `component` I also renamed it to `Component` so it was a properly named React component. Is your code doing something similar?
Comment: Yes , I added your code block  "

} />   .....,   etc. in App.Js
Comment: @gian Ok, I'll see if I can reproduce in a CodeSandbox and get back to you.
Comment: @gian Oh, you what, I think it's the missing component on the `"/admin"` path... I meant to filter that out or remove it from the `routes` config. Let me test.
Comment: @gianYes, confirmed (https://codesandbox.io/s/react-private-routes-are-not-being-redirected-and-they-dont-exist-4rucv). It's the route with missing component. You can either remove the entry or add a component to render for that path.


Convert Date(JS) object to TimeStamp(firestore) in Google Apps Script

Question: I've got a date object in Google App Script which I want to import to firestore as a timestamp object, but it doesn't work when I do it directly.
This stores an empty map in firestore:
data.date = new Date();

I get this in firestore:

But I want this:

This is my full code:
function uploadData() {
   var firestore = FirestoreApp.getFirestore (email, key, projectId);
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "Sheet1";
   var sheet = ss.getSheetByName(sheetname);
   var sheetLR = sheet.getLastRow();
   var sheetLC = sheet.getLastColumn();
   var dataSR = 2;
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);
   var sourceData = sourceRange.getValues();
   var sourceLen = sourceData.length;

  // Loop through the rows
   for (var i=0;i<sourceLen;i++){
     if(sourceData[i][1] !== '') {
       var data = {};

       var date = sourceData[i][0]; //this is the date object
       data.date = new Date(); //Want to convert this date to timestamp object for firestore
       data.title = sourceData[i][1];

       firestore.createDocument("collection", data);
     }

  }
}

Answer: Thanks, this bug has been fixed in the latest version.


Interpreting Coefficients of a Linear Model

Question: I'm having difficulty in interpreting the results of a linear model. I have two categorical: States (AK, IL, MO, KS) and Roads (Con, Cem, Mud) and one continuous predictor variable (Days). My response variable is also continuous (index). I'm using a AIC framework for model selection. The model (best) with lowest AIC is as follows:
model<-lm(index ~ State + Roads*Days, data=myDat)

coef(model)

 >(Intercept)                 StateIL
 1.376299e+00               -6.745194e-03
 StateMO                     StateKS
-6.767209e-02                8.852979e-03
 RoadCem                     RoadMud
-3.633496e-01                7.555775e-01
 Days                        RoadCem:Days
-5.365565e-06               -9.961142e-05
 RoadMud:Days
 8.822059e-05

I am wanting to extract the predicted mean for each of the above with respect to intercept which is the predicted mean for StateAK RoadCon at Day 0.
Comment: For categorical variables, the coefficient represents the estimate when that categorical variable takes value 1 (exists). Also, the first value is used as baseline. So, your intercept incorporates StateAK, RoadCon and Day 0 already.
Answer: Coefficients  RoadCem and RoadMud will differ from RoadCon at Day==0 by -3.633496e-01 and 7.555775e-01 respectively. The Days coefficient, -5.365565e-06,  is the amount by which index will decrease for RoadCon cases on each succeeding day. Then the RoadCem:Days coefficient,   -9.961142e-05, is the amount of decrease from that value with each successive day, while RoadMud:Days coefficient, 8.822059e-05, is the amount of increase from the baseline of (1.376299e+00 + 7.555775e-01) on each succeeding day for that type of Road. These three lines will be shifted up or down for the other States by the amount of their respective coefficients.
In R you could construct a set of values that would cover the range of possibilities with expand.grid and give this to the newdata argument of predict.lm. You would be able to plot the lines with matplot.
Comment: Thanks for the fast response. I'm trying to get the predicted mean for each state, for each Road and for each interaction term between Road and Days from the above model. I want to build a plot of predicted mean for each category using plotrix in R with confidence intervals.
Comment: There is no "predicted mean" for an interaction term. This seems obviously the case for models with interactions involving continuous variables, but I would argue that it also applies to interactions that only involve discrete ('factor') variables. The only way to talk about predictions from such models is to construct scenarios of specific values to be compared against each other. This is so because the existence of interactions means that more than one term will be contributing to a prediction. (And I already laid out a plan for building a dataset needed to make an informative plot.)


Unable to connect after reboot in Google Compute Engine

Question: Due to excessive use I had to upgrade my machine which led to a reboot.
After that I'm unable to connect through PuTTY, only using Google console.
Also, my SVN repository is there, and I can't connect to it either.
I looked at the firewall rules in 'VPC Network', and they are the same before the reboot :

The output of iptables -L :
[newuser@google-server ~]$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
INPUT_direct  all  --  anywhere             anywhere
INPUT_ZONES_SOURCE  all  --  anywhere             anywhere
INPUT_ZONES  all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere             ctstate INVALID
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
FORWARD_direct  all  --  anywhere             anywhere
FORWARD_IN_ZONES_SOURCE  all  --  anywhere             anywhere
FORWARD_IN_ZONES  all  --  anywhere             anywhere
FORWARD_OUT_ZONES_SOURCE  all  --  anywhere             anywhere
FORWARD_OUT_ZONES  all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere             ctstate INVALID
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
OUTPUT_direct  all  --  anywhere             anywhere

Chain FORWARD_IN_ZONES (1 references)
target     prot opt source               destination
FWDI_trusted  all  --  anywhere             anywhere
FWDI_trusted  all  --  anywhere             anywhere

Chain FORWARD_IN_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain FORWARD_OUT_ZONES (1 references)
target     prot opt source               destination
FWDO_trusted  all  --  anywhere             anywhere
FWDO_trusted  all  --  anywhere             anywhere

Chain FORWARD_OUT_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain FORWARD_direct (1 references)
target     prot opt source               destination

Chain FWDI_trusted (2 references)
target     prot opt source               destination
FWDI_trusted_log  all  --  anywhere             anywhere
FWDI_trusted_deny  all  --  anywhere             anywhere
FWDI_trusted_allow  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain FWDI_trusted_allow (1 references)
target     prot opt source               destination

Chain FWDI_trusted_deny (1 references)
target     prot opt source               destination

Chain FWDI_trusted_log (1 references)
target     prot opt source               destination

Chain FWDO_trusted (2 references)
target     prot opt source               destination
FWDO_trusted_log  all  --  anywhere             anywhere
FWDO_trusted_deny  all  --  anywhere             anywhere
FWDO_trusted_allow  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain FWDO_trusted_allow (1 references)
target     prot opt source               destination

Chain FWDO_trusted_deny (1 references)
target     prot opt source               destination

Chain FWDO_trusted_log (1 references)
target     prot opt source               destination

Chain INPUT_ZONES (1 references)
target     prot opt source               destination
IN_trusted  all  --  anywhere             anywhere
IN_trusted  all  --  anywhere             anywhere

Chain INPUT_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain INPUT_direct (1 references)
target     prot opt source               destination

Chain IN_trusted (2 references)
target     prot opt source               destination
IN_trusted_log  all  --  anywhere             anywhere
IN_trusted_deny  all  --  anywhere             anywhere
IN_trusted_allow  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain IN_trusted_allow (1 references)
target     prot opt source               destination

Chain IN_trusted_deny (1 references)
target     prot opt source               destination

Chain IN_trusted_log (1 references)
target     prot opt source               destination

Chain OUTPUT_direct (1 references)
target     prot opt source               destination

My ssh key is still in .ssh/authorized_keys but when using PuTTY, even before asking for the user, it dies with:
Network error: connection timeout

When trying to update my SVN local copy it dies "because host didn't respond".
What I've already looked:

This and this don't adress the problem since my access using Google console works perfectly
Neither this, because it relates to issues regarding first time connecting
Answer: The cause of the problem was that the IP changed after reboot.
I think it would be a good call to inform that besides reboot the machine may suffer from an IP change, unless you reserve a static external IP.
Fortunately, this wasn't my production server, so the change just caused a few hours of frustration for me till I discovered the problem.


Complex analysis Limit

Question: Find
$$\lim_{z \to 1+i} \frac {z^{2} -4z+4+2i}{z^{2}-2z+2}$$
Hi guys, I am now into complex analysis topics, and I have encounter a problem with this limit,
What I have tried is to substitite $z=1+i$ to the equation, and I got the answer
$$\frac{i^{2}+1}{1+i+i^{2}}$$
probably, this is wrong, and I think this question is related to the $\epsilon$ or $\delta$, what should I do to get the correct answer of the limit?
Thank you.
Comment: Note that $z^2-2z+2$ for $z=1+i$ is zero.
Comment: Factorize both the numerator and denominator.
Comment: Why not L'Hopital, by the way ?
Comment: I don't say this is wrong/right, but $i^2+1=0$, so your answer is also equal to $0$.
Comment: @Mahdi Oh, I juz realize that haha, my mind was blocked, but juz not sure if this is the proper way to solve the limit~
Comment: Make the denominator real by multiplying it with its complex conjugate.
Answer: Hint: If you plug in correctly for both the top and the bottom and then simplify you will get an indeterminate limit of $\frac{0}{0}$. Since both the top and the bottom are just complex polynomials this tells you that $1+i$ is their root. What would you do with a real valued limit if you had a fraction of two polynomials that share a root?

Complex analysis Limit


Probability of rolling $111, 222, 333, 444, 555, 666$ in that order

Question: What are the odds of rolling triples with $3d6$ like this: $111, 222, 333, 444, 555$, and $666$ perfectly in a row? I know that the odds of rolling triples in a row without any specific order is $36^3 = 1/46656$. But I don't know how to calculate it when order matters.
Comment: Shouldn't the odds of rolling (six) triples in a row without any specific order be $1/36^6$, not $1/36^3$?
Comment: The chance of rolling *any* triple in a row is $\frac{1}{36}$, as the first roll is "free" and the next two must match the first. Therefore the odds of rolling six triples in a row should be, as @BarryCipra says, $\left(\frac{1}{36}\right)^{6}$.
Answer: $$
\left(\frac{1}{6}\right)^{18}
$$
You need to get 18 dice right, each having $\frac{1}{6}$ probability.
Answer: the probability of a specific triple is $\frac{1}{216}$.  Since you require six specific triples in a row, the prob is
$$
\frac{1}{6^{18}}
$$
Answer: The above answers are correct, but perhaps the simplest way to consider it is that when rolling the set of triples you suggest in specific order, you MUST get the following sequence: 111222333444555666—nothing else will suffice. This is equivalent to rolling one die, eighteen times, and getting exactly the one number you need each time. The probability of getting the one number you need on a given roll is $\frac{1}{6}$ (assuming the die is fair) so the overall probability (assuming rolls are independant) is:
$$
\large
\underbrace{\frac{1}{6}\cdot\frac{1}{6}\cdot\frac{1}{6}\cdot\ldots\cdot\frac{1}{6}}_{18\;\textrm{times}}
$$
or
$$
\left(\frac{1}{6}\right)^{18}
$$


my epoll server can not detect client disconnection

Question: I wrote an epoll server and a simple client. When the client sends a message, it exits immediately and the server does not notice the disconnection.
events[i].events & EPOLLERR || events[i].events & EPOLLHUP
This judgment statement is of no use at all.
What areas need improvement in my epoll server?
I really want to know, please!
This is my server.cc
#include "server.h"
#include "../threadpool/threadpool.h"

static std::string getIpAddress()
{
    struct ifaddrs *ifAddrStruct = nullptr;
    struct ifaddrs *ifa = nullptr;
    void *tmpAddrPtr = nullptr;
    std::string ipAddress;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next)
    {
        if (!ifa->ifa_addr)
            continue;
        if (ifa->ifa_addr->sa_family == AF_INET)
        {
            tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

            if (strcmp(addressBuffer, "127.0.0.1") != 0)
            {
                ipAddress = std::string(addressBuffer);
                break;
            }
        }
    }

    if (ifAddrStruct != nullptr)
    {
        freeifaddrs(ifAddrStruct);
    }

    return ipAddress;
}

static void setFdNoblock(int fd)
{
    fcntl(fd, F_SETFL, fcntl(fd, F_SETFL) | O_NONBLOCK);
}

server::server(int port)
{
    epoll_fd = epoll_create1(0);
    if(epoll_fd == -1)
        throw std::runtime_error("Error in epoll_create1");

    struct sockaddr_in server_addr{};
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(port);

    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(server_socket == -1)
        throw std::runtime_error("Error in socket");

    int reuse = 1;
    if(setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1)
        throw std::runtime_error("Error in setsocketopt");

    if(bind(server_socket, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) == -1)
        throw std::runtime_error("Error in bind");

    if(listen(server_socket, SOMAXCONN) == -1)
        throw std::runtime_error("Error in listen");

    setFdNoblock(server_socket);

    std::cout << "server start on " << getIpAddress() << ':' << port << '\n';
}

server::~server()
{
    close(server_socket);
    close(epoll_fd);
}

void handleClient(int client_socket)
{
    printf("success!!!\n");
}

static int readn(int fd, char* buf, int size)
{
    char* pt = buf;
    int count = size;

    while(count > 0)
    {
        int len = recv(fd, pt, count, 0);
        if(len == -1)
            return -1;
        else if(len == 0)
            return size-count;

        pt += len;
        count -= len;
    }

    return size;
}

static int recvMsg(int cfd, char** msg)
{
    int len = 0;
    readn(cfd, (char*)&len, 4);
    len = ntohl(len);

    char *buf = (char*)malloc(len+1);
    int ret = readn(cfd, buf, len);
    if(ret != len)
    {
        close(cfd);
        free(buf);
        return -1;
    }

    buf[len] = '\0';
    *msg = buf;

    return ret;
}

void server::run()
{
    struct epoll_event event{};
    event.events = EPOLLIN;
    event.data.fd = server_socket;

    if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_socket, &event) == -1)
        throw std::runtime_error("Error in epoll_ctl");

    threadpool threadPool(THREAD_NUM);

    epoll_event events[MAX_EVENTS];

    while(true)
    {
        int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
        if(num_events == -1)
            throw std::runtime_error("Error in epoll_wait");

        for(int i = 0; i < num_events; i++)
        {
            if(events[i].data.fd == server_socket)
            {
                std::cout << "accepting new client...\n";
                int client_socket = accept(server_socket, nullptr, nullptr);
                if(client_socket == -1)
                {
                    std::cerr << "Failed to accept client connection\n";
                    continue;
                }
                event.events = EPOLLIN | EPOLLET;
                event.data.fd = client_socket;
                setFdNoblock(client_socket);

                epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_socket, &event);
                std::cout << "client on line client_socket: " << client_socket << '\n';

                threadPool.enqueue(handleClient, client_socket);//---------------to do
            }
            else
            {
                if (events[i].events & EPOLLERR || events[i].events & EPOLLHUP)
                {
                    epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, nullptr);
                    std::cout << "Client disconnected by EPOLLERR | EPOLLHUP: " << events[i].data.fd << '\n';
                    close(events[i].data.fd);
                }
                else if(events[i].events & EPOLLIN)
                {
                    char* msg = nullptr;
                    int ret = recvMsg(events[i].data.fd, &msg);
                    if(ret == -1)
                    {
                        std::cerr << "Failed to receive message from client_socket: " << events[i].data.fd << '\n';
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, nullptr);
                        close(events[i].data.fd);
                    }
                    else if (ret == 0)
                    {
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, nullptr);
                        std::cout << "Client disconnected: " << events[i].data.fd << '\n';
                        close(events[i].data.fd);
                    }
                    else
                    {
                        std::cout << "Received message from client_socket: " << events[i].data.fd << '\n';
                        std::cout << msg << '\n';
                        free(msg);
                    }
                }
            }
        }
    }
}

This is my client.cc
#include <sys/socket.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno> // For errno
#include <sys/types.h>

#define PORT_NUM 8000
#define IP "10.30.0.245"
#define BUF_SIZE 2048

void errExit(const char* error)
{
    perror(error);
    exit(EXIT_FAILURE);
}

int writen(int fd, const char* msg, int size)
{
    const char* buf = msg;
    int count = size;
    while(count > 0)
    {
        int len = send(fd, buf, count, 0);
        if(len == -1)
        {
            if(errno == EPIPE || errno == ECONNRESET)
            {
                printf("Network connection reset or broken.\n");
                return -1; // Return -1 to indicate network error
            }
            else
            {
                perror("send");
                close(fd);
                return -1;
            }
        }
        else if(len == 0)
        {
            continue;
        }

        buf += len;
        count -= len;
    }

    return size;
}

int sendMsg(int cfd, const char* msg, int len)
{
    if(msg == nullptr || len <= 0 || cfd <= 0)
    {
        return -1;
    }

    char* data = (char*)malloc(len+4);
    if(data == nullptr)
    {
        perror("malloc");
        return -1;
    }

    int bigLen = htonl(len);
    memcpy(data, &bigLen, 4);
    memcpy(data+4, msg, len);

    int ret = writen(cfd, data, len+4);

    free(data);

    return ret;
}

int main(void) {
    int sfd;
    struct sockaddr_in svaddr;
    char buf[BUF_SIZE];

    sfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sfd == -1)
        errExit("socket");

    memset(&svaddr, 0, sizeof(struct sockaddr_in));
    svaddr.sin_family = AF_INET;
    svaddr.sin_port = htons(PORT_NUM);
    inet_pton(AF_INET, IP, &svaddr.sin_addr);

    if(connect(sfd, (const struct sockaddr*) &svaddr, sizeof(struct sockaddr_in)) == -1)
        errExit("connect");

    printf("\nPlease input: ");
    memset(buf, 0, BUF_SIZE);
    if(fgets(buf, BUF_SIZE, stdin) == nullptr)
    {
        printf("Failed to read input.\n");
        close(sfd);
        return EXIT_FAILURE;
    }

    int len = strlen(buf);

    // Remove trailing newline if present
    if (len > 0 && buf[len-1] == '\n') {
        buf[len-1] = '\0';
        len--;
    }

    if (len == 0) {
        printf("Input is empty.\n");
        close(sfd);
        return EXIT_FAILURE;
    }

    if (strcmp(buf, "exit") == 0) {
        printf("Exiting...\n");
        close(sfd);
        return EXIT_SUCCESS;
    }

    if(sendMsg(sfd, buf, len) == -1) {
        errExit("sendMsg");
    }

    close(sfd);
    return EXIT_SUCCESS;
}

I want the server to notice that the client disconnected, what i better do?
Comment: Hi, welcome to SO.  Don't forget to add your programming language tag to your questions!  I added `C++` for you
Comment: Well, a quick glance over your code suggests that you are aware that EOF is indicated by read/recv returning 0; beyond that I'm too lazy to debug your code. I'll leave that detail to someone else, hence no answer :-)

What I'm not too lazy about is suggesting that you should really consider using a library for this kind of stuff. While I default to boost::asio, I wouldn't be religious about it -- chances are that "anything is better than building everything from scratch". Sockets can get pretty messy pretty quickly.
Answer: If I was debugging this code, two things I would do immediately:

add a line to tell you what events have actually occurred in the epoll loop on the server

std::cout << "Server event 0x" << std::hex << static_cast<unsigned>(events[i].events) << std::endl;

Change the order of your if/else conditions in the server epoll loop. Put the detection of EPOLLIN before the EPOLLERR/EPOLLHUP check.

Since your client sends data and then immediately closes its socket, you may be getting an event mask that has coalesced into (EPOLLIN | EPOLLHUP). Your server code doesn't handle that...
Comment: Thank you, I have solved this problem. Your suggestions will be very helpful for my future study.


Using real analysis

Question: Prove that $$
\lim \limits_{n\to \infty }\left( 2+\frac{1}{n+1} \right) =2 $$
Comment: Please show your thoughts on the problem.
Comment: Write down your definition of a limit.  How can you get the expression above to fit that definition?
Answer: I'm guessing you are asking for some type of $(\epsilon, \delta)$ argument. The first fact before beginning is to recall that if $(a_n)$ and $(b_n)$ are convergent sequences, say with limits $A,B$ respectively, then $\lim_{n} (a_n)+(b_n) = \lim_n a_n + \lim_n b_n$. In your case, take $a_n = 2$ and so let's analyze $b_n = \frac{1}{n+1}$.
Here $\frac{1}{n+1}< \frac{1}{n}$ and so if you can show $\frac{1}{n}$ has a limit, then $\frac{1}{n+1}$ will have the same limit since it is a subsequence. If $\frac{1}{n}< \epsilon$ then $n> \frac{1}{\epsilon}$. Therefore, given $\epsilon >0$, if you let $N_0> \frac{1}{\epsilon}$ where $N_0 \in \mathbb{N}$ then;
$$\frac{1}{n+1}< \frac{1}{n} < \epsilon; \forall n \geq N_0$$
Hence, using the fact that $a_n + b_n \to A+B $ then $2+\frac{1}{n+1} \to 2$ and $n \to \infty$ since the above argument implies $\frac{1}{n+1} \to 0$.
$\textbf{Question}$: Use the method above to determine the limits of $b_n = 3 + \frac{2}{n+2}$ and $n \to \infty$.

Using real analysis


Get all registered implementations of an interface in Autofac

Question: I need to get, from an IComponentContext, a list of registered Type's that implement a particular interface.
I don't want actual instances of the types, but rather a list of Type of which I could get instances.
I want to use this list to generate subscriptions on a message bus.
How do I get all registered implementations of an interface in Autofac?
Comment: Have you tried to use Reflection to iterate through all types within an assembly and check if they implement `IComponentContext`? See [Getting all types that implement an interface with C# 3.5](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-5)
Comment: @NikolayKhil That's not the question. I need to look through the context and find registered types. This is an Autofac-specific question.
Answer: I figured this out --
var types = scope.ComponentRegistry.Registrations
    .SelectMany(r => r.Services.OfType<IServiceWithType>(), (r, s) => new { r, s })
    .Where(rs => rs.s.ServiceType.Implements<T>())
    .Select(rs => rs.r.Activator.LimitType);

Comment: ServiceType doesn't have Implements method!
Answer: With AutoFac 3.5.2 (based on this article: http://bendetat.com/autofac-get-registration-types.html)
first implement this function:
    using Autofac;
    using Autofac.Core;
    using Autofac.Core.Activators.Reflection;
    ...

        private static IEnumerable<Type> GetImplementingTypes<T>(ILifetimeScope scope)
        {
            //base on http://bendetat.com/autofac-get-registration-types.html article

            return scope.ComponentRegistry
                .RegistrationsFor(new TypedService(typeof(T)))
                .Select(x => x.Activator)
                .OfType<ReflectionActivator>()
                .Select(x => x.LimitType);
        }

then assume we you have builder,
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
   var types = GetImplementingTypes<T>(scope);
}


php Mostrar a variavel

Question: Tenho uma página que envia emails quando uma das datas do meu formulário estão a terminar.
Atualmente ele envia só o nome da pessoa que tem a data a terminar mas quero que ele informe a data que está no fim.
sql = ("SELECT Nome, data1, data2, data3, data4 < (now()+ interval 10 day)");
$validade = mysql_query($sql);

while($row = mysql_fetch_array($validade)){
$Nome = $row[0];
$PHPMailer = new PHPMailer();
(....)
$PHPMailer->Body = "
Faltam 10 dias para terminar $Nome";

Basta-me colocar as datas assim?
$data1 = $row[1];
$data2 = $row[2];(...)

Comment: teoricamente é so isso. Para saber as `chaves` do array, de um `while($row = mysql_fetch_array($validade)){ echo ''; print_r($row);}`
Comment: Você quer saber como encontrar a data que está para terminar ou como exibir a data?
Comment: quero apenas mostrar a data que está a terminar da pessoa $Nome
Answer: Veja se isso pode solucionar seu problema.
sql = ("SELECT Nome, data1, data2, data3, data4 < (now()+ interval 10 day)");
$validade = mysql_query($sql);

while($row = mysql_fetch_array($validade)){
$Nome = $row[0];
$dataTermino = $row['data2']; // Ou a data que você deseja
$PHPMailer = new PHPMailer();
(....)
$PHPMailer->Body = "
Faltam 10 dias para terminar$Nome";
$PHPMailer->Body = "
A data prevista é$dataTermino";

Comment: Ou pode colocar o `$row['data3']` direto na string. Não precisa ficar criando variáveis.
Comment: $dataTermino = $row['data2'];
Mas se eu tiver mais datas? coloco:
$dataTermino1 = $row['data3']; $dataTermino2 = $row['data4']; (...)
Answer: De acordo com o seu select, os índices equivalentes são:

0 equivalente a Nome
1 equivalente a data1
2 equivalente a data2
3 equivalente a data3
4 equivalente a data4

Supondo que a conexão com o banco já está estabelecida. O código seria:
sql = ("SELECT Nome, data1, data2, data3, data4 < (now()+ interval 10 day)");
$validade = mysql_query($sql);

while($row = mysql_fetch_array($validade))
{
    $nome = $row[0];
    $prazo = $row[1]; // Ou o índice da data que desejar acessar
    $mensagem = "
Faltam menos de 10 dias para terminar $Nome.
" .
                "
Prazo: $prazo
";

    $PHPMailer = new PHPMailer();
    (....)
    $PHPMailer->Body = $mensagem;
}

Se preferir usar o nome dos campos para capturar os dados, faça:
$nome = $row['Nome'];
$prazo = $row['data1']; // Ou o nome do campo da data que desejar acessar

Lembrando que quando utilizamos o mysql_fetch_array podemos passar um segundo parâmetro opcional, o result_type que podem ser as constantes MYSQL_BOTH, MYSQL_NUM ou MYSQL_ASSOC. Caso não informado, o valor usado por padrão pela função é o MYSQL_BOTH.
Exemplos de como viria o seu resultado (usei valores aleatórios):
// Usando MYSQL_BOTH
array (size=10)
    0 => string 'nome capturado' (length=14)
    1 => string '2013-12-20' (length=10)
    2 => string '2014-01-20' (length=10)
    3 => string '2014-02-20' (length=10)
    4 => string '2014-03-20' (length=10)
    'Nome'  => string 'nome capturado' (length=14)
    'data1' => string '2013-12-20' (length=10)
    'data2' => string '2014-01-20' (length=10)
    'data3' => string '2014-02-20' (length=10)
    'data4' => string '2014-03-20' (length=10)

// Usando MYSQL_NUM
array (size=10)
    0 => string 'nome capturado' (length=14)
    1 => string '2013-12-20' (length=10)
    2 => string '2014-01-20' (length=10)
    3 => string '2014-02-20' (length=10)
    4 => string '2014-03-20' (length=10)

// Usando MYSQL_ASSOC
array (size=10)
    'Nome'  => string 'nome capturado' (length=14)
    'data1' => string '2013-12-20' (length=10)
    'data2' => string '2014-01-20' (length=10)
    'data3' => string '2014-02-20' (length=10)
    'data4' => string '2014-03-20' (length=10)

Imagine que você retorne um valor alto de resultados, usando o padrão você duplica a quantidade de resultados armazenados na memória do servidor.
São essas pequenas coisas que influênciam no desempenho de seu script/aplicação.
Para otimizar mais o seu script, aconselho a usar PDO para fazer o acesso ao banco de dados. Para trabalhar com datas em PHP, use a classe DateTime que possui diversas funções específicas para Data / Hora.

php Mostrar a variavel


jQuery Textillate.js - how to "reset" element html and re-start animation

Question: I am animating text using Textillate.js (http://jschr.github.io/textillate/) on html in a span.
The animations are manually triggered by button click ('in').
After/during the animation, a user can click a "reset" button to re-set the span back to the starting html (which is hidden).
Then the animation should run again manually on "in" button click, but I cannot get it to work.
To make it easy to see what I am trying to do, I created this Fiddle:
http://jsfiddle.net/nlapolla/mGgd5/225/
Here is the Fiddle code:

$('#tlt').textillate({
    autoStart: false,
    loop: true,
    in : { effect: 'bounceInRight' }
});

$('.in').on('click', function () {
    $('#tlt').textillate('in');
});

$('.out').on('click', function () {
    $('#tlt').textillate('out');
});

$('.reset').on('click', function () {
    $('#tlt').html('Some text');
});
#tlt {
    font-size:30px;
}
.hideme {
    visibility:hidden;
}
<link href="http://jschr.github.io/textillate/assets/animate.css" rel="stylesheet"/>

Some text

<button class="in">in</button>
<button class="reset">Reset/Hide</button>

Any ideas would really be appreciated!  I've been trying to get this to work for hours - searched SO and found a lot of great advice, but nothing helped in this case... thank you for any help you can provide.  :o)
Comment: Thanks -- but actually that is the Fiddle I started working with - I used it as the basis for my Fiddle.  The problem is that (aside from needing to be initially hidden until the button is clicked) I need it to "reset" and be instantly hidden - and remain hidden until the "in" button is clicked again.  The original Fiddle, starts it over, but it does not hide UNTIL manually triggered to reveal and animate again.  I hope I am making sense.  :o)
Comment: Someone already made a working fiddle over here: http://jsfiddle.net/jschr/mGgd5/
Comment: Got you!  I'll create a fiddle and post it as an answer.
Answer: I can't find a re-init event of textillate but what you could to is, delete and recreate the element on reset. And wrap the options in a function and call it on 'in' click. It will work but I'm not a JS expert so pretty sure there are much better ways of doing this.
function animate(el) {
  $(el).textillate({
    autoStart: false,
    loop: true,
    in : {
      effect: 'bounceInRight'
    }
  });
}

Here is the fiddle
Comment: Instead of "resetting, I ended up using the manual call to textillate "out" set at a delay of zero seconds.  Then I could manually call the textillate "in".  However, your solution also works and I will probably use it in another project.  Thank you!
Comment: @Nick you are welcome. I'm sure you can find better solutions after some time :)
Answer: I know this post is quite old, but I built a common function called retextillate that you can use to call or re-call textillate on an element and:

perform your initial call
re-initialize a given effect on the same element
change whether you call the in animation, the out animation, or both.

This should cover everything:
function retextillate(element, in_effect = "", out_effect = "", type) {

    /*
        element : html element with . or # symbol
        effect  : textillate/animate.css effect you're calling
        type    : either in, out, or both
    */

    $(element).textillate({
        loop: true,
        autoStart: false,
        in : {
            effect  : in_effect,
            delay   : 40
        },
        out : {
            effect  : out_effect,
            reverse : true,
            delay   : 40,
            callback : function() {
                $(element).css('opacity', 0);
            }
        }
    });

    if ( type == 'in' ) {

        $(element).textillate('in');
        $(element).css('opacity', 1);

    } else if ( type == 'out' ) {

        $(element).textillate('out');

    } else if ( type == 'both' ) {

        $(element).textillate('in');
        setTimeout( function() {
            $(element).textillate('out');
        }, 1000);

    }

}

If you're initializing it for the first time, it will go ahead and call textillate on the element.  In order to properly utilize this, you need to define both an in effect and an out effect, whether you plan on using it or not.  If you don't define one, it will just default to blank, which is okay.
So instead of running this on each element:
$('.my_element').textillate({
  in: { effect : 'slideInLeft' }
});

Just call it like this:
retextillate('.my_element', 'slideinleft', 'fadeOut', 'in');

You can play around on the same element over and over without having to refresh the page:
retextillate('.my_element', 'slideInLeft', 'fadeOut', 'in'); /* will show the slideInLeft animation, then stop */
retextillate('.my_element', 'tada', '', 'in'); /* will show the tada animation, then stop */
retextillate('.my_element', 'tada', 'fadeOut', 'both'); /* will show the tada animation, then the fadout animation, then stop */
retextillate('.my_element', '', 'fadeOut', 'out'); /* will show the fadeout animation, then stop */


reinstall PHP as apache module

Question: sorry for the newbie question, I am not a sys admin by any means.
I recently set up a VPS with webmin/virtualmin. Our CMS of choice says that PHP needs to be run as an Apache module in order to run. It says:
Recompile PHP with the flag --with-apxs
I've googled but can't find how to do this particularly. I think I installed PHP using "yum install php" or thru webmin, but can't remember exactly.
Appreciate if anyone can point me in the right direction.
Answer: You should probably give a little more information in order to get the best answers; such as what OS/version do you have? What CMS?
Since you mention yum, I'm going to assume a redhat based system, such as CentOS. If you have installed php using yum and you have apache installed, have you actually started apache? ('service httpd start'). Perhaps (at least that part of) your CMS installation just works?
If not, tell us what happens.
Tell us what you have, what you did and what response you got.
Answer: "As an Apache module" means using mod_php, rather than php-cgi.  I believe the php package on CentOS includes that.

reinstall PHP as apache module


Insert a series into specific column of a CSV file using Pandas Python

Question: I am reading a XLS file and fetching the contents of a single column into a series 'username'.
Now I want to insert the series into a CSV file which has a column named as 'Username'. I am having trouble doing this.
#Reading XLS File
excel_file = 'Some Report.xls'
sm_file = pd.read_excel(excel_file)

#Series
usernames = sm_file['Whois']

Now, I want to insert this series into "Username" column of "test.csv" file.
Test.csv file has many columns and I want to identify "Username" column and insert this series into that column.
I am facing difficulty while doing the same as I'm new in python & pandas.
Comment: Divide your task into subproblems!
Your first problem would be how to identify the "Username" column. Try that and tell us how it went!
Answer: Assuming the Whois column contains the usernames in the xls file, first read the csv 'test.csv' into memory:
import pandas as pd
usernames = sm_file['Whois']
testdf = pd.read_csv('test.csv')

Now, if the 'Usernames' column already exists in 'test.csv', then you can just select the column and assign the usernames series value to it. This is also assuming that the index length is same across the series and the testdf dataframe:
testdf['Usernames'] = usernames
testdf.to_csv('test.csv', encoding='utf-8', index=False, header=True)

I hope this helps.


Pedaling in Prokofiev's "Montagues and Capulets"

Question: I was trying to learn "Montagues and Capulets" and I saw this video of someone playing it.

Whats she doing with the base? I think she must be using the pedals, but I don't know which one.
The sheet music I have doesn't seem to notate any pedals.
https://web.media.mit.edu/~mike/scores/prokofiev/montague-capulet/index.pdf
Comment: I can't believe I have been playing versions of that for nearly 40 years without ever knowing its name! Thank you :-)
Answer: She's using the sustain pedal (the one on the far right). She can do this because, in the opening four measures, only one chord (E minor) is sounding, so there's really nothing in the melody that would clash with other sustained pitches. Measures 5 and 6 are another chord (B minor), but again nothing in the melody will clash with each other.
However, she does change the pedal (that is, she lets up the pedal and immediately presses it back down) every beat 1 and 3. This is largely because those bass notes (the E/G and then D/B) will muddy up the sound if they're both sustained at the same time.
The pedal isn't written in the score, as you say, but it's all but implied with the tenuto markings in the left hand. With the large leaps between each of these beats, it's hard to play these chords tenuto without using the pedal to help create some extra sustain. Notice that she quits using the pedal in m. 9 when beats 2 and 4 are specified as quarter rests.


Mapa abre bugado

Question: Bom dia!
Tenho uma aplicação web, onde utilizo um mapa leafletjs (http://tombatossals.github.io/angular-leaflet-directive/#!/) e openstreetmap como tile.
O mapa funciona de forma perfeita, consigo interagir de qualquer forma (adicionar marcadores, criar layers, zoom..), porém, quando acesso a página onde está o map, ele não carrega de forma correta, conforme printscreen abaixo:

Ele se reajusta quando eu redimensiono a janela ou abro e fecho o console, segue imagem abaixo:

Códigos:
View:

        <leaflet ng-init="vm.buscaEnderecoClientesEmpresas()" center="vm.center" defaults="vm.defaults" markers="vm.markers" width="100%" height="480px"></leaflet>

CSS/SASS:
.box_whiteframe_map {
    background-color: #fff;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .2), 0 1px 1px 0 rgba(0, 0, 0, .14), 0 2px 1px -1px rgba(0, 0, 0, .12);
    color: #000;
    margin: 0;
    clear: both;
}

Controller:
        /* MAP */
    vm.markers = new Array();

    vm.buscaEnderecoClientesEmpresas = function() {
        vm.items = loadSaas(Cookies.get('crm_o2_hash')); // carregar saas id
        vm.items.then(function(items) { // ler array de retorno
            vm.saasid = items;
            var dados = {
                'saasid': vm.saasid
            }
            relatoriosService.carregarEnderecoClientesEmpresas(dados).then(function(response) {
                if (response.data != 'null') {
                    vm.enderecoClientesEmpresas = response.data;
                    angular.forEach(vm.enderecoClientesEmpresas, function(value, key) {
                        if (value.tipo == 'p'){
                            var icon = 'user';
                        } else {
                            var icon = 'cog';
                        }
                        vm.markers.push({
                            group: value.cidade,
                            lat: value.lat_lng.lat,
                            lng: value.lat_lng.lng,
                            message: value.nome,
                            icon: {
                                type: 'awesomeMarker',
                                icon: icon,
                                markerColor: 'blue'
                            },
                            label: {
                                options: {
                                    noHide: true
                                }
                            }
                        });
                    });
                } else {
                    vm.enderecoClientesEmpresas = '';
                }

            }, function(error) {
                console.log('Erro findSemEmail: ', error);
            });
        });
    }

    angular.extend(vm, { // EXTENDE AS PROPRIEDADES DO MAPA (MARCADORES, LOCALIZAÇÃO INCIAL..)

        center: { // LOCALIZAÇÃO INICIAL  .
            lat: -22.952419,
            lng: -43.211667,
            zoom: 4
        },
        defaults: {
            tileLayer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
            zoomControlPosition: 'topright',
            tileLayerOptions: {
                opacity: 0.9,
                detectRetina: true,
                reuseTiles: true,
                attribution: '© OpenStreetMap | &copy Funil PRÓ',
            },
            scrollWheelZoom: true,
            minZoom: 3,
            worldCopyJump: true
        }
    });

    /* MAP FINAL */

Alguma ajuda?
Comment: Pode nos mostrar algum código?
Comment: Eu acredito que passei por um problema parecido e resolvi utilizando um `timeout` e chamando o método `invalidateSize()`. Exemplo: `$timeout(ctrl.map.invalidateSize());`. A variável `ctrl.map` é o meu objeto do Mapa (L.Map). Assim, após o carregamento do Angular, do Document, ele vai executar esse método e dar um _resize_ no mapa.
Comment: Geralmente este problema acontece quando o mapa carregou primeiro que algo ou você colocou o mapa em algum elemento do html que está/estava invisivel.  A solução para os dois problemas é dar um resize no mapa. No primeiro caso você dá um resize depois de onde você tem certeza que o mapa já foi completamente "configurado" e no segundo caso você deve colocar um resize TODAS as vezes que você exibir o elemento escondido.
Comment: Adicionado!!!!!
Answer: Consegui resolver da seguinte forma:
    vm.esconderMostrarMapa = false;

    vm.mostrarMapa = function () {
        $timeout(function() {
            vm.esconderMostrarMapa = true;
        }, 500);
    }

O mapa inicia como false, aí quando fica true o mesmo é mostrado na tela. Sei que não a melhor forma seria utilizando o invalidateSize(), mas vendo as issues no github do lefalet angularjs, várias pessoas estão com esse mesmo problema e não conseguiram resolver utilizando o mesmo.
Outra forma mais correta é utilizando o método map.invalidateSize:
        vm.ajustarMapa = function(){
      leafletData.getMap().then(function(map) {
        setTimeout(function(){
          map.invalidateSize();
        }, 200);
      });
    };

    vm.ajustarMapa();

Mapa abre bugado


What kind of algebraic equations do trandescendal numbers not solve?

Question: I know transcendental numbers cannot solve polynomials or rational functions (since they can always be written as a polynomial), but are they the solutions to equations containing a variable raised to a non-integer?
Comment: Does $x-\alpha=0$ count? Or do you mean equations with integers coefficients but non-integer powers?
Comment: The spelling in the title reminds me of an old Reader's Digest joke about an _oppucant_ and a _redisent_.
Answer: Whatever you accept as generalization of polynomials, I assume the candidate expressions can be expressed with finitely many symbols taken from a finite alphabet (e.g. it is possible to write them down in an intelligible manner on paper or using $\LaTeX$).. Moreover I assume you only accept functions that have at most countably many zeroes in $\mathbb R$ (so this allows us to define $\pi$ as the smallest positive zero of $\sin x$, for example). Then you still can catch at most countably many numbers, hence certainly not all transcendentals.


Assembly << operator

Question: I am following some tutorials on operating system development and I found an article on the
multiboot header. These are some 'magic' values you have to define for it to work with
GRUB2. These are the commands:
 # Declare constants used for creating a multiboot header.
 .set ALIGN,    1<<0             # align loaded modules on page boundaries
 .set MEMINFO,  1<<1             # provide memory map
 .set FLAGS,    ALIGN | MEMINFO  # this is the Multiboot 'flag' field
 .set MAGIC,    0x1BADB002       # 'magic number' lets bootloader find the header
 .set CHECKSUM, -(MAGIC + FLAGS) # checksum of above, to prove we are multiboot

 .section .multiboot
 .align 4
 .long MAGIC
 .long FLAGS
 .long CHECKSUM

Now what I don't understand, and i can't find anywhere, is what the 1<<0 and the 1<<1
do when we .set the align and meminfo.
Thanks in advance!
Comment: these are macro assembler specific: they have the same meaning as the C equivalent.
Answer: Surely if you are interested in operating system development you have already encountered the << operator in some other language? It's bitwise shift left. It is just used for defining some constants here, based on bit indices. Supposedly it is more clear than writing .set ALIGN 1 and .set MEMINFO 2.
You should also learn to read the manuals, or else you won't have much luck with programming.
Comment: Thanks for the answer, i read the gcc docs but i forgot the binutils ones. Yes i encoutered it in C and C++ but thought it would have a different function :)

Assembly << operator


Docker multistage build, python and java

Question: I'm trying to use https://docs.docker.com/develop/develop-images/multistage-build/
I need openjdk 8 and latest panda on alpine
(I'm installing spark / pyspark)
I initially tried using FROM openjdk:8-alpine and then installing all python3 / pandas , but it turns out installing pandas is rather hard in alpine and you need latest alpine docker image (Installing pandas in docker Alpine)
So I need FROM openjdk:8-alpine  and From alpine:latest
My question is how do I know which directory(?) to copy from the each step?
If I do
FROM openjdk:8-alpine
From alpine:latest

I'll need copy java8 related stuff from the openjdk:8-alpine
If I do reverse
From alpine:latest
# install panda
FROM openjdk:8-alpine

I'll need copy (what??)
Comment: I think you need to install JDK manually on the image , multistage will not be helpfull in your case
Comment: Is there a specific reason you need both in the same image?  Typical practice if you have two application components in separate programs is to run them in two separate containers, and use a network call (like HTTP) between them.
Comment: @eugene A general rule is to run only one application per container, even if they're on the same stack (eg: both java apps).
It is possible to run multiple application on one container but that too has complexities. See https://docs.docker.com/config/containers/multi-service_container/
Comment: This should help: https://pythonspeed.com/articles/multi-stage-docker-python/
Comment: BTW, even if you are able to copy all the libraries of python/pandas in the `openjdk:8-alpine` how would you use them? They would still require `python` binary in the final image, right?
Comment: I need to run spark (which requires java) and pyspark which is python.. I guess I could separate them but probably easier to setup single docker.. @DavidMaze
Comment: @Bernard thanks for the tip, I'll take that into account, but I doubt you can separate java /python in spark / pyspark app. (top google hits for spark docker file example have java/python in one dockerfile such as https://github.com/Fokko/docker-pyspark/blob/master/Dockerfile)
Answer: When you use multi-stage build, you typically create an artefact (a compiled app for instance) during the first phase, and copy it to a slimmer base image on the second phase. Everything from the first stage is discarded when the final image is created.
From your comments, I think I understand that you need to start from an image that has both JDK8 AND the latest alpine. Multi-stage build doesn't help here. You'd end up just copying the JDK to the alpine:latest final stage.
I would instead copy the original Dockerfile jdk:8-alpine, change the first line to FROM alpine:3.10 and create your own base image.
If you need pyspark based on this image, you copy the original dockerfile and replace the first line FROM openjdk:8 with your base image created previously.


Using NSNumberFormatter to pad spaces between a currency symbol and the value

Question: Apologies if this is a dumb question but I'm trying to format a currency value for my iphone app and am struggling to left-justify the currency symbol, but right-justify the value. So, "$123.45" is formatted as (say)  $   123.45 depending on format-width. This is a kind of accounting format (I think).
I've tried various methods with NSNumberFormatter but can't get what I need.
Can anyone advise on how to do this?
Thanks
Fitto
Answer: You're looking for the paddingPosition property of NSNumberFormatter. You need to set this to NSNumberFormatterPadAfterPrefix for the desired format.
Comment: It's important to note that this only works when formatWidth is set, as per the question.
Comment: Brilliant. Worked a treat. Thanks
Answer: This didn't work for me. I was able to add a space between the currency symbol and the amount by doing this.
Swift 3.0
currencyFormatter.negativePrefix = "\(currencyFormatter.negativePrefix!) "
currencyFormatter.positivePrefix = "\(currencyFormatter.positivePrefix!) "

Complete code:
extension Int {
    func amountStringInCurrency(currencyCode: String) -> (str: String, nr: Double) {
        let currencyFormatter = NumberFormatter()
        currencyFormatter.usesGroupingSeparator = true
        currencyFormatter.numberStyle = .currency
        currencyFormatter.currencyCode = currencyCode
        currencyFormatter.negativePrefix = "\(currencyFormatter.negativePrefix!) "
        currencyFormatter.positivePrefix = "\(currencyFormatter.positivePrefix!) "

        let nrOfDigits = currencyFormatter.maximumFractionDigits
        let number: Double = Double(self)/pow(10, Double(nrOfDigits))
        return (currencyFormatter.string(from: NSNumber(value: number))!, number)
    }
}

This extension is on an Int that expresses the amount in MinorUnits. I.e. USD is expressed with 2 digits, while japanese yen is expressed without digits. So this is what this extension would return:
let amountInMinorUnits: Int = 1234
amountInMinorUnits.amountStringInCurrency(currencyCode: "USD").str // $ 12.34
amountInMinorUnits.amountStringInCurrency(currencyCode: "JPY").str // JP¥ 1,234

The thousand and decimal separator are determined by the users locale.


mysql errors after upgrading php and mysql

Question: recently upgraded server to php 5.6.5 and mysql 5.6.22. running drupal 7.
after the upgrade we started having issues.
the server seems to run well for a week or so before starting to throw error pages with:
<code>Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Warning: Cannot modify header information - headers already sent by (output started at /path/to/site/includes/database/database.inc:307) in drupal_send_headers() (line 1233 of /path/to/site/includes/bootstrap.inc).
PDOException: SQLSTATE[HY000] [2006] MySQL server has gone away in lock_may_be_available() (line 167 of /path/to/site/includes/lock.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
</code>
when this happens, not every page shows the error, more like 25% or so.
so far i have had no luck tracking down the cause of the error. it seems to 'reset' if i stop/start mysql. such that if i stop/start i can get another week of no problems and then it begins again. this was making me think that it is a problem with a mysql setting related to connections or something, but i am no expert in this area and so am asking here.
after googling and seeing many posts suggesting to increase 'max_allowed_packets', we tried this but still the same issue occurs.
Answer: I added the following items to my.cnf which fixed my PDO broken pipe issues.  I am using a homebrew installation of mysql on a macbook pro with 16GB RAM:
key_buffer_size = 384M
max_allowed_packet = 100M
table_open_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
query_cache_size = 128M
query_cache_size = 256M
Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8
innodb_buffer_pool_size=512M
Comment: setting query_cache_size = 256M did the trick for me
Answer: The timestamps on those log entries would be helpful so we can see how much time went by before you received the "MySQL server has gone away..." message.
From the symptoms it seems MySQL is crashing, but it could be a connection issue between the client (Drupal/PHP/PDO) and the MySQL server; "send of 128 bytes failed" is an indication.
Log onto your MySQL server and tell us what's in your MySQL error log (typically in /var/lib/mysql but depends on your OS). Typically the error file is named mysql.err.


font-weight overwriting my custom font-face (wkhtmltopdf)

Question: I use @font-face on my website for my users to get their own custom font.
On internet everything works fine. (Don't pay attention to the line-height, it's not an issue.)

But when I export in pdf I get this

I've made some tests and I realized it's due to my inherit 'font-weight:400'

If I change the value for 'font-weight:900' it exports well.
The problem I have is webpages are generated dynamically and I can't predict the font-weight of the user uploaded font.
Is there a way to remove the font-weight attribute in order to not interfere with the uploaded @font-face ?
I've tried 'font-weight:unset !important' but without success...
Comment: You may be misunderstanding how @font-face rules work: what you do with `@font-face` is that you are teaching the CSS engine what it should be doing when it sees a combination of font-family plus {font-weight, font-style, ...}. Irrespective of the font's actual look, if you declare a `@font-face` rule and say "when you see family X, with weight 100, and style normal, use source myfont-italic-superbold.woff", then any element with a class that says to use `font-family: X; font-weight: 100; font-style: normal;` will use `myfont-itaic-superbold.woff`.
Comment: So: if you have a url to the user's uploaded font, declare an `@font-face` rule that gives it a unique font family name, don't specify any other property, and then render the element that should use the font with the element's font-family set to that unique name
Comment: thanks mike, it's useful to understand that
Answer: Try font-weight:normal;. That typically works for me.
Comment: not working. I still get 'font-weight:400' on my style inspector and the rendering doesn't works as well :/
Comment: Do you have a link?


Terminology: Can "goodness-of-fit statistics" and "indicators" be used interchangeably?

Question: I want to use several indicators to determine the goodness of fit of my model, such as R square, K-S, chi-square etc.

What should I call them? Can I call them goodness-of-fit indicators? I see a paper calling them statistics.
Answer: In mathematics indicator has a very precise meaning:

In mathematics, an indicator function or a characteristic function is
  a function defined on a set $X$ that indicates membership of an
  element in a subset $A$ of $X$, having the value $1$ for all elements
  of $A$ and the value $0$ for all elements of $X$ not in $A$. It is
  usually denoted by a symbol $1$ or $I$, sometimes in boldface or
  blackboard boldface, with a subscript describing the set.

While in case of goodness of fit we are talking rather about measures, statistics, or tests, e.g.

The goodness of fit of a statistical model describes how well it fits
  a set of observations. Measures of goodness of fit typically summarize
  the discrepancy between observed values and the values expected under
  the model in question. Such measures can be used in statistical
  hypothesis testing, e.g. to test for normality of residuals, to test
  whether two samples are drawn from identical distributions (see
  Kolmogorov–Smirnov test), or whether outcome frequencies follow a
  specified distribution (see Pearson's chi-squared test). In the
  analysis of variance, one of the components into which the variance is
  partitioned may be a lack-of-fit sum of squares.

Notice that goodness of fit statistics measure how well does your morel fit the data. In some cases you can conduct a statistical test to check this. However they never indicate (i.e. show, point, demonstrate) that your model fits -- such decisions are always done subjectively, based on the available measures since it is never a yes/no kind of situation.
You might been thinking about "estimator" (as "estimator" and "indicator" sound similar), but this would also be incorrect since you are not estimating any property of your data.
So you can call them "measures", sometimes they are called "statistics", and if you were talking solely about tests (which $R^2$ is obviously not), then about "tests".
Comment: @NickCox totally agree :) The only thing that I'm saying is: "indicator" is an unfortunate choice as it's own meaning that can be understood differently than the authors intent.
Comment: _Goodness-of-fit measures_ is plural, so I am not clear what else you seek.
Comment: +1. The precise meaning of indicator in mathematics is well taken; indeed personally I much prefer the term _indicator variable_ to the awful and awkward _dummy variable_. But nothing can undermine the usefulness of indicator as a looser, informal and general term for any measure or piece of evidence that indicates. There is a splendid discussion early in Mosteller, F. and Tukey, J.W. 1977. _Data analysis and regression_. Reading, MA: Addison-Wesley of the importance of indication in statistics. There is a literature on "social indicators", and so on.
Comment: @NickCox I would agree if we were talking about social science, biology etc., but if this is a paper with mathematical content that using a phrase that has a pretty precise meaning is not a good idea. Moreover, those statistics *measure* the extend of goodness of fit rather that *indicating* that something fits or not.
Comment: As in this thread http://stats.stackexchange.com/questions/202879/what-are-the-most-misused-statistics-terms-that-we-should-care-to-correct mathematicians or statistical people can use an existing word and give it an exact formal meaning, but they then should not imply that to be the only correct usage. The  everyday senses of _group_, _field_ or _ring_ were not made obsolete when those terms were adopted in algebra.
Comment: I don't know the OP's field and in any case the question is general. But in any applied field, it is prudent to use terms that people reading a paper will be comfortable with, just as it is also a good idea to use exact and correct terminology. There can be some tension between those aims. When I write in journals on geology, glaciology, forestry, etc. I need to think what will be clear and most easily understood.
Comment: Indeed; many threads on CV alone show that people with overlapping but not identical understanding and terminology can fail to understand each other almost completely.
Comment: I assume R square could be could gof measures? But is there plural form when I stating multiple measures?
Answer: They are statistics insofar they are calculated from samples, but that term is too broad to be a good answer.
The term goodness of fit is well established, except that some of those measures are inverse and really measure badness of fit, a term occasionally used, by J.B. Kruskal among others. But that objection is at most a quibble, and it's well understood in statistics, as elsewhere, that performance measures can be direct or inverse, so that usually people want high $R^2$ and low chi-square, or low inflation and high GDP growth, or whatever.
As another example, root mean square error should ideally be low, with nothing else said.
(If you know about overfitting, you'll know the limitations of these comments, but here the focus is on terminology.)
I like the term figures of merit, as an all-purpose term used in several fundamental and applied sciences. Again, merit can be direct (number of Nobel Prizes won) or inverse (number of downvotes on Cross Validated).
The term indicator is not especially good for your purpose and certainly not synonymous with goodness-of-fit measures. As @Tim explains in his answer, there is a much more specific technical sense, and as I emphasise in my comments on his answer, there is a much wider, less technical sense for the term indicator. There is no middle ground in which indicators mean goodness-of-fit statistics, exactly. But if you were to talk about goodness-of-fit indicators, I don't think you would be misunderstood. It's just not an especially good term for the purpose.
Comment: Goodness-of-fit statistics or measures is fine by me.
Comment: Well, then what should I call them? Goodness-of-fit indicator? or just goodness of fit? That feels strange.


copies of installations for each client

Question: I have built a Drupal based web app product that I want to give (a trimmed down version) for free. I am expecting 100s and 1000s of subscribers. Each one should get an exclusive code base (drupal files) and database- thats my product's need.
I plan to use AWS- amazon web services.
1). I want users to visit my company site and click and install the product(the web app site) for themselves. This should automatically
       a. create a sub-domain,
       b. copy my main code base and database. How to do these?
2). For maintenance and upgrades management, I want to have a single
parent code base (probably at private github) and would want each of these sites to replicate that. This is to avoid upgrading 1000s of sites individually. How to do this?
3). Some of my subscribers may want to upgrade to paid version. So I may have to customize their instance. How to ensure the custom changes are not overridden on maintenance acts of above point.
I have a low budget so I cannot buy any service to do this. I am hoping that a module or some Drush way can solve this.
Comment: Thousands of installations and databases.. There must be a better way using Organic Groups or similar and https://www.drupal.org/project/domain . I have a similar thing where any domain or subdomain can point at my single installation and database. I don't have it automated though. What aspect of your product's needs requires a separate install?
Answer: You may be able to use Aegir (Hostmaster): https://www.drupal.org/project/hostmaster
Comment: This is what I was looking for. Thanks  . But can Aegir allow visitors to my company site to fill a simple form - like name and email  and get their site set up? Not very clear in [link](http://docs.aegirproject.org/en/3.x/usage/advanced/clients/#create-clients)

copies of installations for each client