text:
Q: loading relationship with groupBy laravel I have a query which selects some relationships and groups by the accommodations to remove the duplicate accommodations. But now when I want to load the discount realtion on rooms, it doesn't work because I select only the accommodation_id.
Here is my code:
 $data = AccommodationRoom::with('accommodation.city', 'accommodation.accommodationFacilities', 'accommodation.gallery','discount')
        ->select('accommodation_id')
        ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
            $query->whereDate('from_date', '<=', $from_date);
            $query->whereDate('to_date', '>=', $to_date);
        })
        ->whereHas('accommodation', function ($query) use ($searchCity) {
            $query->where('city_id', $searchCity);
        })
        ->groupBy('accommodation_id')
        ->get();

Now if I add the id to the select it would be fine, but my groupBy doesn't work and gives me an error in this case. So I need a solution to get all my accomodations with the listed relations.

A: As you are looking for all your accommodations with some related models, you should actually select from your Accommodation model. This will work out of the box for the first three relations but will require some tweaking for the discount relation. The simpliest solution is to create a HasManyThrough relation on the Accommodation model:
class Accommodation extends Model
{
    public function discounts()
    {
        return $this->hasManyThrough(Discount::class, AccommodationRoom::class);
    }
}

Note: this expects your models to use foreign key columns named by convention; for different names you will need to pass the custom foreign key names as additional parameters according to the documentation.
With this relation set up, you can then use a query like the following:
$data = Accommodation::with('city', 'accommodationFacilities', 'gallery', 'discounts')
    ->whereHas('accommodationRooms.roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->where('city_id', $searchCity)
    ->get();

Further explanation as asked for in the comments:
HasManyThrough builds a virtual relation between two models using a third model in between. Imagine you have Post, Comment and Like as models. One Post can have many Comments and one Comment can have many Likes:
            has many                       has many
Post   ----------------->   Comment   ----------------->   Like
       1                n             1                n

In this case we also know that one Post can have many Likes. And this is exactly the knowledge we utilize when using HasManyThrough. We simply tell Eloquent that a Post has many Likes, connected by the Posts in between:
            has many                       has many
Post   ----------------->   Comment   ----------------->   Like
       1                n             1                n

                   has many through Comment
Post   ------------------------------------------------>   Like
       1                                               n


text:
Q: Nagios uses sendmail, new mail server, need to change SMTP server I'm working with a CentOS server that has Nagios running and sending notification emails. The emails are still going to the old email system which was kept up to ensure all emails were being routed to the correct location. I didn't set the system up, but it appears that this machine was able to relay to the smtp server to send mail? It still sends it through to the old system. I have the hostname for the new SMTP server but I'm not sure where I need to input this data.

A: Nagios actually uses external commands to send email—it doesn't send them directly. For example, in our config here, /etc/nagios3/commands.cfg contains (in part):
define command{
    command_name    notify-host-by-email
    command_line    /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$
    }

if you scroll to the right, you'll see that it's sending via /usr/bin/mail. mail generally uses the system MTA (Exim in my case, but probably not yours).
If yours is also going through the system MTA, you'll probably find the Email chapter of the Deployment Guide useful, in particular its two MTA sections.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GetKeyboardState one key delay I'm working on ToUnicodeEx function and it requires keyboard state as the input parameter. So, I used the GetKeyboardState function to do that. But I noticed when I'm typing key combinations with modifier keys like SHIFT+A there is one character delay. Here is the example.
aaa (holding SHIFT now) aAAAAAAA (release SHIFT) Aaaa
While I was debugging this I noticed GetKeyboardState is causing this delay. How can I handle or prevent this delay?
Here is my whole keyboard hook proc.
void proc(KBDLLHOOKSTRUCT kbdStruct) {

    fdebug = fopen("debug.txt", "a");
    foutput= fopen("output.txt", "a");
    WCHAR pwszBuff[9];
    WCHAR key[9];
    char str[8];
    BOOL isDead = FALSE;
    BYTE lpKeyState[256];
    HWND currentHwnd = GetForegroundWindow();
    LPDWORD currentProcessID = 0;
    DWORD currentWindowThreadID = GetWindowThreadProcessId(currentHwnd, currentProcessID);
    DWORD thisProgramThreadId = GetCurrentThreadId();
    hkl = GetKeyboardLayout(thisProgramThreadId);
    if (AttachThreadInput(thisProgramThreadId, currentWindowThreadID, TRUE))
    {
        GetKeyboardState(lpKeyState);

        AttachThreadInput(thisProgramThreadId, currentWindowThreadID, FALSE);
    }
    else
    {
        GetKeyboardState(lpKeyState);
    }

    int ret = ToUnicodeEx(kbdStruct.vkCode, kbdStruct.scanCode, lpKeyState, pwszBuff, 8, 0, hkl);
    fprintf(fdebug, "vkCode: %d\n", (int)kbdStruct.vkCode);
    fprintf(fdebug, "ret: %d\n", (int)ret);
    fprintf(fdebug, "lastIsDead: %d\n", (int)lastIsDead);
    fprintf(fdebug, "lastIsMod: %d\n", (int)lastIsMod);
    fprintf(fdebug, "lastVKCode: %d\n", (int)lastVKCode);
    if (ret == -1) {
        isDead = TRUE;
        ClearKeyboardBuffer(kbdStruct.vkCode, kbdStruct.scanCode, hkl);
    }
    else if (ret == 0) {

    }
    else {
        memcpy(&key, &pwszBuff, sizeof(pwszBuff));
        WideCharToMultiByte(CP_UTF8, 0, key, -1, str, sizeof(str), NULL, NULL);
        fprintf(fdebug, "str: %s\n", str);
    }

    if (lastVKCode != 0 && lastIsDead == TRUE) {
        ToUnicodeEx(lastVKCode, lastScanCode, lastKeyState, pwszBuff, 4, 0, hkl);
        memcpy(&key, &pwszBuff, sizeof(pwszBuff));
        WideCharToMultiByte(CP_UTF8, 0, key, -1, str, sizeof(str), NULL, NULL);
        fprintf(fdebug, "str: %s\n", str);
        lastVKCode = 0;

    }
    fprintf(fdebug, "%s", "---------------------------------------------------\n");

    fprintf(foutput, "LSHIFT: %d\n", (int)lpKeyState[160]);
    fprintf(foutput, "RSHIFT: %d\n", (int)lpKeyState[161]);
    fprintf(foutput, "%s", "---------------------------------------------------\n\n");

    lastVKCode = kbdStruct.vkCode;
    lastScanCode = kbdStruct.scanCode;
    lastIsDead = isDead;
    fclose(fdebug);
    fclose(foutput);
}

Here is updated version of hookcallback thanks for Ton Plooij. But still, I have the same problem.
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
    LRESULT ret = CallNextHookEx(_hook, nCode, wParam, lParam);
    if (nCode >= 0)
    {
        if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
        {
            hookStruct = *((KBDLLHOOKSTRUCT*)lParam);
            proc(hookStruct);

        }
    }
    return ret;
}

A: AttachThreadInput(thisProgramThreadId, currentWindowThreadID, FALSE);

This does not do what you hope it does.  Sometimes.  It is a valiant and necessary effort to get the proper values when you call GetKeyboardState().  Took me a while to find the failure mode, it wasn't obvious at all and I could not get the code to fail the same way.  It works just fine when a GUI process is in the foreground, try it with Notepad or VS for example.
But not when it is a console mode process.
Explaining that is a bit convoluted, it is actually GetWindowThreadProcessId() that returns misleading information.  It tries too hard to keep up the illusion that it is the console process that owns the console window.  It doesn't, it is actually the associated conhost.exe process that owns it.  It was csrss.exe on old Windows versions, conhost.exe was added in Windows 7 to solve the drag+drop issues caused by UIPI (aka UAC).
But without any decent way to discover the specific conhost.exe process that owns the window, let alone the thread id.  The subject of this Q+A.  Pretty doubtful it is going to help you.
Only decent advice is the well-known unpleasant one: if you need to reliably translate keystrokes then you need to use a WH_KEYBOARD hook instead of WH_KEYBOARD_LL.  So GetKeyboardState() is always accurate, the hook callback runs in-process.

A: A LowLevelKeyboardProc receives WM_KEYUP and WM_KEYDOWN messages in its wParam. You could simply keep track of pressed modifier keys yourself, in this case to detect shift down and up. Store the key state information in a static variable and use this to test if shift is pressed while processing other keys instead of using GetKeyState.

A: You can try GetAsyncKeyState().
This function in my keyboard hook module work perfectly.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx
It seems that this function can catch hardware interrupt when you press keys.
And your GetKeyboardState has something to do with the Windows Registry.
It seems to have something to do with belows:
"HKEY_USERS\DEFAULT\ControlPanel\Keyboard",Modify "KeyboardDelay" value to 0(default 1)
And change "KeyboardSpeed" value to 48(dafault 31).

A: According to Hans Passant's answer I searched for how can I get correct value from GetWindowThreadProcessId() and succeeded with instead of getting hWnd and windowThreadID every time in hook callback, I get these values to global variable just after program start and used variables in hook callback.


text:
Q: Spread vs dcast I have a table like this,
> head(dt2)
  Weight Height   Fitted interval limit    value
1   65.6  174.0 71.91200     pred   lwr 53.73165
2   80.7  193.5 91.63237     pred   lwr 73.33198
3   72.6  186.5 84.55326     pred   lwr 66.31751
4   78.8  187.2 85.26117     pred   lwr 67.02004
5   74.8  181.5 79.49675     pred   lwr 61.29244
6   86.4  184.0 82.02501     pred   lwr 63.80652

I want it to have like this,
> head(reshape2::dcast(dt2,
         Weight + Height + Fitted + interval ~ limit,
         fun.aggregate = mean))
  Weight Height   Fitted interval      lwr      upr
1   42.0  153.4 51.07920     conf 49.15463 53.00376
2   42.0  153.4 51.07920     pred 32.82122 69.33717
3   43.2  160.0 57.75378     conf 56.35240 59.15516
4   43.2  160.0 57.75378     pred 39.54352 75.96404
5   44.8  149.5 47.13512     conf 44.87642 49.39382
6   44.8  149.5 47.13512     pred 28.83891 65.43133

But using tidyr::spread, How can I do that?
I was using,
> tidyr::spread(dt2, limit, value)

But getting the error,
Error: Duplicate identifiers for rows (1052, 1056), (238, 242), (1209, 1218), (395, 404), (839, 1170), (25, 356), (1173, 1203, 1215), (359, 389, 401), (1001, 1200), (187, 386), (906, 907), (92, 93), (930, 1144), (116, 330), (958, 1171), (144, 357), (902, 1018), (88, 204), (960, 1008), (146, 194), (1459, 1463), (645, 649), (1616, 1625), (802, 811), (1246, 1577), (432, 763), (1580, 1610, 1622), (766, 796, 808), (1408, 1607), (594, 793), (1313, 1314), (499, 500), (1337, 1551), (523, 737), (1365, 1578), (551, 764), (1309, 1425), (495, 611), (1367, 1415), (553, 601)

Random 10 Rows::
> dt[sample(nrow(dt), 10), ]
     Weight Height   Fitted interval limit    value
1253   52.2  162.5 60.28203     conf   upr 61.51087
426    49.1  158.8 56.54022     pred   upr 74.75756
1117   78.4  184.5 82.53066     conf   lwr 80.98778
1171   85.9  166.4 64.22611     conf   lwr 63.21254
948    61.4  177.8 75.75494     conf   lwr 74.66393
384    90.9  172.7 70.59731     pred   lwr 52.41828
289    75.9  172.7 70.59731     pred   lwr 52.41828
3      44.8  149.5 47.13512     pred   lwr 28.83891
774    87.3  182.9 80.91258     pred   upr 99.12445
772    86.4  175.3 73.22669     pred   upr 91.40919

A: Let's say you were starting with data that looked like this:
mydf
#   Weight Height  Fitted interval limit    value
# 1     42  153.4 51.0792     conf   lwr 49.15463
# 2     42  153.4 51.0792     pred   lwr 32.82122
# 3     42  153.4 51.0792     conf   upr 53.00376
# 4     42  153.4 51.0792     pred   upr 69.33717
# 5     42  153.4 51.0792     conf   lwr 60.00000
# 6     42  153.4 51.0792     pred   lwr 90.00000

Notice the duplication in rows 5 and 6 of the grouping columns (1 to 5). This is essentially what "tidyr" is telling you. The first row and fifth are duplicates, as are the second and sixth.
tidyr::spread(mydf, limit, value)
# Error: Duplicate identifiers for rows (1, 5), (2, 6)

As suggested by @Jaap, the solution is to first "summarise" the data. Since "tidyr" is only for reshaping data (unlike "reshape2", which aggregated and reshaped), you need to perform the aggregation with "dplyr" before you change the data form. Here, I've done that with summarise for the "value" column.
If you stopped the execution at the summarise step, you would find that our original 6-row dataset had "shrunk" to 4 rows. Now, spread would work as expected.
mydf %>%
  group_by(Weight, Height, Fitted, interval, limit) %>%
  summarise(value = mean(value)) %>%
  spread(limit, value)
# Source: local data frame [2 x 6]
#
#   Weight Height  Fitted interval      lwr      upr
#    (dbl)  (dbl)   (dbl)    (chr)    (dbl)    (dbl)
# 1     42  153.4 51.0792     conf 54.57731 53.00376
# 2     42  153.4 51.0792     pred 61.41061 69.33717

This matches the expected output from dcast with fun.aggregate = mean.
reshape2::dcast(mydf, Weight + Height + Fitted + interval ~ limit, fun.aggregate = mean)
#   Weight Height  Fitted interval      lwr      upr
# 1     42  153.4 51.0792     conf 54.57731 53.00376
# 2     42  153.4 51.0792     pred 61.41061 69.33717

Sample data:
 mydf <- structure(list(Weight = c(42, 42, 42, 42, 42, 42), Height = c(153.4,
     153.4, 153.4, 153.4, 153.4, 153.4), Fitted = c(51.0792, 51.0792,
     51.0792, 51.0792, 51.0792, 51.0792), interval = c("conf", "pred",
     "conf", "pred", "conf", "pred"), limit = structure(c(1L, 1L,
     2L, 2L, 1L, 1L), .Label = c("lwr", "upr"), class = "factor"),
         value = c(49.15463, 32.82122, 53.00376, 69.33717, 60,
         90)), .Names = c("Weight", "Height", "Fitted", "interval",
     "limit", "value"), row.names = c(NA, 6L), class = "data.frame")

A: Here are data.table alternatives to dplyr.  Use mydf from Ananda's answer.
library(data.table)
library(magrittr)
library(tidyr)

DT <- data.table(mydf)

First, you can use by to compute the mean by each limit.
DT[, .(lwr = mean(value[limit == "lwr"]),
       upr = mean(value[limit == "upr"])),
   by = .(Weight, Height, Fitted, interval)]

If this limit == ... looks too much hard coding, you can first aggregate into a long format, then spread.  This works because once you aggregate, there is no duplicate.
DT[, .(value = mean(value)), by = .(Weight, Height, Fitted, interval, limit)] %>%
  spread(key = "limit", value = "value")

Both gets you
#   Weight Height  Fitted interval      lwr      upr
#1:     42  153.4 51.0792     conf 54.57731 53.00376
#2:     42  153.4 51.0792     pred 61.41061 69.33717


text:
Q: Firefox opens blank page instead of application url – Codeception and selenium2 I'm trying to use codeception for acceptance tests. I decided to use it with Selenium2.
Starting environment:
acceptance.suite.yml:
class_name: WebGuy
modules:
    enabled:
        - Selenium2
        - WebHelper
    config:
          Selenium2:
              url: 'http://nemo.dev'
              browser: firefox
              delay: 1000

test:
<?php
$I = new WebGuy($scenario);
$I->wantTo('see text');
$I->amGoingTo('/');
$I->see('text');

After build and run Firefox starts, shows blank page, and exits.
In console:
1) Couldn't see text in SigninCept.php
Guy couldn't see "text": 'text' in .
Failed asserting that response contains "text". Response was saved to 'log' directory.

Scenario Steps:
2. I see "text"
1. I am going to /

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Running Mac OS X 10.8.3, selenium: selenium-server-standalone-2.32.0.jar, PHP 5.3.15.
Failure, white screen screenshot in logs, no understanding of situation.

A: Pretty basic issue. You should specify the starting page. Always.
Insert this line before commands.
$I->amOnPage('/');


text:
Q: cordova/phonegap - how to write in Isolated Storage, Windows Phone 8 Porting my app from android to WP8, I am writing/reading using cordova's API in //myDir/MyFile.html
Here my javascript code:
function writeOnFileSystem() {
    window.resolveLocalFileSystemURI(
                "/", onSuccess,
                onError);
}

function onSuccess(entry) {
    entry.getDirectory("myDir", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess, onGetDirectoryFail);
 }

function onError(error) {
    console.log("onError ...");
}

function onGetDirectorySuccess(dir) {
     dir.getFile("myFile.html", {
        create: true,
        exclusive: false
    }, gotFileEntry, fail);
}

...

function readFile() {
    window.resolveLocalFileSystemURL(
            "//MyDir/myFile.html", gotFSRead,
            onErrorRead);
}

*

*What is the path for writing in my app's Isolated Storage?


text:
Q: can i use PyTorch Data Loader to load raw data images which are saved in CSV files? I have raw data images saved in separate CSV files(each image in a file). I want to train a CNN on them using PyTorch. how should I load data to be appropriate for using as CNN's input? (also, it is 1 channel and the image net's input is RGB as the default)

A: PyTorch's DataLoader, as the name suggests, is simply a utility class that helps you load your data in parallel, build your batch, shuffle and so on, what you need is instead a custom Dataset implementation.
Ignoring the fact that images stored in CSV files is kind of weird, you simply need something of the sort:
from torch.utils.data import Dataset, DataLoader

class CustomDataset(Dataset):

    def __init__(self, path: Path, ...):
        # do some preliminary checks, e.g. your path exists, files are there...
        assert path.exists()
        ...
        # retrieve your files in some way, e.g. glob
        self.csv_files = list(glob.glob(str(path / "*.csv")))

    def __len__(self) -> int:
        # this lets you know len(dataset) once you instantiate it
        return len(self.csv_files)

    def __getitem__(self, index: int) -> Any:
        # this method is called by the dataloader, each index refers to
        # a CSV file in the list you built in the constructor
        csv = self.csv_files[index]
        # now do whatever you need to do and return some tensors
        image, label = self.load_image(csv)
        return image, label

And that's it, more or less. You can then create your dataset, pass it to a dataloader and iterate the dataloader, something like:
dataset = CustomDataset(Path("path/to/csv/files"))
train_loader = DataLoader(dataset, shuffle=True, num_workers=8,...)

for batch in train_loader:
    ...


text:
Q:  Wont show up, yet it exists in the dom I can inspect element and see <input type="file" accept="image" />, it seems like the type="file" is causing the problem, when I remove it I can refresh and see the input box. I am wondering if this is a problem with angular 2 or if this is a problem with how I bootstrapped my application. This problem did not exist in previous iterations of angular 2, it only occurred within the last update to the "stable version" . I can post my component but there is nothing there but my selector and html reference . Any help appreciated to point me in the right direction to debug this! Thanks in advance

A: Had bad styling layered inside other components . I have much to learn


text:
Q: Makefile: How to correctly include header file and its directory? I have the following makefile:
CC=g++
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

all: Lock.o DBC.o Trace.o

%.o: %.cpp $(DEPS)
    $(CC) -o $@ $< $(CFLAGS)

clean:
    rm -rf *o all

This makefile and all three source files Lock.cpp, DBC.cpp, Trace.cpp are located in the current directory called Core. One of the source file Trace.cpp contains a line that includes a header file outside the current directory:
//in Trace.cpp
#include "StdCUtil/split.h"

The header file split.h is located at one level above the current directory and then in the subdirectory called StdCUtil. So that's why I added INC_DIR = ../StdCUtil in the makefile. The overall directory structure looks like the following:
root
  |___Core
  |     |
  |     |____Makefile
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

But when I make it, it gives me the error:
Trace.cpp:8:28: fatal error: StdCUtil/split.h: No such file or directory
 #include "StdCUtil/split.h"
                            ^
compilation terminated.
<builtin>: recipe for target 'Trace.o' failed

Why this doesn't find the header file split.h even if I specify the INC_DIR in the makefile? How to correct this?

A: The preprocessor is looking for StdCUtil/split.h in

*

*./ (i.e. /root/Core/, the directory that contains the #include statement). So ./ + StdCUtil/split.h = ./StdCUtil/split.h and the file is missing

and in

*

*$INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):
$INC_DIR = ../

or the include directive:
#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.
Reference:

*

*C++ #include semantics
EDIT/UPDATE
It should also be
CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

A: These lines in your makefile,
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

and this line in your .cpp file,
#include "StdCUtil/split.h"

are in conflict.
With your makefile in your source directory and with that -I option you should be using #include "split.h" in your source file, and your dependency should be ../StdCUtil/split.h.
Another option:
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/..  # Ugly!
DEPS = $(INC_DIR)/split.h

With this your #include directive would remain as #include "StdCUtil/split.h".
Yet another option is to place your makefile in the parent directory:
root
  |____Makefile
  |
  |___Core
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core and StdCUtil directories. Object, for example. With this, your makefile becomes:
INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS  = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.

DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.

all: $(OBJS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
  $(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/Trace.o: $(DEPS)

A: This is not a question about make, it is a question about the semantic of the #include directive.
The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include directive "StdCUtil/split.h".
To fix this, just use -I.. instead of -I../StdCUtil.

A: Try INC_DIR=../ ../StdCUtil.
Then, set CCFLAGS=-c -Wall $(addprefix -I,$(INC_DIR))
EDIT: Also, modify your #include to be #include <StdCUtil/split.h> so that the compiler knows to use -I rather than local path of the .cpp using the #include.


text:
Q: Sampling a stream of web requests at a fixed rate ensuring a relatively balanced sample of different request types I want to sample a stream of web requests hitting a web app. The requests will be sampled at some fixed rate e.g. 100 a minute.
Each web request will be classified by some key e.g. formed by hashing some combination of HTTP verb, path, query parameters etc. I want to ensure that every class of request is represented approximately evenly, basically a less common request should have a much higher chance of being sampled than a more common one. I also want to avoid just sampling the first requests that are seen in the time interval, to avoid performance problems when the time period starts.
Accuracy isn't hugely important, if it's 110 samples one minute and 85 the next it isn't a huge concern as long as it's close to 100 on average.
I've read about reservoir sampling for maintaining counts of recent requests. My question is - how do I figure out the probability to sample a request based on the recent counts, ensuring a relatively even number of samples of each class and taking into account the target rate? Or is there a better approach I'm not considering?


text:
Q: Please Help - "/dev/sda1 is mounted." E2fsck: Cannot continue, aborting." Thanks https://serving.photos.photobox.com/18156716f350a12bd31b61ca638825e809e811d642dc091097fdb48b9f5fac5062a5c74a.jpg
Here is the picture of my problem. I cannot boot my laptop and cannot log on to the ubuntu screen. I have serious problems as I have copied the wrong info on the data recovery through Test disk.
What actually happened:
1) Used testdisk and backed up 2 files. 1 file was not imoportant. Now the hard drive space is now completely full. I tried so many sources on Askubuntu and google but still no help.
2) Keep showing black screen with "_" flashing - The link that I uploaded is here.
Please help, cannot sleep until its done. Very important files including family and work is here.
Now my screen keeps blinking: https://www.youtube.com/watch?v=BN4twl0V8JQ
Thanks


text:
Q: node-red displaying msyql results using the dashboard node Newbie question: I've started playing with node-red and think it could be a great gateway drug for node.js (and javascript for that matter). But I'm already a bit stuck.
I have a flow which is performing a very simply query against a mysql database. I'm getting the results returned to me, but I have so far not been able to parse those results in any meaningful way. It looks the results are returned as an array, but how can I access and manipulate that array, in a function? Below is the data being passed in from the mysql node:
[
  { "at_time": "2017-03-27T18:33:46.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-27T22:14:02.000Z", "event": "woke_up" },
  { "at_time": "2017-03-27T22:14:12.000Z", "event": "food" },
  { "at_time": "2017-03-28T00:13:42.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T03:50:15.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:33.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:38.000Z", "event": "food" },
  { "at_time": "2017-03-28T06:56:29.000Z", "event": "up_for_day" },
  { "at_time": "2017-03-28T18:08:49.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-28T18:32:48.000Z", "event": "woke_up" }
]

Thanks!

A: JavaScript arrays have many functions available to help you work with their content. It is too broad a subject to provide a succinct answer without more details on specifically what you want to do.
As you identify, Node-RED is built using JavaScript and its Function node is no different.
Assuming your Function is receiving that array as msg.payload, you would use the following syntax to access the various elements:
var firstElement = msg.payload[0];
var secondElement = msg.payload[1];

and so on.
Each element of that array appears to be a JavaScript object - with key/value pairs. To access those values you would use the following syntax:
var first_at_time = firstElement.at_time;
var first_event = firstElement.event;

These are fundamental operations with javascript and there are plenty of guides available that will introduce you to them, such as: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays


text:
Q: Proof verification: $f$ is convex iff $f'$ is monotonically increasing This is (the first half of) exercise 14 in Baby Rudin

Let $f:(a, b) \to \mathbb{R}^1$ be differentiable. Prove that $f$ is convex iff $f'$ is monotonically increasing.

($\Rightarrow$) Assume $f$ is convex in $(a, b)$. Fix $0 < \lambda < 1$ and $a < y \le x < b$. Notice that
\begin{align}\tag{13.1}
        y \le x \implies y (1-\lambda) \le x (1-\lambda) \implies y - \lambda y \le x -\lambda x \implies \lambda x + y - \lambda y \le x
    \end{align}
By the definition of convexity, we have that
\begin{equation}\tag{13.2}
        f[\lambda x + y - \lambda y] \le \lambda f(x) + f(y) - \lambda f(y)
    \end{equation}
and differentiating (13.2) with respect to x, we have
\begin{equation}\tag{13.3}
        f^{\prime}[\lambda x + y - \lambda y] \cdot \lambda \le \cdot \lambda f^{\prime}(x) \implies f^{\prime}[\lambda x + y - \lambda y] \le f^{\prime}(x)
    \end{equation}
By (13.1) and (13.3), we conclude that $f'$ is monotonically increasing.
($\Leftarrow$) Suppose $f'$ is monotonically increasing. Fix $0< \lambda< 1$ and suppose $f$ is not convex. Then $\exists p, q \in (a, b)$ such that
\begin{equation}\tag{13.4}
        f(\lambda p + q - \lambda q) > \lambda f(p) +f(q) - \lambda f(q) \stackrel{\textrm{w.r.t. } p}{\implies} f'(\lambda p + q- \lambda q) > f'(p)
    \end{equation}
Without loss of generality, let $p \geq q$, which implies
\begin{align*}
        p (1-\lambda) > q (1-\lambda) \implies p - \lambda p > q -\lambda q \implies p > \lambda p + q - \lambda q
    \end{align*}
Since $f'$ is monotonically increasing, we get $f'(p) > f'(\lambda p + q- \lambda q)$ which contradicts (13.4).

Can someone please critique my proof? Please don't bother suggesting a new proof as those can be found here and here. I am new to handling derivatives in an abstract setting, so I am not sure if it is valid to differentiate (13.3) and preserve the direction of the inequality, like I did. Is there a theorem/ lemma that supports this move?

A: You can usually never differentiate inequalities.
If $f,g : ]a,b[ \rightarrow \mathbb R$ are differentiable,
$$
\forall x \in ]a,b[, \ f(x) \leq g(x)
$$
does not imply
$$
\forall x \in ]a,b[, \ f'(x) \leq g'(x).
$$
For example, take $f(x) = x^2$ and $g(x) = x$. We have $f(x) \leq g(x)$ on $[\frac{1}{2},1]$ and yet for all $x \in [\frac{1}{2},1]$, $f'(x) = 2x \geq 1 = g'(x)$.
The reason the result fails is because saying a function is above another does not tell us anything about how fast these functions grow comparatively.
You can try to draw a counter-example to convince yourself.
Hope this helps!


text:
Q: iOS5 storyboard UIPageViewController I am developing an application and I am using iOS5 storyboard. Basically what I have is a UITabBarController as the root controller which contains some UIViewController and a UISplitViewController. What I want to do is to use a UIPageViewController as the DetailController of the UISplitViewController. The problem is that the UIPageViewController doesn't show its view controllers but it shows a black screen. What I do is to initialize two content view controllers in the viewDidLoad method of the DetailController and assign them with the instruction:
[self setViewControllers:self.pagesViewControllerArray direction:UIPageViewControllerNavigationOrientationHorizontal animated:NO completion:nil];
so I cannot figure out where is the mistake.
The viewDidLoad method is the following:
- (void)viewDidLoad{

    self.dataSource = self;
    self.delegate = self;

    self.page1ViewController = [[Page1ViewController alloc] initWithNibName:@"Page1ViewController" bundle:nil];
    self.page2ViewController = [[Page2ViewController alloc] init];

    self.pagesViewControllerArray = [NSArray arrayWithObjects:self.page1ViewController, self.page2ViewController, nil];

    [self setViewControllers:self.pagesViewControllerArray direction:UIPageViewControllerNavigationOrientationHorizontal animated:NO completion:nil];

}

I tried to use both a viewcontroller with its nib associated and a viewcontroller with its view dynamically loaded but it is not working.
Any help would be really appreciated.
Thanks

A: First make sure viewDidLoad is being called. There are so many ways an instance may be initialized and I am not sure when each option is used. If initWithNibName is used then viewDidLoad will not be called, if I remember correctly. To make sure the method is called you can add an NSLog statement like...
NSLog(@"viewDidLoad: %@", NSStringFromClass([self class]));

That will show in the debugger console if it is being called. You can also add the initWithNibName method to see if that is called.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"initWithNibName: %@", NSStringFromClass([self class]));
    }
    return self;
}

I have found that Storyboards do not work as I expected. What I have started using is Container Views. There is nothing fancy about them. They are just visual elements you can place inside of a view which are then wrappers around a standard UIViewController and then the design surface shows the related view with the same dimensions as the container view you placed in the other view. Then you can manage the details there. If you do need to handle any initialization with the parent view controller you will use the prepareForSegue method. You will need to set the name for the embed segue for the container view (not a push segue like you usually see) and when it fires you can access the destinationViewController which is simply the embedded view controller inside of the container view. It may take some tinkering to figure it out.
Also look up UIPageViewController in the Documentation tab of the Organizer. There is a sample project listed at the bottom of the left column which you may find useful.


text:
Q: VS Setup Project - Sqlexpresschk.exe is not a valid win32 application when ran from Win XP KN Pro SP3 I need your help - I have a problem with getting a VS Setup to work on Windows XP KN SP3 because I encounter an error with Microsoft SQL Express Version Checker executable because "SqlExpressChk.exe is not a valid Win32 application" and I do not know how to fix it, having tried a lot of things already. Details follow.
I have a VS Setup project with 3 pre-requisites that are to be installed from the local machine (not downloaded). They are .NET 4 Framework, SQL Server 2008 R2 and Windows Installer 4.5. I have downloaded all the necessary bootstrapper files from MS Download Center and saved to the my local dev machine so the VS Setup project builds fine.
I am testing the Setup on Windows KN SP3 (running on Hyper-V) however when you run the setup, the following error occurs:

Which suggests that the executable is 64-bit. Why is Setup using a 64-bit version of the checker if it knows that we are on a 32-bit machine? If I can get my hands on a 32-bit version of this checker, then maybe the setup will continue, but I cannot find any.
Install log shows the following (although it maybe wrong, since if sqlexpresschk.exe wasn't run, then how would the logger know the actual values?):
Running checks for package 'SQL Server 2008 R2 Express', phase BuildList
Running external check with command 'SqlExpress2008R2\SqlExpressChk.exe' and parameters '10.50.1600 1033'
Process exited with code 0
Setting value '0 {int}' for property 'SQLExpressChk'
The following properties have been set for package 'SQL Server 2008 R2 Express':
Property: [SQLExpressChk] = 0 {int}
Running checks for command 'SqlExpress2008R2\SQLEXPR32_x86_ENU.EXE'
Result of running operator 'ValueNotExists' on property 'VersionNT': false
Result of running operator 'VersionLessThan' on property 'VersionNT' and value '5.1.3': false
Result of running operator 'VersionEqualTo' on property 'VersionNT' and value '5.2.0': false
Result of running operator 'VersionEqualTo' on property 'VersionNT' and value '5.2.1': false
Result of running operator 'ValueEqualTo' on property 'AdminUser' and value 'false': false
Result of running operator 'ValueEqualTo' on property 'SQLExpressChk' and value '-1': false
Result of running operator 'ValueEqualTo' on property 'SQLExpressChk' and value '-2': false
Result of running operator 'ValueEqualTo' on property 'SQLExpressChk' and value '-3': false
Result of running operator 'ValueEqualTo' on property 'SQLExpressChk' and value '-4': false
Result of running operator 'ValueLessThan' on property 'SQLExpressChk' and value '-4': false
Result of running operator 'ValueNotEqualTo' on property 'ProcessorArchitecture' and value 'Intel': false
Result of running operator 'ValueNotEqualTo' on property 'SQLExpressChk' and value '1': true
Result of checks for command 'SqlExpress2008R2\SQLEXPR32_x86_ENU.EXE' is 'Bypass'
Running checks for command 'SqlExpress2008R2\SQLEXPR32_x86_ENU.EXE'
Result of running operator 'ValueNotEqualTo' on property 'ProcessorArchitecture' and value 'Intel': false
Result of running operator 'ValueNotEqualTo' on property 'SQLExpressChk' and value '2': true
Result of checks for command 'SqlExpress2008R2\SQLEXPR32_x86_ENU.EXE' is 'Bypass'
Running checks for command 'SqlExpress2008R2\SQLEXPR_x64_ENU.EXE'
Result of running operator 'ValueNotEqualTo' on property 'ProcessorArchitecture' and value 'amd64': true
Result of checks for command 'SqlExpress2008R2\SQLEXPR_x64_ENU.EXE' is 'Bypass'
Running checks for command 'SqlExpress2008R2\SQLEXPR_x64_ENU.EXE'
Result of running operator 'ValueNotEqualTo' on property 'ProcessorArchitecture' and value 'amd64': true
Result of checks for command 'SqlExpress2008R2\SQLEXPR_x64_ENU.EXE' is 'Bypass'
'SQL Server 2008 R2 Express' RunCheck result: No Install Needed

It is bypassing the install, because of
Result of running operator 'ValueNotEqualTo' on property 'SQLExpressChk' and value '1': true

Since in package.xml:
<BypassIf Property="SQLExpressChk" Compare="ValueNotEqualTo" Value="1"/>

I don't understand what does that value reflect, but maybe one of you do?
What do you think?
Regards,
Sergey
p.s.
Things I've tried include re-downloading the packges, re-building the project, installing sql server 2008 r2 on the target windows xp machine (setup runs fine on its own, btw) and trying to find a local version of the version checker, but couldn't find one. Even trying to modify EF Models to work on SQL CE so I wouldn't need to depend on SQL Express, but I get a separate problem in EF which prevents me from doing that. Restarting win xp many times.

A: I think I figured it out.  First, I backed up C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\Bootstrapper\Packages\SqlExpress2008R2\SqlExpressChk.exe.  Then, I copied the SqlExpressChk.exe from C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\SqlExpress2008 to C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\Bootstrapper\Packages\SqlExpress2008R2.
I found another article online that verified that I wasn't crazy: https://robindotnet.wordpress.com/2010/03/21/how-to-pass-arguments-to-an-offline-clickonce-application/


text:
Q: Binding Date and Time to a single Date model in Angular I have a requirement to allow a user to set a date & time for the start and end of a date range. Since input type datetime-local is currently unsupported in firefox and IE I can't use it. So I was hoping to share a single date model across a date and time input.
Like so:

  angular.module('date.deleter', [])
    .controller('DateDeleteController', function($scope) {
      //force display to be a bit more human-readable
      var loadedAt = new Date(new Date().toISOString().slice(0, 19));
      $scope.data = {
        theDate: loadedAt,
        minDate: loadedAt
      };
    })
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css" />

Change Something And Watch Date Dissappear o_O

    <input type="date" id="theDate" name="theDate" ng-model="data.theDate" min="{{data.minDate | date:'yyyy-MM-dd'}}" placeholder="yyyy-MM-dd">
    <input type="time" id="theStartTime" name="theStartTime" ng-model="data.theDate" min="{{data.minDate | date:'HH:mm:ss'}}" placeholder="HH:mm:ss">

output the scope here

{{data}}

In the snippet I set a single date object to be the model of a date and a time input. And then output the scope data object into a div so I can see what is happening. I also set the min of the inputs to be the date and time they load.
If you load the snippet then change the values you'll notice that at some settings not just is the input marked as invalid but the date object disappears from the scope entirely. Sometimes to be returned when you undo your change.
Is this expected behaviour? Am I trying to do something crazy in exposing a separate date & time input as a single datetime model?

A: So, for the benefit of people who may end up here via Google I was trying to do something crazy!
The documentation for the time input says:

Model must be a Date object. This binding will always output a Date object to the model of January 1, 1970, or local date new Date(1970, 0, 1, HH, mm, ss)

So if you change the time field then the date of the bound model might be set to 1/1/1970. I also noticed that the timezone was applying as well so sometimes setting 00:15 in the time field would actually set 23:15 the day before.
However, if the model is marked as invalid it disappears from the scope. I think that is very weird but I can live with it now I know.


text:
Q: Convert nested hash table recursively in Perl I have a nested hash table, like this:
{"a": {"b": {"c": {"d": "", "e": ""},
             "m": ""},
       "f": ""},
 "h": {"i": {"j": "", "k": ""}
      }
}

And I would like to convert it to format like this:
[
    {"title": "a", "isFolder": true,
        "children": [
            {"title": "b", "isFolder": true",
                "children": [
                    {"title": "c", "isFolder": true",
                        "children": [
                            {"title": "d"},
                            {"title": "e"}
                        ]
                    },
                    {"title": "m"}
                ]
            },
            {"title": "f"},
            {"title": "g"}
        ]
    },
    {"title": "h", "isFolder": "true",
        "children": [
            {"title": "i", "isFolder": "true",
                "children": [
                    {"title": "j"},
                    {"title": "k"}
                ]
            }
        ]
    }
]

So I wrote a program:
#!/usr/bin/perl

use JSON;

$json = JSON->new->allow_nonref;

$struct = [];
sub convertRaw() {
    ($raw, $ts) = @_;

    foreach (keys %$raw) {
        if ($raw->{$_}) {
            push @$ts, {"title" => $_, "isFolder" => "true", "children" => []};
            &convertRaw($raw->{$_}, @$ts[-1]->{"children"});
        }
        else {
            push @$ts, {"title" => $_};
        }
    }
}

$raw_struct = {"a"=> {"b"=> {"c"=> {"d"=> "", "e"=> ""},
                             "m"=> ""},
                      "f"=> ""},
               "h"=> {"i"=> {"j"=> "", "k"=> ""}
                     }
              };

&convertRaw($raw_struct, $struct);

print $json->pretty->encode($struct)."\n";

However, the output turned out to be this:
[
   {
      "isFolder" : "true",
      "children" : [
         {
            "isFolder" : "true",
            "children" : [
               {
                  "title" : "k"
               },
               {
                  "title" : "j"
               },
               {
                  "title" : "a"
               }
            ],
            "title" : "i"
         }
      ],
      "title" : "h"
   }
]

Really confused. Could you figure out what's the problem here?

A: You have globally declared variables $raw and $ts. So hash updates during child element processing will affect future processing of parent elements. Declare them as lexically scoped variables:
sub convertRaw {
    my ($raw, $ts) = @_;
    # the rest of the code


text:
Q: Clojure Liberator: get request body twice Let's assume, that I've got an endpoint POST /endpoint that takes JSON as input data:
POST /endpoint
{
  "resource": {
    "name": "great"
  }
}

Now, I want to check whether the incoming JSON is valid. I thought that :malformed? hook would be a great place for doing that.
So I came up with such a code:
(ANY "/endpoint" []
     (resource
      :allowed-methods [:post]
      :available-media-types ["application/json"]
      :malformed? (fn [ctx] (let [body (get-body-from-request ctx)
                                   is-malformed (not (is-body-valid body))]
                                is-malformed)
      :post! (fn [ctx] (let [body (get-body-from-request ctx)]
                          (create-an-object body)))
      :handle-created (fn [ctx] {:method :post :body (:body @request)})))

So my intention was:

*

*get the body from request, check if it's valid (is-body-valid)

*in post! hook, use the body again and do real work (create-an-object)

The problem here is the get-body-from-request function:
(defn get-body-from-request [ctx]
  (json/read-str (slurp (get-in ctx [:request :body])) :key-fn keyword))

It works perfectly but the body is an InputStream,  so I can read it only once.
Is there a way to use body of the request in more than one hook NOT using atoms?
The solutions coming to my mind:

*

*A middleware wrapper that adds a string version of body to the ctx param.

*Pass the result of malformed? to post!...

*Use atoms.

Thanks!

A: OK, it was pretty easy, there's of course a wrapper that does that...
[ring-json-params "0.1.3"]
Then you just wrap your app handler:
(ns my.app
  (:require [ring.middleware.json :refer [wrap-json-params]]))

(def app
  (-> handler
      (wrap-json-params)))

and in your ctx object you've got a json-params object:
:malformed? (fn [ctx] (let [params (get-in ctx [:request :json-params])]
                        false))


text:
Q: Kendo Grid. Razor Mode. Column Sorting I'm using Kendo UI Grid in my current project. I found out that Sorting doesn't work if column has Template.
In following solution fix only for javascript grid realization:
http://www.kendoui.com/forums/kendo-ui-web/grid/row-template-sorting.aspx
How to achive sorting in Razor mode?
Example of column with template:
     columns.Bound(e => e.OrderNumber).Template(e => @Html.ActionLink(e.OrderNumber.ToString(), "Test", "Test"));

A: Creating a Template for the column and/or using a RowTemplate should not affect the sorting support.
Here is an example via JavaScript (Razor outputs JavaScript at the end and should make no difference)
$("#grid").kendoGrid({
    dataSource: dataSource,
    pageable: true,
    sortable:true,
    rowTemplate:"foo #= ProductID#",
    height: 430,
    toolbar: ["create"],
    columns: [
        { field:"ProductName", title: "Product Name" },
        { field: "UnitPrice", title:"Unit Price", format: "{0:c}", width: "100px" },
        { field: "UnitsInStock", title:"Units In Stock", width: "100px" },
        { field: "Discontinued", width: "100px" },
        { command: ["edit", "destroy"], title: " ", width: "160px" }],
    editable: "popup"
});


text:
Q: Designing correctly Java Classes Lets say I have the classes DrugAmount:
package core;

public abstract class DrugAmount {

    boolean drugInMg = false;
    boolean drugInMl = false;
    double numberofAmpoules = 0.0;
    double ampoulesInML = 0.0;
    double ampoulesInMG = 0.0;

    public DrugAmount() {
    }

    public DrugAmount(int numberOfAmpoules) {
        setNumberofAmpoules(numberOfAmpoules);
    }

    // SETTER:

    private void setNumberofAmpoules(int numberOfAmpoules) {
        this.numberofAmpoules = numberOfAmpoules;
    }

    // GETTER:

    public double getNumberOfAmpoules() {
        return numberofAmpoules;
    }

    public double getAmpoulesInML() {
        return ampoulesInML;
    }

    public double getAmpoulesInMG() {
        return ampoulesInMG;
    }

    public boolean isDrugInMl() {
        return drugInMl;
    }

    public boolean isDrugInMg() {
        return drugInMg;
    }

}

And the classes DrugAmountMg:
package core;

public class DrugAmountMg extends DrugAmount {

    public DrugAmountMg(double drugAmount) {
        super();
        setDrugInMg();
        setAmpoulesMG(drugAmount);
        setNumberOfAmpoules();
        turnDrugFromMgToMl();
    }

    public DrugAmountMg(int drugAmount) {
        super(drugAmount);
        setDrugInMg();
        setAmpoulesMG();
        turnDrugFromMgToMl();
    }

    private void setNumberOfAmpoules() {
        numberofAmpoules = ((1 / Ampoule.AMOUNT_OF_ONE_AMPOULE_IN_MG) * getAmpoulesInMG());
    }

    private void setAmpoulesMG() {
        ampoulesInMG=(Ampoule.AMOUNT_OF_ONE_AMPOULE_IN_MG*getNumberOfAmpoules());
    }

    private void setAmpoulesMG(double drugAmount) {
        ampoulesInMG=drugAmount;
    }

    private void turnDrugFromMgToMl() {
        if (isDrugInMg()) {
            ampoulesInML=(Ampoule.AMOUNT_OF_ONE_AMPOULE_IN_ML / Ampoule.AMOUNT_OF_ONE_AMPOULE_IN_MG) * getAmpoulesInMG();
        }
    }

    private void setDrugInMg() {
        drugInMg = true;
    }
}

Like you can see there are "package private" object variables in the class DrugAmount - is this good java practice?
Or should I modify them to private and declare new object variables in the child class DrugAmountMg and assign them the value of the DrugAmount-variables by getter-methods?

A: You could leave them as they are, but will you really ever need to access them from other classes in the same package that are not subclasses? I would make them protected in the base class.
You should definitely not declare new fields in the child class. The class would then have two of each field (say, drugInMg for instance), and even though only one of them would be in scope in the source code of the child class, you could run into trouble if you were to try to set the private field through reflection, for example in a unit test. On the project I'm working on we have occasionally run into problems with that, where a class has fields with the same type and name declared as private fields at different points in the class hierarchy, and unit tests that use a reflective utility to set up the private field fail because they've set the wrong one.
I'm not sure what you mean by "assign them the value of the DrugAmount-variables by getter-methods". I suspect you meant that you would make the fields private in the base class, create getters, duplicate the fields in the child class, and get the value from the base class to set up the child? Again, duplicating fields in this way is a bad idea.
The other thing you could do is make the fields private in the base class and provide getters and setters to allow the child classes to update the fields, but that creates the potential for outsiders to call the setters. You could make the setters protected or package-private, but why not just make the actual fields protected? Then only subclasses can access them.


text:
Q: What is the proj4js projection code for the Gall-Peters Projection? Does the Proj4JS library support the Gall-Peters projection? I can't seem to find a projection acronym for it?

A: The code you are looking for is "cea" for Cylindrical Equal Area.
The actual definition will be:
"+proj=cea +lon_0=0 +x_0=0 +y_0=0 +lat_ts=45 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"

Change the value of lat_ts to 44.138 for the strict Peter projection, although as your title implies, the Gall and Peters projections are virtually the same (I won't get into *that * political argument, thank you!).
Some prefer the Behrman which is similar but with a lat_ts of 30. This produces less distortion of the equatorial regions (something Peters was claiming he was trying to fix!) .


text:
Q: How to add newline to text file in comprehensive nested list? I have a nested list:
A = [['a', 'b', 'c', 'd', 'e'], ['a', 'a', 'b', 'c'], ['b', 'c'], ['a', 'd']]

I want to save list A to multiple text files with the limitation of 2 nested list per text file.
So the output should be like:
in small_file_2.txt:
a
b
c
d
e

a
a
b
c

in small_file_4.txt:
b
c

a
d

I tried this code:
lines_per_file = 2
for lineno, line in enumerate(A):
    if lineno % lines_per_file == 0:
        if smallfile:
           smallfile.close()
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
        smallfile = open(small_filename, "w")
     smallfile.write('\n'.join(str(x) for x in line)+'\n')
smallfile.close()

Unfortunately, the output in text files are not as I expected it to be. It does not print the newline for after every new nested list.

A: The fix is fairly simple:
\n.join([]) adds \nbetween every item, but not before and after. The first \n you've added just added one afterwards. If you want it separated, you need a second one.
lines_per_file = 2
for lineno, line in enumerate(A):
    if lineno % lines_per_file == 0:
        if smallfile:
           smallfile.close()
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
        smallfile = open(small_filename, "w")
    smallfile.write('\n'.join(str(x) for x in line)+'\n\n')         # <= add a second \n
smallfile.close()

A: Second approach with with and no empty lines at the end:
lines_per_file = 2
for lineno in range(0, len(A), lines_per_file):
    small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
    with smallfile = open(small_filename, "w"): #this will close the file by itself
        smallfile.write('\n\n'.join('\n'.join(str(x) for x in A[current])) for current in range(lineno, min(lineno+lines_per_file, len(A)))

Let's explain the magic:
for lineno in range(0, len(A), lines_per_file):

We'll be taking all lines from 0 to lines_per_file-1, then lines_per_file to 2*lines_per_file-1... Until the end.
'\n'.join(str(x) for x in A[current])

This is what you used, but we call the line directly from A. Parses one line as single characters in multiple lines.
'\n\n'.join(...)

Parsed lines will have two linebreaks between each other - that means there will be an empty line you wanted.
for current in range(lineno, min(lineno+lines_per_file, len(A))

As I said, we are taking lines from lineno (that is: 0, lines_per_file, 2*lines_per_file...) until the next step. Or until the end of the A, whichever is shorter (that's why there's min).

A: Below code will work fine as per your requirement.
lines_per_file = 2
for lineno, line in enumerate(A):
    if lineno % lines_per_file == 0:
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
    smallfile = open(small_filename, "a")
    smallfile.write('\n'.join(str(x) for x in line)+'\n')
    smallfile.write('\n')
    smallfile.close()
smallfile.close()


text:
Q: XML Parsing fails at empty line after body I'm trying to parse an xml file and .parse() returns false and I don't know why. It fails at the next line after I close the body. Anyone has a clue why this is happening? My code is below and I've attached some screenshots as well:
func parseXMLFileWithName(_ name : NSString) {
    let path = String(Bundle.main.path(forResource: name as String, ofType: "xml")!)
    let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
    let parser = XMLParser(data: data as Data)
    parser.delegate = self
    if !parser.parse() {
        let error = parser.parserError
        let line = parser.lineNumber
        let col = parser.columnNumber
        print("XML parsing failed at \(line):\(col): \(error?.localizedDescription ?? "")")
    }
}

private func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [AnyHashable: Any]) {

    if elementName == "word" {

        let newWord = NSMutableDictionary()
        var correctWord = true
        var currentType = ""

        if let type = attributeDict["type"] as? String {
            newWord["type"] = type
            currentType = type
        } else {
            correctWord = false
        }

        if let value = attributeDict["value"] as? String {
            newWord["value"] = value
        } else {
            correctWord = false
        }

        if let trans = attributeDict["trans"] as? String {
            newWord["trans"] = trans
        } else {
            correctWord = false
        }

        //if everything was ok, tag "word" has all 3 attributes than i add the new dictionary to the array of nsdictionary
        if correctWord == true {
            let wordDict = NSDictionary(dictionary: newWord)
            allElements.append(wordDict)
            if currentType == "word" {
                words.append(wordDict)
            }

            if currentType == "phrase" {
                phrases.append(wordDict)
            }

            if currentType == "dict" {
                dicts.append(wordDict)
            }
        }
    }
}

Edit: I'm not getting the error anymore. I was calling parser.parse() too many times. Problem is it won't append my dicts dictionary.


text:
Q: Integral over the Japanese bracket I want to show that
$$\int \langle x\rangle^{-1-\epsilon} dx = \int (1+|x|^2)^{\frac{-1-\epsilon}{2}}dx$$
converges for $\epsilon>0$. Assume we're on $\mathbb{R}$. Because of symmetry we can integrate from $0$ to $\infty$ modulo a constant:
$$\int_0^{\infty} (1+r^2)^{\frac{-1-\epsilon}{2}}dr$$
Now I'm a bit helpless because I haven't found a way to calculate this integral just yet. Please provide me some hint how to proceed (subsitution, partial integration, etc.)

A: There are multiple ways to show that the integral converges, as suggested by the comments. We can substitute $t=r^2$ and obtain (replace $dr$ by $(4t)^{-1/2}dt$)
$$ \frac{1}{2}\int_0^{\infty} (1+t)^{-(1+\epsilon)/2}t^{-1/2}dt$$
Another substitution $(1+t)^{-1} =s $ yields
$$ I= \frac{1}{2} \int_0^1 \frac{s^{\epsilon/2 - 1}}{(1-s)^{1/2}}ds$$
(the minus sign from the derivative of the map $t\mapsto (1+t)^{-1}$ is reversed by flipping the transformed integral boundaries $1$ and $0$). This integral is known as the Beta function $\frac{1}{2} B(\epsilon/2,1/2)$ which is known to converge.
Another approach is to split the integral into to parts:
$$\int_0^1 (1+r^2)^{-(1+\epsilon)/2} dr + \int_1^{\infty} (1+r^2)^{-(1+\epsilon)/2} dr$$
Since $(1+r^2)$ is never zero, the integrand of the first integral is bounded and since the integral is over a compact set it is finite. For the second integral observe that $(1+r^2) > r^2$ for all $r$ and so
$$ (1+r^2)^{-(1+\epsilon)/2} \leq r^{-(1+\epsilon)}$$
Now
$$\int_1^{\infty} r^{-(1+\epsilon)} dr = r^{-\epsilon}|_1^{\infty} $$
which is finite (In hindsight the problem was really easy. Apparently I'm a really lazy person, apologies).


text:
Q: where is the implicit being supplied from when i invoke akka.http.scaladsl.Http.apply()? I am using Akka HTTP for REST support, and I need to use Actors in another part of the
server I'm developing.  My understanding is that one typically needs to use exactly ONE ActorSystem
instance throughout one's application.  From the definition of akka.http.scaladsl.Http.apply(),
it seems that when I use the Http method, as in the snippet from my code below --
val service: FooRestService = new FooRestService()
Http(). bindAndHandle(service.route, "localhost", 8080)   // something is supplying the imply method w/ implicit ActorSystem !

--- somehow the Http object's apply() method is getting supplied with an implicit ActorSystem instance...  For easy reference, Http.apply() is defined like this:
package akka.http.scaladsl.Http
        ...
    object Http {
        ...
      def apply()(implicit system: ActorSystem): HttpExt = super.apply(system)

Since I need to stick to exactly one ActorSystem instance, I want to supply the other (non-REST) Actor-based code in my system with the
SAME reference as the one that is being supplied to the Http apply() method.
I guessed that my code must be doing a package import of a package with a package object with an implicit ActorSystem, or there
must be some other way this implicit is slipping in like a ninja in the dead of night. I've poked around quite a bit,
but couldn't figure it out ;^(
Any suggestions much appreciated !

A: Not sure I fully understood what the problem is but in your every actor you have context: ActorContext. You can obtain ActorSystem from context.system. Thus you don't need to explicitly pass ActorSystem around.

A: Here is how I used @expert's answer (above) to debug where my implicit was coming from.  The key thing is to dump out the system variable from the Actor that is getting the implicit.. then look at the name to figure out where the implicit came from. In my case the implicit was coming from my own code (how dumb!).    Anyway.. thanks to the answer above my problem is solved.
    val http: HttpExt = Http()
    val sys = http.system
    System.out.println("sys:" + sys);
    http. bindAndHandle(
        service.route, "localhost", injector.getInstance(classOf[Conf]).getInt(PROVISIONER_PORT )
      )


text:
Q: Devise Rails reset_password method is not working According to the documentation the method reset_password of the Devise gem of Ruby should work like this:
User.find(1).reset_password('password123', 'password123')

This method is returning true, but when I try to login with this user and the new password (or even with the old password) the app won't let me and log "Completed 401 Unauthorized".
Also I am using omniauth to be able to login socially.


text:
Q: Java animation, with key listener I tried to make it so that,if I pressed the right/left key, the sprite/Mario would face right/left. If I pressed the right key, he would face right. But for some reason, When I pressed the left key, he won't face left.
Source Code: First ,Second
Images

A: "To fire keyboard events, a component must have the keyboard focus."—How to Write a Key Listener

A: Don't use a KeyListener. Instead use Key Bindings which are more flexible and are used by all Swing components.


text:
Q: Сохранение файлов webpack по разным папкам? В доках webpack имеется:
module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist'
  }
};

Получается, что в entry можно указать путь до любого файла в src.
Вопрос: как правильно на настоящий момент в webpack 4 указывать в output пути до разных папок, например сохранить app.js в /dist/app/, а search.js в /dist/search/?

A: К сожалению - никак. You can only have one output path., но можно использовать несколько конфигов и экспортировать массив с этими конфигами:
// webpack.config.js

const { join } = require('path');

const appConfig = {
    entry: './src/app.js',
    output: {
        filename: '[name].js',
        path: join(__dirname, 'dist/app')
    }
};

const searchConfig = {
    entry: './src/search.js',
    output: {
        filename: '[name].js',
        path: join(__dirname, 'dist/search')
    }
};

const common = {
    context: __dirname,

    module: {
        rules: [...]
    }
};

module.exports = [{
    ...common,
    ...appConfig
}, {
    ...common,
    ...searchConfig
}];


text:
Q: Can I use other open source libraries in the application contest? I just found out about and started looking into the Ubuntu App Contest, and I wanted to double check the contest's stance on using open source libraries built by others that are freely available on the web.
I read through the rules and some of the other Q&As, and it sounds like using these libraries would not be allowed (since it could mean the app isn't built from scratch, and the library would not be in the Ubuntu archive - although I could bundle the library with the app), and I just wanted to verify this assumption.

A: You are free to use any libraries you choose as long as they are available to the user using the normal Ubuntu app installation method. This means that the library needs to be in the archives already, or included with your application.  As long as you can do one of these, the application is admissible for the App Showdown contest.  Be aware that your entry will be judged only on the code you wrote and the value it adds on top of the libraries you are using.


text:
Q: How to prove $ L_X(\omega(Y)) = (L_X\omega)Y + \omega(L_XY)$ starting from the fundamental definition of Lie derivative? The Lie derivative of a smooth real valued function $f$ along a vector field $X$, on a point $p$ in some smooth manifold is given as
$$
L_X f(p) :=  \lim_{h\to 0} \frac{1}{h}\left[ f(\phi(p)) - f(p) \right]\label{Lief}\tag{1}
$$
The Lie derivative of a vector field $Y$ along another vector field $X$, on a point $p$ in some smooth manifold is given as
$$
L_X Y(p) =\frac{d}{dt}\left[\phi_{-t*}Y(p)\right] :=  \lim_{h\to 0} \frac{1}{h}\left[ (\phi_{-h*}Y)_p - Y_p \right]\label{Liev}\tag{2}
$$
$\phi_t$ is the integral curve of the vector field $X$, with the push-forward map defined by
$$(\phi_{-h*}Y)_p  = \phi_{-h*}Y_{\phi_h(p)}$$
Similarly, the Lie derivative of a one-form $\omega$ along a vector field $X$, is given by
$$
L_X \omega(p) =\frac{d}{dt}\left[\phi_{t}^*\omega\right](p) :=  \lim_{h\to 0} \frac{1}{h}\left[ (\phi_{h}^*\omega)_p - \omega_p \right]\label{Lieo}\tag{3}
$$
$$
(\phi_h^* \omega)(p)(X_p) = \omega(\phi_h(p)) (\phi_{h*}X_p)
$$

Now, I want to prove that the Lie derivative
$$
L_X(\omega(Y)) = (L_X\omega)Y + \omega(L_XY)
$$
The function $\omega(Y)(p) = \omega_p (Y_p)$, as $\omega(Y)(p)$ is a function it's transformation rule should be something like
\begin{align}
L_X(\omega(Y)) &=  \lim_{h\to 0} \frac{1}{h}\left[ (\phi_{h}^*(\omega(Y)))_p - (\omega(Y))_p \right] \label{LiewY}\tag{4}
\end{align}

*

*Is the equation \eqref{LiewY} the right way to begin?, or the expression be more like \eqref{Lief} as $\omega(Y)$ is a real valued function over the manifold,

*I am not sure how $(\phi_{h}^*(\omega(Y)))_p$ in \eqref{LiewY} will look when
simplified.

This question has an answer here but in terms of Cartan's formula.
I'd like to know how to start from the very basic definition of Lie derivative

A: A naive manner to prove basic formulae in Differential Geometry consists in writing everything in local frame and coframe.
Let $\partial_1, \ldots, \partial_n$ denote a local frame around $p$ and $e^1, \ldots, e^n$ its dual coframe. Write our vector fields and forms in these bases:
$$X = x^i \partial_i,\ Y = y^i \partial_i,\ \omega = \omega_i e^i.$$
But $\omega(Y) = \omega_i y^i$ is a function and the Lie derivative for function is just the usual directional derivative. So by the usual Leibniz rule, we have
$$\mathcal{L}_X(\omega(Y)) = \mathcal{L}_X(\omega_i) y^i + \omega_i \mathcal{L}_X (y^i) = x^j \partial_j \omega_i y^i + \omega_i x^j\partial_j y^i.$$
It is well known that $\mathcal{L}_X(Y) = [X, Y]$. Thus
$$ \mathcal{L}_X(Y) = (x^j \partial_j y^i - y^j \partial_j x^i)\partial_i\mbox{ and }
\omega(\mathcal{L}_X(Y)) = \omega_i(x^j \partial_j y^i - y^j \partial_j x^i).$$
Finally, $\phi_t^{\star}\omega = \omega_i(\phi_t) e^i \circ d\phi_t$. Thus by the Leibniz rule again
$$ \left.\frac{d}{dt}\right|_{t=0} \phi_t^{\star}\omega = \left.\frac{d}{dt}\right|_{t=0} \omega_i(\phi_t) e^i + \omega_i \left.\frac{d}{dt}\right|_{t=0} e^i \circ d\phi_t = \{x^j \partial_j \omega_i + \omega_j \partial_i x^j \} e^i.$$
Hence, $\mathcal{L}_X(\omega)(Y) = \{x^j \partial_j \omega_i + \partial_i x^j \omega_j\} y^i.$ Simplify terms to conclude.
A more sophisticate manner to prove the equality consists in using tensorial algebra.
All your definitions of Lie derivatives are particular cases of the Lie derivative of tensor fields. For any tensor field $T$ on your manifold, the Lie derivative is given by
$$ \mathcal{L}_X(T) = \left.\frac{d}{dt}\right|_{t=0} (\phi_{-t})_{\star} T_{\phi_t}$$
Now, it is easy to prove that the Lie derivative commutes with contractions and satisfies the following Leibniz rule for the tensor product:
$$ \mathcal{L}_X(T \otimes S) = \mathcal{L}_X(T) \otimes S + T \otimes \mathcal{L}_X(S).$$
But $\omega(Y)$ is a contraction of $\omega \otimes Y$ and the terms of the right-hand side of your equality are given by the same contraction.


text:
Q: Why are inner class not public when viewed in reflection? AKA why does this test fail?
[TestFixture]
public class Tests
{
    [Test]
    public void InnerClassShouldBePublic()
    {
        Assert.IsTrue(typeof (InnerClass).IsPublic);
    }

    public class InnerClass
    {
    }

}

A: It fails because nested types are not considered Public, they are considered NestedPublic instead.
From the IsPublic() MSDN documentation:

Do not use with nested types; use IsNestedPublic instead.


text:
Q: Autorun Excel VBA script when outlook saves attachment I have an outlook procedure that auto saves an excel attachment to a certain location on my hard drive.
I also have a VBA script in Excel that is designed to use the data from that file and send off emails to particular parties. Normally I would have to open the file and run the VBA script. Is there a way to have this VBA script auto-execute once the file is saved from outlook?

A: The macro in the excel file won't run just because you have saved it.
However, you can run the macro by opening the workbook and calling the macro at Workbook_Open event
1.Open the workbook from outlook programatically
2.Let's say your macro procedure is Sub runMe() then you could write following function in Workbook
Private Sub Workbook_Open()
   Call runMe
End Sub

3.After the macro is completed, close the workbook programatically.


text:
Q: Duplicate dominating parents when using Deterministic Crowding in Genetic Algorithm This is pseudocode for using deterministic crowding:
for i from 0 to N/2
     p1, p2 = select_two_random_individual()
     c1, c2 = crossover(p1, p2)

     c1 = mutate(c1)
     c2 = mutate(c2)

     if((d(p1, c1) + d(p2, c2)) < (d(p1, c2) + d(p2, c1))
          population.add(Winner between p1 and c1)
          population.add(Winner between p2 and c2)
     Else
          population.add(Winner between p1 and c2)
          population.add(Winner between p2 and c1)

Which d is a function that determines the difference between two individual.
The question is, what happens if an individual gets selected two times as parent, and wins over its child both times? Do I end up with duplicate individual in new population?

A: Yes, it is not uncommon to have duplicate individuals in a population. It is in fact expected that at some point all solutions will converge to an optimal, this is where all solutions in a population are the same. This is only a problem when there is premature convergence.


text:
Q: Como funciona o "padding" do C/C++? Em várias respostas aqui no StackOverflow tenho percebido os usuários comentando sobre padding nas estruturas de dados.
struct {
  int a;
  char b;
  float d;
}

*

*O que vem a ser este padding (enchimento) que existe entre os campos de uma struct?

*Ele ocorre apenas em structs ou pode ocorrer em classes também?

*Como posso evitá-lo? (Otimizar o código)

A: O que é
Isto é usado para facilitar o trabalho de leitura de memória e colocação em registradores. Os registrados trabalham com um tamanho fixo de acordo com sua arquitetura. O ideal é que os dados caibam dentro deste tamanho. Então os dados são armazenados em palavras. O padding (ou preenchimento) alinha estes dados acrescentando bytes não significativos. Os compiladores fazem isto por padrão. Se precisa de um comportamento específico é necessário o uso de diretivas indicando a forma necessária.
Para todos os efeitos classes são estruturas (structs) e funcionam da mesma forma.
Desperdício
No seu exemplo a estrutura provavelmente terá 12 bytes (arquitetura de 32 bits) já que o membro b será preenchido com 3 bytes extras para fazer o padding. Assim todos os membros terá 4 bytes. Este número é obtido levando em consideração que a maioria das arquiteturas possuem uma palavra com 4 bytes de tamanho.
Evidentemente em arquiteturas 64 bits o estrago é ainda maior (e é possível ter preenchimento ainda maior), você pode ter até 7 bytes de desperdício. A palavra costuma refletir como os registrados são usados nos processadores. Note que estou usando dados comuns nas principais arquiteturas. Compiladores C e C++ são liberais quanto ao tamanho de quase todos os tipos se aplicando um tamanho mínimo.
Eliminar o padding pode otimizar em alguns casos o consumo de memória mas pode causar outros problemas de performance. Ler dados da memória em tamanhos diferentes da palavra da arquitetura precisam de processamento extra. Na maioria dos casos não compensa a troca.
Economizando
Claro que há casos que podem haver o preenchimento natural mantendo o uso da palavra:
struct {
    int a;
    char b;
    char c;
    char d;
    char e;
    float f;
}

Esta estrutura pode muito bem ter os mesmo 12 bytes. Os 4 chars cabem no alinhamento da palavra. Então pensar a ordem dos membros pode ser bastante útil.
Esta é a forma mais recomendada de resolver o problema. Ele não possui nenhuma desvantagem para o software em si. Claro que eventualmente você terá que colocar dados em uma ordem que não é tão intuitiva para ler.
Mesmo neste caso você só terá uma vantagem de consumo de memória clara se a estrutura for usada repetidas vezes em outra estrutura. Economizar alguns bytes não vale o esforço. Economizar alguns bytes multiplicado por milhões de vezes pode fazer alguma diferença.
Mas também é possível controlar como o padding é feito com diretivas (muitas vezes não padronizadas entre compiladores). Exemplo:
Quando realmente precisa, podemos fazer o packing. Exemplos em empacotamento.
#pragma pack(1)

No C++ da Microsoft, como outros compiladores que seguem o padrão do C,  torna o tamanho em 1 byte eliminando de fato qualquer padding. Claro que membros com mais de 1 byte terão seu tamanho normal. Isto indica o tamanho mínimo que o membro deve ter. No GCC poderia usar opcionalmente:
__attribute__((packed))

Coloquei no GitHub para referência futura.
Desta forma informa-se que um membro específico deve não receber o padding. Isto é mais flexível mas pode ser inseguro em certas plataformas.
Empacotar membros é arriscado e se não souber bem o que está fazendo poderá ter resultados inesperados. Bom, quase tudo em C e C++, mas alguns recursos são mais arriscados.
Mesmo a forma considerada padrão não é considerada portável.
Obviamente podemos usar o operador sizeof para descobrir o tamanho real do dado. Este operador devolve sempre o tamanho exato que o dado ocupa na memória e não a soma de seus membros. Ou seja, ele considera o preenchimento.
Reforço que raramente estes procedimentos são necessários. Quase sempre a tentativa de empacotar estruturas é otimização prematura. Por tornar o uso das estruturas menos intuitivo a recomendação é evitar até que se prove ser fundamental.
Artigo na Wikipedia.
Artigo interessante.


text:
Q: Reading the body of SMIME encrypted email I have an Outlook addin which handles outgoing emails using the ItemSend event. as part of the handling I read the body and attachments of the outgoing email.
when the user encrypts the email message (SMIME) in one environment my addin cannot read the body of the email - PR_BODY_W property (I assume that the body is in the smime.p7m). However, in a different environment my addin does find and read the PR_BODY_W successfully.
I wonder if my capability to to read the PR_BODY_W depends on whether the ItemSend callback is called before or after Outlook encrypts the message? is this configurable?

A: Outlook always represents signed and encrypted message as regular IPM.Note items. Even MailItem.MAPIOBJECT is a fake IMessage object.
How do you retrieve PR_BODY?


text:
Q: How can I overwrite the save button to change on a custom page? When I use the standard save action in the commandButton it goes every time to the default page.
But I want to chamge to a custom page when i click on the save button..how??
I tried a lot of things like this...
public Pagereference goHome(){

Pagereference to = Apexpages.currentPage();
     to.setRedirect(true);
return to;
}

or
public Pagereference goHome(){

Pagereference to = new Pagereference('/apex/mypage?user=guest');    return to;
}

<apex:commandButton value="Save"  action="{!goHome}" />

A: It should be very simple! Check how this example works for you (you'll need to associate the page to a valid Opportunity by adding ?id=006... in the URL).
public class redirectTestCtrl{
    public Opportunity o {get;set;}

    public redirectTestCtrl(ApexPages.StandardController ctrl){
        o = (Opportunity)ctrl.getRecord();
    }

    public PageReference save(){
        upsert o;
        //return new PageReference('/home/home.jsp'); // go to home page
        return new PageReference('/' + o.AccountId);  // or to the related Account's page
    }
}

<apex:page standardController="Opportunity" extensions="redirectTestCtrl">
    <apex:outputField value="{!o.AccountId}" />
    <apex:form>
        <apex:inputField value="{!o.Name}" />
        <apex:commandButton value="Save" action="{!save}" />
    </apex:form>
    {!Opportunity.Name} {!Opportunity.AccountId}
</apex:page>

A: The standard save() method may be called from an extension using ApexPages.StandardController. Here's a simple example of how it could be achieved:
Apex Page:
<apex:page standardController="Account" extensions="AccountExtension">
    <apex:form >

        <apex:pageMessages />

        <apex:pageBlock title="Account">
            <apex:pageBlockSection title="Account Details">
                <apex:inputField value="{!account.Name}" />
            </apex:pageBlockSection>

            <apex:pageBlockButtons >
                <apex:commandButton action="{!Save}" value="save" />
                <apex:commandButton action="{!Cancel}" value="cancel" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>

Extension Class:
public class AccountExtension {

    ApexPages.StandardController stdController;

    public AccountExtension(ApexPages.StandardController controller) {
        stdController = controller;
    }

    public PageReference save() {
        stdController.save(); // calling standard save() method
        return null; // return 'null' to stay on same page
    }
}


text:
Q: You don't have permission to access /betaSite/ on this server I'm having a big problem.  I just revamped this apt. companies website and created the new website in a folder contained in the current website.  I just finished and have put all of the old site files into and oldSite folder and brought all the new files out of the betaSite folder and into the public folder.  I've tried changing the file persmissions but idk if they are sticking.  Please help!  I really have no clue how to fix this.  Thanks!
asirentals.com
asirentals.com/index.shtml

A: From here: http://www.thesitewizard.com/apache/install-apache-2-windows.shtml

If you want "index.shtml" to be your default start page for your directories, ie, if you want Apache to load "index.shtml" when you type "localhost" or "localhost/directory/", you will need to search for a line in your "httpd.conf" that begins with "DirectoryIndex" and add index.shtml to the list of files there. For example, modify it as follows:
  DirectoryIndex index.shtml index.html


text:
Q: Testing the Mac Installer Package using Xcode 6 Before submitting my Mac App to the App Store I am used to test the installation package following
the procedure described here:
Testing the Mac Installer Package - Apple documentation
This mainly involve archiving the app, exporting as Mac Installer Package and installing it using:
sudo installer -store -pkg .... -target /

Since I updated to Xcode 6 I always get a signature error when I start the app [EXC_CRASH (Code Signature Invalid)]:
Process:               ......... [1749]
Path:                  /Applications/.........
Identifier:            ......
Version:               ???
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           .......... [1749]
User ID:               501

Date/Time:             2014-11-07 18:52:45.292 +0100
OS Version:            Mac OS X 10.10 (14A389)
Report Version:        11
Anonymous UUID:        142A2C49-B327-E26A-0DE4-0CCB99AC1DC0

Sleep/Wake UUID:       174FDF51-B783-4172-952B-EB8E5B07D436

Time Awake Since Boot: 2700 seconds
Time Since Wake:       690 seconds

Crashed Thread:        0

Exception Type:        EXC_CRASH (Code Signature Invalid)
Exception Codes:       0x0000000000000000, 0x0000000000000000

kernel messages:

VM Regions Near 0x7fff75cbe0a8 (cr2):
    __LINKEDIT             00007fff68263000-00007fff68277000 [   80K] r--/rwx SM=COW  /usr/lib/dyld
--> Submap                 00007fff70000000-00007fff80000000 [256.0M] r--/rwx SM=PRV  process-only VM submap
    unused shlib __DATA    00007fff749e7000-00007fff76f76000 [ 37.6M] rw-/rw- SM=COW  system shared lib __DATA not used by this process

Thread 0 Crashed:
0   dyld                            0x00007fff681f4000 _dyld_start + 0

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x000000000000000d  rbx: 0x0000000000000000  rcx: 0x0000000000000000  rdx: 0x0000000000000000
  rdi: 0x0000000000000000  rsi: 0x0000000000000000  rbp: 0x0000000000000000  rsp: 0x00007fff556dcb50
   r8: 0x0000000000000000   r9: 0x0000000000000000  r10: 0x0000000000000000  r11: 0x0000000000000000
  r12: 0x0000000000000000  r13: 0x0000000000000000  r14: 0x0000000000000000  r15: 0x0000000000000000
  rip: 0x00007fff681f4000  rfl: 0x0000000000000201  cr2: 0x00007fff75cbe0a8

Logical CPU:     0
Error Code:      0x020000f4
Trap Number:     133

Binary Images:
    0x7fff681f3000 -     0x7fff68229837  dyld (???) <4696A982-1500-34EC-9777-1EF7A03E2659> /usr/lib/dyld

External Modification Summary:
  Calls made by other processes targeting this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by all processes on this machine:
    task_for_pid: 1226
    thread_create: 0
    thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=300K resident=288K(96%) swapped_out_or_unallocated=12K(4%)
Writable regions: Total=8420K written=0K(0%) resident=12K(0%) swapped_out=0K(0%)     unallocated=8408K(100%)

REGION TYPE                      VIRTUAL
===========                      =======
STACK GUARD                        56.0M
Stack                              8192K
VM_ALLOCATE                           8K
VM_ALLOCATE (reserved)                4K        reserved VM address space (unallocated)
__DATA                              228K
__LINKEDIT                           80K
__TEXT                              220K
mapped file                        1044K
shared memory                         4K
===========                      =======
TOTAL                              65.6M
TOTAL, minus reserved VM space     65.5M

Model: MacBookPro11,1, BootROM MBP111.0138.B11, 2 processors, Intel Core i7, 2.8 GHz, 16 GB, SMC 2.16f68
Graphics: Intel Iris, Intel Iris, Built-In
Memory Module: BANK 0/DIMM0, 8 GB, DDR3, 1600 MHz, 0x80AD, 0x484D54343147533641465238412D50422020
Memory Module: BANK 1/DIMM0, 8 GB, DDR3, 1600 MHz, 0x80AD, 0x484D54343147533641465238412D50422020
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x112), Broadcom BCM43xx 1.0 (7.15.124.12.8)
Bluetooth: Version 4.3.0f10 14890, 3 services, 27 devices, 1 incoming serial ports
Network Service: Wi-Fi, AirPort, en0
Serial ATA Device: APPLE SSD SM0512F, 500.28 GB
USB Device: Internal Memory Card Reader
USB Device: Apple Internal Keyboard / Trackpad
USB Device: BRCM20702 Hub
USB Device: Bluetooth USB Host Controller
Thunderbolt Bus: MacBook Pro, Apple Inc., 17.2

Exactly the same app as not this problem using Xcode 5.
Any suggestion?
This is getting me crazy since I am not confident to submit the app to Apple.

A: I eventually contacted Apple support and they answered that the procedure is:
1) Export your app as a Mac Application

2) productbuild --component <APP>.app /Applications <APP>.pkg --sign "3rd Party Mac Developer Installer:"

3) sudo installer -store -pkg <APP>.pkg -target /

The documentation doesn't mention point #2!

A: This doesn't seem to affect app review. If your archive is validated, you can just submit your app and it should work fine when downloaded from the app store.

A: Apple's Technical Q&A QA1884 document (dated 2015-01-26) covers this topic:

When I run my Mac app, it crashes immediately, and the crash log says Exception Type: EXC_CRASH (Code Signature Invalid). What is going on here?
... distribution builds of Mac apps cannot be run directly; they are for submitting to iTunes Connect for app review only.

The document suggests some work arounds.


text:
Q: Linked List is only printing last element after adding a new node I'm very new to C++ and would like to know why my program is only printing the last node of my input file after adding a new node. After adding the new node it only prints the last node and the node the user enters in.
I also need help with searching for the highest gpa of all the students entered and displaying which student that is as well as their gpa.
Here is the input file:
14
Breen_Jeremy
482929
3.5
Burgess_Patrick
492929
3.2
Catalan_Kristian
393923
2.5
Clark_Brenna
848292
4.0
Duda_Heather
292032
3.7
Freeland_Jesse
391939
4.0
Jarvis_Stephen
392939
2.5
Lemieux_Tyler
392934
3.5
OConnell_Kelly
103939
4.0
Osborne_John
193945
2.8
Richards_Daniel
494585
3.0
Swanbeck_James
693922
3.5
Tayek_Chandler
592022
3.0
Whippen_Andrew
199502
2.8

Here is my program:
 // This program does some basic functionalities of using a linked list

 #include<iostream>
 #include<string.h>
 #include<cstring>
 #include<fstream>
 using namespace std;

struct node
{
string name;
int student_ID;
 double gpa;
node * next;
};

int main()
{
// Variable definitions
node * first;               // Pointer to the first node in the list
node * last;                // Pointer to the last node in the list
char more_nodes = 'y';  // Control to know if the user wants to enter more
int numStudents;
double largest_GPA;
string best_student;
bool swap = true;
ifstream database;
void print(node * first);

database.open("class_list.txt");

database >> numStudents;

// Creates the first node
first = new node;           // Create the first node
first -> next = NULL;   // Point it to NULL (since it's the end)
last = first;               // Point last to it (since it's the end)

 for (int i = 0; i < numStudents; i++)
  {

  database >> first -> name;
  database >> first -> student_ID;
  database >> first -> gpa;
  print(first);
  }//end for

// This loop adds one new node, loads data into it, and updates pointers
  while (more_nodes == 'y')
   {
   last -> next = new node;         // Get a new node tacked onto the end of the list

cout << "Enter the name of the student" << endl;
cin >> last -> next -> name;
cout << "Enter the student ID" << endl;
cin >> last -> next -> student_ID;
cout << "Enter the GPA of the student" << endl;
cin >> last -> next -> gpa;
last -> next -> next = NULL;        // Point the new node to NULL
last = last -> next;        // Toggle last to point to this new node (since it's the new "last")

cout << "Do you have more students to enter? Enter y for yes or n for no" << endl;
cin >> more_nodes;

++numStudents;
print(first);
}//end while

node * temp;
temp = first;

while (temp -> next != NULL)
{
while(swap)
{
   swap = false;
      if (temp -> next -> gpa > temp-> gpa)
       {
        largest_GPA = temp -> gpa;
         temp -> gpa = temp -> next -> gpa;
         temp -> next -> gpa = largest_GPA;
         temp -> name = best_student;
         swap = true;
         }//end if
  }//end while
  temp = temp -> next;
 }//end while

 cout << "The best student is " << best_student <<endl;
 cout << "The largest GPA is " << largest_GPA <<endl;

  database.close();

  return 0;

 }//end main

 // Print out the linked list by having a temporary pointer scroll through the entire list

void print(node * first)
  {
    node * temp;                // Make a temporary (dummy) pointer
    temp = first;               // Point it to the first node in the list

    while(temp != NULL)     // Continue until temp reaches NULL (the end)
    {

    cout << temp -> name << endl;
    cout << temp -> student_ID << endl;
    cout << temp -> gpa << endl;
    temp = temp -> next;                    // Move temp to the next node

      }//end while

   }//end function

A: First, the correct header for the std::string definition is:
#include <string>

These refer to the C string library in different ways:
#include<string.h> // In the global namespace.
#include<cstring>  // In the std namespace.

If the program compiles with your compiler it is due to the implementation of the iostream or fstream headers and shouldn't be relied on.  It didn't compile with mine.
Next, the loop loading records from a file is only creating and reusing one node.  Here's a way to correct that:
for(int i = 0; i < numStudents; i++)
{
    node* temp = new node;
    database >> temp->name;
    database >> temp->student_ID;
    database >> temp->gpa;
    temp->next = NULL;
    if(first == NULL)
    {
        first = last = temp;
    }
    else
    {
        last->next = temp;
        last = temp;
    }
}//end for

print(first);

Lastly, to find the best GPA, track the node with the largest GPA:
node* temp = first;
node* best = first;
while(temp != NULL)
{
    if(temp->gpa > best->gpa)
    {
        best = temp;
    }
    temp = temp->next;
}//end while

cout << "The best student is " << best->name << endl;
cout << "The largest GPA is " << best->gpa << endl;

Some other things to think about:

*

*What if the file is empty or doesn't exist?

*What if the number of students in the file is 0?

*How do you handle a tie for largest GPA? There is a three-way tie in the file.

The code as is won't handle these conditions.

A: Hmm too long code for me, BUT, being new and working with pointers can lead to head scratching moments. If you have extra time, try Java first. You will have a much harder time screwing with the pointers (because you don't get access to them), and you can still build structures like the linked list.
Also I don't like your loop structure, Your loop is initial loop (i = 0), and then the rest of it (i >= 0), when it could be easier to have it all on a single while. I suggest something like this:
continueprocessing = false;
if( filehascontents ) continueprocessing = true;
while( continueprocessing )
{
    if( !filestillhascontents )
    {
        continueprocessing = false;
        continue;//or break; whatever your style
    }

    /*read contents for this loop*/

    /*validate contents to process are valid node data*/
    if( !valid node data ) continue;

    //if we are still here that means we got data, and its valid node data
    node *n = new node;
    /*also initialize n with the data*/

    //you integrate this into the single loop, to me that's better, up to you
    if( first == null )
    {
        first = n;
        last = n;
        continue;
    }

    //now we are done with the initial linking case, work the regular cases
    last->next = n;
    last = n;
}

Basically on the style I show you you assume the regular case, but start the loop checking special conditions and exit early if you hit them. That way your structure is (loop) (special conditions block) (regular case block) (endloop)
Anyway onto your very own code, your for loop, which is the while on mine (one that adds nodes), sets everything to first and keeps overwriting the data there, so that's why you only have one node, because you never add nodes.
As a nitpick you have a loop at the middle that uses "swap", but swap definition is all the way up there, move the initialization down with the code that actually uses it, easier to work with later.
Finally your swap function is wrong, and the only way to keep it that simple yet working would be to reinitialize temp to first everytime a swap happens so you do the search from the beginning again until you are sure the whole list is in order.
EDIT: I see, its not just wrong, its all sorts of wrong, not sure if you want to order your list or you are only looking for the max node, so as another nitpick, try to be overly descriptive on your names and try to be nitpicky about semantics so others and you later on have more ease reading the code, I'd go with renaming temp to maxgpastudent for example, or even result, if you are only looking for the max node because it will be your result.
Then do not use largestGPA as a temp variable for your swapping, it is largestGPA and it should only contain the largest GPA, if you need a temp variable, create one. Finally if you are trying to reorder, redo the function because your assignments are mixing everything, you are swapping gpas, but not swapping the student name, and you dont have to swap values, it's a linked list, swap the links.


text:
Q: How do you remove a CAEmitterLayer when it ends the lifetime of it's CAEmitter Cells -- instead of repeating until you remove it from super layer I am using generic code (from the iOS Fireworks demo) in a slightly changed way.  I have the following in a subclass of UIView.  What I want is to make the firework appear at the point the user touches (not hard) and play out for the length of the CAEmitterLayer/CAEmitterCells 'lifetime'.  Instead, this is immediately starting when i add it to addSublayer -- like I am sure it is meant to.  However, I would like to use it in a slightly different way.  Is there a way that I can change this so there is a CATransaction with a completion block (to removeFromSuperlayer) or something like that?  Any ideas are welcomed.
 #import "FireworksView.h"

    @implementation FireworksView

 - (void)launchFirework{

    //Load the spark image for the particle

    CAEmitterLayer *mortor = [CAEmitterLayer layer];
    mortor.emitterPosition = CGPointMake(self.bounds.size.width/2, self.bounds.size.height*(.75));
    mortor.renderMode = kCAEmitterLayerAdditive;

    //Invisible particle representing the rocket before the explosion
    CAEmitterCell *rocket = [CAEmitterCell emitterCell];
    rocket.emissionLongitude = -M_PI / 2;
    rocket.emissionLatitude = 0;
    rocket.lifetime = 1.6;
    rocket.birthRate = 1;
    rocket.velocity = 400;
    rocket.velocityRange = 100;
    rocket.yAcceleration = 250;
    rocket.emissionRange = M_PI / 4;
    rocket.color = CGColorCreateCopy([UIColor colorWithRed:.5 green:.5 blue:.5 alpha:.5].CGColor);
    rocket.redRange = 0.5;
    rocket.greenRange = 0.5;
    rocket.blueRange = 0.5;

    //Name the cell so that it can be animated later using keypath
    [rocket setName:@"rocket"];

    //Flare particles emitted from the rocket as it flys
    CAEmitterCell *flare = [CAEmitterCell emitterCell];
    flare.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage;
    flare.emissionLongitude = (4 * M_PI) / 2;
    flare.scale = 0.4;
    flare.velocity = 100;
    flare.birthRate = 45;
    flare.lifetime = 1.5;
    flare.yAcceleration = 350;
    flare.emissionRange = M_PI / 7;
    flare.alphaSpeed = -0.7;
    flare.scaleSpeed = -0.1;
    flare.scaleRange = 0.1;
    flare.beginTime = 0.01;
    flare.duration = 0.7;

    //The particles that make up the explosion
    CAEmitterCell *firework = [CAEmitterCell emitterCell];
    firework.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage;
    firework.birthRate = 9999;
    firework.scale = 0.6;
    firework.velocity = 130;
    firework.lifetime = 2;
    firework.alphaSpeed = -0.2;
    firework.yAcceleration = 80;
    firework.beginTime = 1.5;
    firework.duration = 0.1;
    firework.emissionRange = 2 * M_PI;
    firework.scaleSpeed = -0.1;
    firework.spin = 2;

    //Name the cell so that it can be animated later using keypath
    [firework setName:@"firework"];

    //preSpark is an invisible particle used to later emit the spark
    CAEmitterCell *preSpark = [CAEmitterCell emitterCell];
    preSpark.birthRate = 80;
    preSpark.velocity = firework.velocity * 0.70;
    preSpark.lifetime = 1.7;
    preSpark.yAcceleration = firework.yAcceleration * 0.85;
    preSpark.beginTime = firework.beginTime - 0.2;
    preSpark.emissionRange = firework.emissionRange;
    preSpark.greenSpeed = 100;
    preSpark.blueSpeed = 100;
    preSpark.redSpeed = 100;

    //Name the cell so that it can be animated later using keypath
    [preSpark setName:@"preSpark"];

    //The 'sparkle' at the end of a firework
    CAEmitterCell *spark = [CAEmitterCell emitterCell];
    spark.contents = (id)[UIImage imageNamed:@"tspark.png"].CGImage;
    spark.lifetime = 0.05;
    spark.yAcceleration = 250;
    spark.beginTime = 0.8;
    spark.scale = 0.4;
    spark.birthRate = 10;

    preSpark.emitterCells = [NSArray arrayWithObjects:spark, nil];
    rocket.emitterCells = [NSArray arrayWithObjects:flare, firework, preSpark, nil];
    mortor.emitterCells = [NSArray arrayWithObjects:rocket, nil];

    [self.layer addSublayer:mortor];
        }

A: The answer to this is, using CAEmitter, there is NO WAY -- delegate, etc -- to stop the emitter when it ends the cycle.  The only thing you can do is gracefully remove it from the layer when you think it should be removed.

A: Ok, so I was able to sort of achieve this by creating an animation with delegate that fired along with the emitter. in the animationDidStop i made a for loop that went through my view hierarchy and looked for emitters and removed them. it's buggy and I still want a real solution, but this works for now.
for (CALayer *layer in _plusButton.layer.sublayers) {
    if (layer.class == [CAEmitterLayer class]) {
        [layer removeFromSuperlayer];
    }

}