Q:

How to form dependency between 2 windows services

I have 2 windows services, ServiceA and ServiceB.
I would like to know how can I start ServiceA first and then start ServiceB when ServiceA is on interval.

A:

Service dependencies is exactly what you need. If ServiceA depends on ServiceB, it will be started only after ServiceB entered the running state.
If you need to add dependency to the service you're developing, first add service installer to the project, then use it's ServicesDependedOn property to specify services that should be started before yours.
If you need to modify dependency of installed service, use command line (or programmatically run the command):
sc config [service name] depend= <Dependencies(separated by / (forward slash))>


Q:

Copy entire directory and content from one location to another using PHP

I am trying to copy an entire folder from one location to another using PHP, but it doesn't seem to work:
$username = "peter" //this is just an example.
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder

// copy image folder
$source = "templates/template1/images/";//copy image folder -source
$dest = $userdir;

function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}

// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}

// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}

}

// Clean up
$dir->close();
return true;
}

I have also tried other solutions I saw online   without success. Would appreciate any help possible

I also just tried this script without any luck.
I just tried another script and still no luck :(.
$template_homepage = "templates/template1/index.php";//path to default template homepage
$homepage = file_get_contents($template_homepage);//get default homepage structure

$username = testuser;// folder name for store

if (trim($username) == '') {
die("An error occured.");
} else {
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder for new website

// copy image folder
$src = 'templates/template1/images';//copy image folder -source
$dst = $userdir;

   function rcopy($src, $dst) {
  if (file_exists($dst)) rrmdir($dst);
  if (is_dir($src)) {
mkdir($dst);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
}
  else if (file_exists($src)) copy($src, $dst);

}

$fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder

   // $stringData = $title; //."\n";//
   fwrite($fh, $homepage);// write homepage structure into new homepage file.
    fclose($fh);// close new homepage file.
 $launchpage = "../Users/".$username."/"; // launch new homepage file.
header("Location: $launchpage");
   }

A:

Why don't you use exec and use the OS command to copy the folder over?
exec('cp -r sourcedir destdir');


Q:

Cassandra: primary range full repair on all nodes of cluster or datacenter

As everyone would agree, Cassandra repairs are necessary but are very expensive and failure prone, gets stuck most of the time if any node in the cluster go down while the repair is running on any other node in the cluster. I am running full sequential repair on primary range using the following command in a rolling fashion:
node repair -pr -full -seq

But have a doubt, Is it enough to run this repair on every node of a data-center (I have 4 different data-centers) or is it required to be run on every node of the whole cluster? I found some documents on this topic, but the language doesn't answer this question properly. For example 3.1 Primary range repair

A:

Update: I was actually wrong here thinking ring as two DCs instead of single, the actual token Ring is more of:
    | DC  | Node | Token |
    |-----|------|-------|
    | DC1 |node1 |   1   |
    | DC2 |node2 |   5   |
    | DC1 |node3 |   10  |
    | DC2 |node4 |   15  |
    | DC1 |node5 |   20  |
    | DC2 |node6 |   25  |

The primary range for node4 here is 11-15, not 6-15 (which is the primary range + local ranges). You must do -pr on each node. Deleting original so it doesn't cause any confusion.

A:

With repair -pr -full you must run repair on every node in the cluster.  See this blog post I wrote a couple years ago for a detailed description of why.


Q:

Create media sample timestamps for live source filter?

I'm trying to write an UDP streaming application with directshow that intends to work in LAN environment. Things turned out to be fine until the client starts to experience freezing issues when seeking.
Here is what I did:
Server

Client

On the server side, I have two transform filter, one for Video and one for Audio. In these two filters, each of them creates a thread that reads the MediaSamples and perform multicast without modifying the timestamps/flags. Meanwhile, the Video transform filter simply pass the media samples to the decoder. The Audio transform filters will do the same.
On the client side. The live source filter simply reads the Video and Audio MediaSamples from the UDP port. At here, I perform some simple Timestamp calculation which is:

MediaSample start time = Current Stream Time + 40 ms

The videos would stream just fine in LAN environment. However, I found out when I do a seek, the client side will freeze for a moment. When I check the renderer, it will show lots of frames are dropped. I'm guessing the timestamps are causing the frames to dropped.
I also noticed whenever a perform a seek, the initial frames are usually have negative stamps. If I don't send these frames over to the client, the client will not freeze. But some the frames would be broken. I'm guessing this is due to fact these negative frames are the KeyFrames that leads to seeked position. If they are missing, the image would be broken.
After doing some research, I tried this approach:

Set the first sample's timestamp to current stream time.
T1 = Stream Time.
Use this first sample's timestamp as baseline.
Base = T1
Every sample after is calculated as
Tn = Stream Time + Tn  - Base

Which also didn't work. I am  guessing that's because the server and client's clock are not synchronized. However, I was thinking it might work, because after every seek on the server side, the timestamps starts from 0 again.
I am trying to figure out what to do next.
I would really appreciate it if anyone could give me some advice.
2013-07-26 Update
Roman, Thank for your help. I have tried to rebase the timestamps with the method mentioned in http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/c1c762a0-af92-4987-b084-f0d194766999/is-a-video-sample-with-negative-timestamp-a-preroll-sample

Client detects discontinuity by checking IMediaSample::IsDiscontinuity
If a discontinuity occurs, set baseline(B) to the received the timestamp
Then every timestamp is calculated as

TS - Received timestamp      TC - Calculated timestamp
  TC = Current Stream Time + TS - B + 40ms

where I get current stream time by using CRefTime and StreamTime()
After making the changes above, when I start to stream, the client's video moves very slow for awhile and eventually freezes. The client's screen goes active again for about half a second after I stop the server from sending data.
What did I do wrong here?  Is it about the clock rate?
2013-08-01 Update
Following Roman's suggestion, I was able to find my mistakes in the timestamps by adding a pass through filter after the SourceFilter which allows me to examine the timestamps coming from the SourceFilter's video output pin.
However, right now I have encountered another problem when seeking. On the client side, even though all the frames are displayed properly, it's suffering from huge delay before it's starts updating new frames.
I have checked these frames and they are the preroll frames that lead to the frame of my seeked position. I'm confirmed it by setting the preroll flag to false in the media samples and letting it be played. It seems that the graph is processing these preroll frames in normal rate on the client side, but on the server side, these preroll frames are processed lot quicker.
Is there a way to get around this delay or it's just something I have to deal with?
These are the samples I captured in the pass through filter.
Server
6848 : GetState 2
31772 : 11210a90 BeginFlush
31784 : 11210a90 EndFlush
31784 : NewSegment: 38700000..300900000 at 1x
31814 : GetState 1
31814 : GetState 1
31814 : GetState 1
31815 : GetState 1
31815 : GetState 1
31816 : 11210a90 Sample 4515 bytesD time -3870.0 to -3837.0 latency 0.0 <-- Preroll Starts
31828 : 11210a90 Sample 62335 bytes time -3837.0 to -3804.0 latency 0.0
31834 : GetState 1
31843 : 11210a90 Sample 51483 bytes time -3804.0 to -3770.0 latency 0.0
31844 : GetState 1
31856 : 11210a90 Sample 62535 bytes time -3770.0 to -3737.0 latency 0.0
31864 : GetState 1
31869 : 11210a90 Sample 62041 bytes time -3737.0 to -3704.0 latency 0.0
31874 : GetState 1
31885 : 11210a90 Sample 61509 bytes time -3704.0 to -3670.0 latency 0.0
31888 : GetState 1
31900 : 11210a90 Sample 62280 bytes time -3670.0 to -3637.0 latency 0.0
31906 : GetState 1
31912 : 11210a90 Sample 63084 bytes time -3637.0 to -3604.0 latency 0.0
31926 : GetState 1
31929 : 11210a90 Sample 62388 bytes time -3604.0 to -3570.0 latency 0.0
31936 : GetState 1
31941 : 11210a90 Sample 61956 bytes time -3570.0 to -3537.0 latency 0.0
31951 : GetState 1
31956 : 11210a90 Sample 52196 bytes time -3537.0 to -3503.0 latency 0.0
31967 : GetState 1
31968 : 11210a90 Sample 53707 bytes time -3503.0 to -3470.0 latency 0.0
31980 : 11210a90 Sample 55162 bytes time -3470.0 to -3437.0 latency 0.0
31982 : GetState 1
31991 : 11210a90 Sample 54511 bytes time -3437.0 to -3403.0 latency 0.0
31998 : GetState 1
32002 : 11210a90 Sample 53676 bytes time -3403.0 to -3370.0 latency 0.0
32013 : 11210a90 Sample 54214 bytes time -3370.0 to -3337.0 latency 0.0
32016 : GetState 1
32031 : 11210a90 Sample 53590 bytes time -3337.0 to -3303.0 latency 0.0
32036 : GetState 1
32042 : 11210a90 Sample 54067 bytes time -3303.0 to -3270.0 latency 0.0
32046 : GetState 1
32055 : 11210a90 Sample 55115 bytes time -3270.0 to -3237.0 latency 0.0
32066 : GetState 1
32067 : 11210a90 Sample 56462 bytes time -3237.0 to -3203.0 latency 0.0
32076 : GetState 1
32079 : 11210a90 Sample 45412 bytes time -3203.0 to -3170.0 latency 0.0
32090 : 11210a90 Sample 49165 bytes time -3170.0 to -3136.0 latency 0.0
32096 : GetState 1
32102 : 11210a90 Sample 47378 bytes time -3136.0 to -3103.0 latency 0.0
32113 : 11210a90 Sample 47024 bytes time -3103.0 to -3070.0 latency 0.0
32116 : GetState 1
32123 : GetState 1
32127 : 11210a90 Sample 46739 bytes time -3070.0 to -3036.0 latency 0.0
32138 : GetState 1
32141 : 11210a90 Sample 45601 bytes time -3036.0 to -3003.0 latency 0.0
32152 : 11210a90 Sample 45939 bytes time -3003.0 to -2970.0 latency 0.0
32154 : GetState 1
32163 : 11210a90 Sample 47212 bytes time -2970.0 to -2936.0 latency 0.0
32170 : GetState 1
32180 : 11210a90 Sample 44130 bytes time -2936.0 to -2903.0 latency 0.0
32190 : GetState 1
32190 : 11210a90 Sample 43858 bytes time -2903.0 to -2869.0 latency 0.0
32200 : GetState 1
32201 : 11210a90 Sample 44417 bytes time -2869.0 to -2836.0 latency 0.0
32211 : 11210a90 Sample 44330 bytes time -2836.0 to -2803.0 latency 0.0
32217 : GetState 1
32224 : 11210a90 Sample 44660 bytes time -2803.0 to -2769.0 latency 0.0
32236 : 11210a90 Sample 43832 bytes time -2769.0 to -2736.0 latency 0.0
32237 : GetState 1
32247 : GetState 1
32248 : 11210a90 Sample 43512 bytes time -2736.0 to -2703.0 latency 0.0
32260 : 11210a90 Sample 43342 bytes time -2703.0 to -2669.0 latency 0.0
32267 : GetState 1
32272 : 11210a90 Sample 43589 bytes time -2669.0 to -2636.0 latency 0.0
32286 : 11210a90 Sample 42888 bytes time -2636.0 to -2603.0 latency 0.0
32287 : GetState 1
32297 : GetState 1
32297 : 11210a90 Sample 44217 bytes time -2603.0 to -2569.0 latency 0.0
32308 : 11210a90 Sample 46987 bytes time -2569.0 to -2536.0 latency 0.0
32311 : GetState 1
32321 : 11210a90 Sample 45233 bytes time -2536.0 to -2502.0 latency 0.0
32331 : GetState 1
32332 : 11210a90 Sample 46052 bytes time -2502.0 to -2469.0 latency 0.0
32343 : GetState 1
32343 : 11210a90 Sample 45819 bytes time -2469.0 to -2436.0 latency 0.0
32357 : 11210a90 Sample 46946 bytes time -2436.0 to -2402.0 latency 0.0
32363 : GetState 1
32371 : 11210a90 Sample 44469 bytes time -2402.0 to -2369.0 latency 0.0
32373 : GetState 1
32387 : 11210a90 Sample 44398 bytes time -2369.0 to -2336.0 latency 0.0
32393 : GetState 1
32401 : 11210a90 Sample 45456 bytes time -2336.0 to -2302.0 latency 0.0
32403 : GetState 1
32412 : 11210a90 Sample 46051 bytes time -2302.0 to -2269.0 latency 0.0
32423 : GetState 1
32425 : 11210a90 Sample 38146 bytes time -2269.0 to -2236.0 latency 0.0
32436 : 11210a90 Sample 38028 bytes time -2236.0 to -2202.0 latency 0.0
32443 : GetState 1
32446 : 11210a90 Sample 39705 bytes time -2202.0 to -2169.0 latency 0.0
32455 : GetState 1
32460 : 11210a90 Sample 36533 bytes time -2169.0 to -2135.0 latency 0.0
32468 : GetState 1
32472 : 11210a90 Sample 37019 bytes time -2135.0 to -2102.0 latency 0.0
32483 : 11210a90 Sample 37277 bytes time -2102.0 to -2069.0 latency 0.0
32488 : GetState 1
32494 : 11210a90 Sample 36698 bytes time -2069.0 to -2035.0 latency 0.0
32498 : GetState 1
32506 : 11210a90 Sample 36436 bytes time -2035.0 to -2002.0 latency 0.0
32516 : GetState 1
32516 : 11210a90 Sample 37650 bytes time -2002.0 to -1969.0 latency 0.0
32528 : 11210a90 Sample 38623 bytes time -1969.0 to -1935.0 latency 0.0
32536 : GetState 1
32538 : 11210a90 Sample 38525 bytes time -1935.0 to -1902.0 latency 0.0
32546 : GetState 1
32549 : 11210a90 Sample 38196 bytes time -1902.0 to -1868.0 latency 0.0
32559 : 11210a90 Sample 38130 bytes time -1868.0 to -1835.0 latency 0.0
32564 : GetState 1
32575 : 11210a90 Sample 39116 bytes time -1835.0 to -1802.0 latency 0.0
32583 : GetState 1
32587 : 11210a90 Sample 45008 bytes time -1802.0 to -1768.0 latency 0.0
32593 : GetState 1
32599 : 11210a90 Sample 40588 bytes time -1768.0 to -1735.0 latency 0.0
32610 : 11210a90 Sample 40633 bytes time -1735.0 to -1702.0 latency 0.0
32613 : GetState 1
32621 : 11210a90 Sample 41867 bytes time -1702.0 to -1668.0 latency 0.0
32623 : GetState 1
32633 : 11210a90 Sample 40974 bytes time -1668.0 to -1635.0 latency 0.0
32643 : GetState 1
32643 : 11210a90 Sample 41854 bytes time -1635.0 to -1602.0 latency 0.0
32653 : GetState 1
32654 : 11210a90 Sample 42312 bytes time -1602.0 to -1568.0 latency 0.0
32665 : 11210a90 Sample 42155 bytes time -1568.0 to -1535.0 latency 0.0
32668 : GetState 1
32681 : 11210a90 Sample 41618 bytes time -1535.0 to -1501.0 latency 0.0
32688 : GetState 1
32696 : 11210a90 Sample 41394 bytes time -1501.0 to -1468.0 latency 0.0
32703 : GetState 1
32715 : GetState 1
32719 : 11210a90 Sample 41221 bytes time -1468.0 to -1435.0 latency 0.0
32731 : 11210a90 Sample 41515 bytes time -1435.0 to -1401.0 latency 0.0
32735 : GetState 1
32742 : 11210a90 Sample 41570 bytes time -1401.0 to -1368.0 latency 0.0
32748 : GetState 1
32752 : 11210a90 Sample 43045 bytes time -1368.0 to -1335.0 latency 0.0
32762 : GetState 1
32765 : 11210a90 Sample 42187 bytes time -1335.0 to -1301.0 latency 0.0
32778 : GetState 1
32780 : 11210a90 Sample 41181 bytes time -1301.0 to -1268.0 latency 0.0
32791 : 11210a90 Sample 41675 bytes time -1268.0 to -1235.0 latency 0.0
32793 : GetState 1
32804 : 11210a90 Sample 42541 bytes time -1235.0 to -1201.0 latency 0.0
32813 : GetState 1
32818 : 11210a90 Sample 41916 bytes time -1201.0 to -1168.0 latency 0.0
32827 : GetState 1
32833 : 11210a90 Sample 40903 bytes time -1168.0 to -1134.0 latency 0.0
32843 : 11210a90 Sample 41798 bytes time -1134.0 to -1101.0 latency 0.0
32846 : GetState 1
32855 : 11210a90 Sample 41537 bytes time -1101.0 to -1068.0 latency 0.0
32860 : GetState 1
32866 : 11210a90 Sample 40623 bytes time -1068.0 to -1034.0 latency 0.0
32877 : GetState 1
32880 : 11210a90 Sample 40275 bytes time -1034.0 to -1001.0 latency 0.0
32889 : GetState 1
32890 : 11210a90 Sample 37519 bytes time -1001.0 to -968.0 latency 0.0
32901 : 11210a90 Sample 37575 bytes time -968.0 to -934.0 latency 0.0
32903 : GetState 1
32912 : 11210a90 Sample 38719 bytes time -934.0 to -901.0 latency 0.0
32920 : GetState 1
32928 : 11210a90 Sample 36653 bytes time -901.0 to -867.0 latency 0.0
32934 : GetState 1
32940 : 11210a90 Sample 36593 bytes time -867.0 to -834.0 latency 0.0
32951 : 11210a90 Sample 35818 bytes time -834.0 to -801.0 latency 0.0
32954 : GetState 1
32960 : 11210a90 Sample 36516 bytes time -801.0 to -767.0 latency 0.0
32966 : GetState 1
32974 : 11210a90 Sample 35436 bytes time -767.0 to -734.0 latency 0.0
32986 : 11210a90 Sample 36906 bytes time -734.0 to -701.0 latency 0.0
32986 : GetState 1
32996 : 11210a90 Sample 37786 bytes time -701.0 to -667.0 latency 0.0
32998 : GetState 1
33008 : 11210a90 Sample 36125 bytes time -667.0 to -634.0 latency 0.0
33012 : GetState 1
33019 : 11210a90 Sample 36410 bytes time -634.0 to -601.0 latency 0.0
33027 : GetState 1
33034 : 11210a90 Sample 36077 bytes time -601.0 to -567.0 latency 0.0
33045 : 11210a90 Sample 37942 bytes time -567.0 to -534.0 latency 0.0
33047 : GetState 1
33060 : 11210a90 Sample 36691 bytes time -534.0 to -500.0 latency 0.0
33066 : GetState 1
33071 : 11210a90 Sample 36991 bytes time -500.0 to -467.0 latency 0.0
33075 : GetState 1
33082 : 11210a90 Sample 37085 bytes time -467.0 to -434.0 latency 0.0
33091 : GetState 1
33092 : 11210a90 Sample 36362 bytes time -434.0 to -400.0 latency 0.0
33103 : 11210a90 Sample 36669 bytes time -400.0 to -367.0 latency 0.0
33109 : GetState 1
33112 : 11210a90 Sample 36624 bytes time -367.0 to -334.0 latency 0.0
33126 : 11210a90 Sample 38299 bytes time -334.0 to -300.0 latency 0.0
33129 : GetState 1
33139 : GetState 1
33140 : 11210a90 Sample 37931 bytes time -300.0 to -267.0 latency 0.0
33152 : GetState 1
33153 : 11210a90 Sample 38297 bytes time -267.0 to -234.0 latency 0.0
33163 : 11210a90 Sample 38490 bytes time -234.0 to -200.0 latency 0.0
33172 : GetState 1
33176 : 11210a90 Sample 40219 bytes time -200.0 to -167.0 latency 0.0
33184 : GetState 1
33188 : 11210a90 Sample 45656 bytes time -167.0 to -133.0 latency 0.0
33199 : 11210a90 Sample 44289 bytes time -133.0 to -100.0 latency 0.0
33204 : GetState 1
33210 : 11210a90 Sample 39973 bytes time -100.0 to -67.0 latency 0.0
33216 : GetState 1
33222 : 11210a90 Sample 38835 bytes time -67.0 to -33.0 latency 0.0
33230 : GetState 1
33234 : 11210a90 Sample 43513 bytes time -33.0 to 0.0 latency 0.0
33246 : 11210a90 Sample 39879 bytes time 0.0 to 1.0 latency 0.0 <-- Preroll ends
33250 : GetState 1
33262 : GetState 1
33262 : 11210a90 Run STO 23440168ms ST 0ms
33262 : 11210a90 Sample 40240 bytes time 33.0 to 34.0 latency 33.0
33302 : 11210a90 Sample 40200 bytes time 67.0 to 68.0 latency 42.204
33337 : 11210a90 Sample 40430 bytes time 100.0 to 101.0 latency 41.204
33464 : 11210a90 Sample 40407 bytes time 134.0 to 135.0 latency 37.8390
33497 : 11210a90 Sample 43949 bytes time 167.0 to 168.0 latency 36.8390
33531 : 11210a90 Sample 40345 bytes time 200.0 to 201.0 latency 35.8390
33559 : 11210a90 Sample 40497 bytes time 234.0 to 235.0 latency 41.6530
33600 : 11210a90 Sample 40504 bytes time 267.0 to 268.0 latency 33.7936
33626 : 11210a90 Sample 114853 bytes time 300.0 to 301.0 latency 40.7936
33658 : 11210a90 Sample 20719 bytes time 334.0 to 335.0 latency 42.7936

Client
31372 : GetState 2
32794 : f622d30 Sample 4515 bytesD time 30199.0 to 30232.0 latency -52.0 <---Discontinuity
32809 : f622d30 Sample 62335 bytes time 30232.0 to 30265.0 latency -34.0
32843 : f622d30 Sample 51483 bytes time 30265.0 to 30299.0 latency -35.0
32869 : f622d30 Sample 62535 bytes time 30299.0 to 30332.0 latency -27.0
32898 : f622d30 Sample 62041 bytes time 30332.0 to 30365.0 latency -23.0
32917 : f622d30 Sample 61509 bytes time 30365.0 to 30399.0 latency -9.0
32937 : f622d30 Sample 62280 bytes time 30399.0 to 30432.0 latency 5.0
32958 : f622d30 Sample 63084 bytes time 30432.0 to 30465.0 latency 17.0
32984 : f622d30 Sample 62388 bytes time 30465.0 to 30499.0 latency 24.0
33019 : f622d30 Sample 61956 bytes time 30499.0 to 30532.0 latency 23.0
33054 : f622d30 Sample 52196 bytes time 30532.0 to 30566.0 latency 21.0
33104 : f622d30 Sample 53707 bytes time 30566.0 to 30599.0 latency 5.0
33135 : f622d30 Sample 55162 bytes time 30599.0 to 30632.0 latency 8.0
33196 : f622d30 Sample 54511 bytes time 30632.0 to 30666.0 latency -21.0
33224 : f622d30 Sample 53676 bytes time 30666.0 to 30699.0 latency -15.0
33265 : f622d30 Sample 54214 bytes time 30699.0 to 30732.0 latency -23.0
33287 : f622d30 Sample 53590 bytes time 30732.0 to 30766.0 latency -12.0
33336 : f622d30 Sample 54067 bytes time 30766.0 to 30799.0 latency -27.0
33369 : f622d30 Sample 55115 bytes time 30799.0 to 30832.0 latency -27.0
33416 : f622d30 Sample 56462 bytes time 30832.0 to 30866.0 latency -40.0
33455 : f622d30 Sample 45412 bytes time 30866.0 to 30899.0 latency -46.0
33487 : f622d30 Sample 49165 bytes time 30899.0 to 30933.0 latency -45.0
33538 : f622d30 Sample 47378 bytes time 30933.0 to 30966.0 latency -62.0
33577 : f622d30 Sample 47024 bytes time 30966.0 to 30999.0 latency -68.0
33616 : f622d30 Sample 46739 bytes time 30999.0 to 31033.0 latency -74.0
33663 : f622d30 Sample 45601 bytes time 31033.0 to 31066.0 latency -87.0
33690 : f622d30 Sample 45939 bytes time 31066.0 to 31099.0 latency -81.0
33732 : f622d30 Sample 47212 bytes time 31099.0 to 31133.0 latency -90.0
33775 : f622d30 Sample 44130 bytes time 31133.0 to 31166.0 latency -98.0
33819 : f622d30 Sample 43858 bytes time 31166.0 to 31200.0 latency -110.0
33851 : f622d30 Sample 44417 bytes time 31200.0 to 31233.0 latency -108.0
33880 : f622d30 Sample 44330 bytes time 31233.0 to 31266.0 latency -104.0
33924 : f622d30 Sample 44660 bytes time 31266.0 to 31300.0 latency -115.0
33959 : f622d30 Sample 43832 bytes time 31300.0 to 31333.0 latency -116.0
33989 : f622d30 Sample 43512 bytes time 31333.0 to 31366.0 latency -113.0
34023 : f622d30 Sample 43342 bytes time 31366.0 to 31400.0 latency -114.0
34062 : f622d30 Sample 43589 bytes time 31400.0 to 31433.0 latency -119.0
34088 : f622d30 Sample 42888 bytes time 31433.0 to 31466.0 latency -112.0
34118 : f622d30 Sample 44217 bytes time 31466.0 to 31500.0 latency -108.0
34159 : f622d30 Sample 46987 bytes time 31500.0 to 31533.0 latency -116.0
34185 : f622d30 Sample 45233 bytes time 31533.0 to 31567.0 latency -109.0
34209 : f622d30 Sample 46052 bytes time 31567.0 to 31600.0 latency -99.0
34237 : f622d30 Sample 45819 bytes time 31600.0 to 31633.0 latency -94.0
34258 : f622d30 Sample 46946 bytes time 31633.0 to 31667.0 latency -82.0
34286 : f622d30 Sample 44469 bytes time 31667.0 to 31700.0 latency -76.0
34306 : f622d30 Sample 44398 bytes time 31700.0 to 31733.0 latency -63.0
34333 : f622d30 Sample 45456 bytes time 31733.0 to 31767.0 latency -57.0
34354 : f622d30 Sample 46051 bytes time 31767.0 to 31800.0 latency -44.0
34374 : f622d30 Sample 38146 bytes time 31800.0 to 31833.0 latency -31.0
34402 : f622d30 Sample 38028 bytes time 31833.0 to 31867.0 latency -26.0
34482 : f622d30 Sample 39705 bytes time 31867.0 to 31900.0 latency -72.0
34507 : f622d30 Sample 36533 bytes time 31900.0 to 31934.0 latency -64.0
34528 : f622d30 Sample 37019 bytes time 31934.0 to 31967.0 latency -51.0
34569 : f622d30 Sample 37277 bytes time 31967.0 to 32000.0 latency -59.0
34600 : f622d30 Sample 36698 bytes time 32000.0 to 32034.0 latency -56.0
34626 : f622d30 Sample 36436 bytes time 32034.0 to 32067.0 latency -48.0
34651 : f622d30 Sample 37650 bytes time 32067.0 to 32100.0 latency -41.0
34670 : f622d30 Sample 38623 bytes time 32100.0 to 32134.0 latency -26.0
34689 : f622d30 Sample 38525 bytes time 32134.0 to 32167.0 latency -12.0
34723 : f622d30 Sample 38196 bytes time 32167.0 to 32201.0 latency -12.0
34749 : f622d30 Sample 38130 bytes time 32201.0 to 32234.0 latency -5.0
34771 : f622d30 Sample 39116 bytes time 32234.0 to 32267.0 latency 7.0
34791 : f622d30 Sample 45008 bytes time 32267.0 to 32301.0 latency 19.0
34818 : f622d30 Sample 40588 bytes time 32301.0 to 32334.0 latency 27.0
34848 : f622d30 Sample 40633 bytes time 32334.0 to 32367.0 latency 29.0
34948 : f622d30 Sample 41867 bytes time 32367.0 to 32401.0 latency -37.0
34970 : f622d30 Sample 40974 bytes time 32401.0 to 32434.0 latency -26.0
34999 : f622d30 Sample 41854 bytes time 32434.0 to 32467.0 latency -22.0
35018 : f622d30 Sample 42312 bytes time 32467.0 to 32501.0 latency -8.0
35050 : f622d30 Sample 42155 bytes time 32501.0 to 32534.0 latency -6.0
35078 : f622d30 Sample 41618 bytes time 32534.0 to 32568.0 latency -1.0
35102 : f622d30 Sample 41394 bytes time 32568.0 to 32601.0 latency 9.0
35122 : f622d30 Sample 41221 bytes time 32601.0 to 32634.0 latency 22.0
35148 : f622d30 Sample 41515 bytes time 32634.0 to 32668.0 latency 29.0
35166 : f622d30 Sample 41570 bytes time 32668.0 to 32701.0 latency 45.0
35198 : f622d30 Sample 43045 bytes time 32701.0 to 32734.0 latency 47.0
35216 : f622d30 Sample 42187 bytes time 32734.0 to 32768.0 latency 61.0
35239 : f622d30 Sample 41181 bytes time 32768.0 to 32801.0 latency 72.0
35274 : f622d30 Sample 41675 bytes time 32801.0 to 32834.0 latency 70.0
35301 : f622d30 Sample 42541 bytes time 32834.0 to 32868.0 latency 76.0
35319 : f622d30 Sample 41916 bytes time 32868.0 to 32901.0 latency 92.0
35370 : f622d30 Sample 40903 bytes time 32901.0 to 32935.0 latency 75.0
35395 : f622d30 Sample 41798 bytes time 32935.0 to 32968.0 latency 84.0
35415 : f622d30 Sample 41537 bytes time 32968.0 to 33001.0 latency 97.0
35437 : f622d30 Sample 40623 bytes time 33001.0 to 33035.0 latency 107.0
35461 : f622d30 Sample 40275 bytes time 33035.0 to 33068.0 latency 117.0
35482 : f622d30 Sample 37519 bytes time 33068.0 to 33101.0 latency 129.0
35518 : f622d30 Sample 37575 bytes time 33101.0 to 33135.0 latency 126.0
35537 : f622d30 Sample 38719 bytes time 33135.0 to 33168.0 latency 142.0
35559 : f622d30 Sample 36653 bytes time 33168.0 to 33202.0 latency 152.0
35576 : f622d30 Sample 36593 bytes time 33202.0 to 33235.0 latency 170.0
35607 : f622d30 Sample 35818 bytes time 33235.0 to 33268.0 latency 171.0
35698 : f622d30 Sample 36516 bytes time 33268.0 to 33302.0 latency 113.0
35724 : f622d30 Sample 35436 bytes time 33302.0 to 33335.0 latency 122.0
35750 : f622d30 Sample 36906 bytes time 33335.0 to 33368.0 latency 128.0
35769 : f622d30 Sample 37786 bytes time 33368.0 to 33402.0 latency 143.0
35796 : f622d30 Sample 36125 bytes time 33402.0 to 33435.0 latency 149.0
35827 : f622d30 Sample 36410 bytes time 33435.0 to 33468.0 latency 151.0
35852 : f622d30 Sample 36077 bytes time 33468.0 to 33502.0 latency 159.0
35871 : f622d30 Sample 37942 bytes time 33502.0 to 33535.0 latency 175.0
35896 : f622d30 Sample 36691 bytes time 33535.0 to 33569.0 latency 182.0
35926 : f622d30 Sample 36991 bytes time 33569.0 to 33602.0 latency 186.0
35949 : f622d30 Sample 37085 bytes time 33602.0 to 33635.0 latency 196.0
35971 : f622d30 Sample 36362 bytes time 33635.0 to 33669.0 latency 207.0
35989 : f622d30 Sample 36669 bytes time 33669.0 to 33702.0 latency 223.0
36017 : f622d30 Sample 36624 bytes time 33702.0 to 33735.0 latency 229.0
36045 : f622d30 Sample 38299 bytes time 33735.0 to 33769.0 latency 233.0
36064 : f622d30 Sample 37931 bytes time 33769.0 to 33802.0 latency 248.0
36086 : f622d30 Sample 38297 bytes time 33802.0 to 33835.0 latency 259.0
36108 : f622d30 Sample 38490 bytes time 33835.0 to 33869.0 latency 270.0
36126 : f622d30 Sample 40219 bytes time 33869.0 to 33902.0 latency 286.0
36157 : f622d30 Sample 45656 bytes time 33902.0 to 33936.0 latency 288.0
36177 : f622d30 Sample 44289 bytes time 33936.0 to 33969.0 latency 302.0
36205 : f622d30 Sample 39973 bytes time 33969.0 to 34002.0 latency 307.0
36225 : f622d30 Sample 38835 bytes time 34002.0 to 34036.0 latency 321.0
36251 : f622d30 Sample 43513 bytes time 34036.0 to 34069.0 latency 329.0
36277 : f622d30 Sample 39879 bytes time 34069.0 to 34070.0 latency 336.0 <--- End of Preroll frames
36608 : f622d30 Sample 40240 bytes time 34102.0 to 34103.0 latency 37.0
36648 : f622d30 Sample 40200 bytes time 34136.0 to 34137.0 latency 32.0
36676 : f622d30 Sample 40430 bytes time 34169.0 to 34170.0 latency 36.0
36711 : f622d30 Sample 40407 bytes time 34203.0 to 34204.0 latency 35.0
36748 : f622d30 Sample 43949 bytes time 34236.0 to 34237.0 latency 31.0
36786 : f622d30 Sample 40345 bytes time 34269.0 to 34270.0 latency 26.0
36805 : f622d30 Sample 40497 bytes time 34303.0 to 34304.0 latency 41.0
36846 : f622d30 Sample 40504 bytes time 34336.0 to 34337.0 latency 33.0
36872 : f622d30 Sample 114853 bytes time 34369.0 to 34370.0 latency 40.0
36906 : f622d30 Sample 20719 bytes time 34403.0 to 34404.0 latency 41.0

A:

Seek involves pausing and restarting streaming: you have a discontinuity in time stamping. You either have to re-claculate time stamps automatically on sending side to restore the continuity, or otherwise detect this on client side and rebase the time stamps there. Or, another option, the client side would flush the queues and continue from fresh.


Q:

Typescript sorting list by status (string value)

I need to sort list of items by its status and I am not sure which approach I should go, is it creating comparer or some kind of sorting technique ?
Would lodash work here ?
example input list:
[
{id: 1, name: "name1", status: "Failed"},
{id: 2, name: "name2", status: "Success"},
{id: 3, name: "name3", status: "In progress"},
{id: 4, name: "name4", status: "Reserved"},
{id: 5, name: "name5", status: "Pending"}
]

example sorted list (output) sorted in Failed -> In progress -> Reserved -> Pending -> Success
[
{id: 1, name: "name1", status: "Failed"},
{id: 3, name: "name3", status: "In progress"},
{id: 4, name: "name4", status: "Reserved"},
{id: 5, name: "name5", status: "Pending"}
{id: 2, name: "name2", status: "Success"},
]

stack I am using is Angular + Typescript.
Edit: List is kinda big, about ~15k rows usually.

A:

You can sort your array based on values in other array:
let sortOrder = ['Failed', 'In progress', 'Reserved', 'Pending', 'Success'];
let array = [
    { id: 1, name: "name1", status: "Failed" },
    { id: 2, name: "name2", status: "Success" },
    { id: 3, name: "name3", status: "In progress" },
    { id: 4, name: "name4", status: "Reserved" },
    { id: 5, name: "name5", status: "Pending" }
];

array.sort((a, b) => {
    return sortOrder.indexOf(a.status) - sortOrder.indexOf(b.status);
});

console.log(array);


Q:

Overloading `--` operator is not working in C++ on Mac

I am trying to overload operators in C++.
I was creating a custom Stack data structure.
This is my Stack.h in the headers directory:
/*******************************************************************************
 * Stack --                                                                    *
 * This class will just interface a stack of integers.                         *
 * A stack is a linear data structure. Elements are pushed into stack from the *
 * bottom and is popped from the top.                                          *
 *                                                                             *
 * Author -- Aditya R.Singh                                                    *
 * Version -- 1.0                                                              *
 * Since -- 2014-06-24                                                         *
 *******************************************************************************/

#ifndef STACK_H
#define STACK_H

class Stack {

    public:
        Stack();                 // To initiallize stuff.
        void operator>>(int);    // To push elements in the stack.
        int operator--();        // To pop element from the stack.
        void display_stack();    // To display the whole stack.

    private:
        typedef struct stack {

            int data;
            struct stack *top, *previous;
        } node;                           // The structure of the whole stack.
        node *PTR;                        // To point to the top of the stack.
        node *BUFFER;                     // To temporarily store the node to be     freed.
        int data;                         // Data to be popped from the stack.
        int choice;                       // To get choice of the user.
};

#endif

My Stack.cpp file, in my sources directory is:
/*******************************************************************************
 * Stack --                                                                    *
 * This file contains the implementation of all functions from the class Stack.*
 *                                                                             *
 * Author -- Aditya R.Singh                                                    *
 * Version -- 1.0                                                              *
 * Since -- 2014-06-24                                                         *
 *******************************************************************************/

#include <iostream>
#include "../headers/Stack.h"

using namespace std;

Stack::Stack() {

    PTR->top = NULL;
    PTR->previous = NULL;
}

void Stack::operator>>(int data) {

    PTR = (node*)malloc(sizeof(node));
    PTR->previous = PTR->top;
    PTR->top = PTR;
    PTR->data = data;
}

int Stack::operator--() {

    BUFFER = PTR->top;
    data = BUFFER->data;
    PTR->top = PTR->previous;
    free(BUFFER);
    return data;
}

void Stack::display_stack() {

    BUFFER = PTR;

    while(BUFFER != NULL) {

        cout << BUFFER->data << endl;
        BUFFER = BUFFER->previous;
    }
}

My Main.cpp in the sources directory:
/*******************************************************************************
 * Main --                                                                     *
 * This program will demonstrate the use of a stack.                           *
 *                                                                             *
 * Author -- Aditya R.Singh                                                    *
 * Version -- 1.0                                                              *
 * Since -- 2014-06-24                                                         *
 *******************************************************************************/

#include <iostream>
#include "../headers/Stack.h"

using namespace std;

int get_choice() {

    int choice = 0;

    cout << "*************************************" << endl;
    cout << "************     STACK    ***********" << endl;
    cout << "*************************************" << endl;
    cout << "********** 0> QUIT APP      *********" << endl;
    cout << "********** 1> PUSH          *********" << endl;
    cout << "********** 2> POP           *********" << endl;
    cout << "********** 3> DISPLAY STACK *********" << endl;
    cout << "********** 4> CLEAR CONSOLE *********" << endl;
    cout << "*************************************" << endl;
    cout << endl << "Enter choice = ";
    cin >> choice;

    return choice;
}

int main() {

    Stack stack;
    int choice = -1;
    int data;

    while(choice) {

        choice = get_choice();

        switch(choice) {

            case 1: cout << "Enter number to be pushed = ";
                    cin >> data;
                stack >> data;
                break;

            case 2: cout << "Just pushed " << stack-- << endl;
                break;

            case 3: stack.display_stack();
                    break;

            case 4: system("clear");
                    break;

            default: cout << "Invalid choice!"  << endl;
                     break;
        }
    }

    return 0;
}

My headers, sources and objects directories are in Stack directory.
My Terminal is pointing in the Stack directory.
Now I compiled the Stack.cpp file like this:
gcc -c sources/Stack.cpp -o objects/Stack.o

It compiled fine and produced the Stack.o file in the objects directory.
But when I compiled the Main.cpp file like this:
gcc sources/Main -o Stack objects/Stack.o

It's giving me the following error:
Main.cpp:66:43: error: cannot decrement value of type 'Stack'
                    case 2: cout << "Just pushed " << stack-- << endl;

It's finding some problem when I am trying to --(decrement) the value of stack. But I overloaded the -- operator in class Stack. So what is the possible problem?
Please help.

A:

You have overloaded the pre-decrement operator int operator--(); however you are using the post-decrement operator, which has overload signature int operator--(int); The int parameter is just a token to distinguish between the prefix and suffix version.


Q:

Как создать плиточное меню WPF

Есть страница разделенная Grid'ом. Нужно в одну ячейку поместить динамически созданные элементы управления (кнопки в виде плиток), причем используя условие.
Если сomboBox.SelectedItem = ... , то создать определенное количество элементов.
Если значение сomboBox.SelectedItem изменилось, то удалить элементы управления, и создать новые. Количество зависит от того, что будет выбрано в comboBox.
Как пример, вот такое меню:

A:

Окей, смотрите, что должно быть.
Для начала, VM. Допустим, у нас есть список яблок и список груш.
enum ProductType
{
    Apples, Pears
}

Нам нужна коллекция всех продуктов:
public static IEnumerable<ProductType> AllProductTypes { get; } =
    Enum.GetValues(typeof(ProductType)).Cast<ProductType>();

И свойство с INotifyPropertyChanged:
private ProductType currentProduct;
public ProductType CurrentProduct
{
    get => currentProduct;
    set => Set(ref currentProduct, value);
}

(я пользуюсь базовым классом отсюда).
Это мы привяжем к комбобоксу:
<Combobox ItemsSource="{x:Static local:YourVM.AllProductTypes}"
          SelectedItem="{Binding CurrentProduct}"/>

Теперь, список. Пускай у нас есть список сортов яблок и список сортов груш.
class Product { }
class AppleVariety : Product { }
class PearVariety : Product { }

IEnumerable<Product> AllProducts = ...;
IEnumerable<AppleVariety> AllApples = AllProducts.OfType<AppleVariety>().ToList();
IEnumerable<PearVariety> AllPears = AllProducts.OfType<PearVariety>().ToList();

Теперь, нам нужно свойство, представляющее собой текущий список — яблоки или груши.
IEnumerable<Product> currentSelection;
IEnumerable<Product> CurrentSelection
{
    get => currentSelection;
    set => Set(ref currentSelection, value);
}

Затем, нам нужно при изменении значения CurrentProduct менять и список. Сделаем это в сеттере CurrentProduct: вместо
    set => Set(ref currentProduct, value);

напишем там
    set => if (Set(ref currentProduct, value)) CurrentSelection = GetCurrentProductList();

и соответственно
IEnumerable<product> GetCurrentProductList()
{
    switch (CurrentProduct)
    {
    case Apples:
        return AllApples;
    case Pears:
        return AllPears;
    default:
        throw new InvalidOperationException("Unknown product kind");
    }
}

Отлично, теперь отображение.
Тут всё просто. Список продуктов показываем так:
<ListView ItemsSource="{Binding CurrentSelection}>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- тут код для отображения вашего продукта -->
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ListView>

Вот вроде бы и всё.


Q:

line spacing in label + vb.net

I have a .NET 2.0 standard Label on my form, well I put some text in it with several lines. But the spacing between the lines are too small. Just want to know if there's a way to fix this.
Thanks...

A:

The only solution I can see would be to make multiple labels and space the labels appropriately.
You may need to create the labels dynamically, one per line.
Of course, you could do a .Split(vbNewLine) on the text you want to display and then for each string in the list, create a new label control, adding it to the form, and spacing it out appropriately from the previous label.
Not ideal, but about the only way to accomplish it.


Q:

Envolver parte de uma string

Estou testando uma função para selecionar a parte de um título que vem após o sinal de dois pontos:
$('.carousel .item .carousel-caption h2').each(function(){
        var val = $(this).text();
        console.log(val);
        var string = val.substr(val.indexOf(":") + 1);
        console.log(string);

        var foo = val.replace('/('+string+')/g', '$1');
        console.log(foo);
    });

Eu consigo selecionar a parte que preciso, mas não consigo incluir as tags. No console, a variável foo aparece igual a variável val.

A:

Você não pode concatenar uma string numa expressão regular literal como está tentando (na verdade, você acabou usando uma string em vez da regex literal). Use o construtor RegExp:
var foo = val.replace(new RegExp('('+ string + ')', 'g'), "$1");

Depois, não esqueça de substituir o valor do elemento (suponho que a intenção seja essa):
$(this).html(foo);


Q:

PostFix 550 5.1.1 Recipient not found from external email

This is a new installation.  PostFix reports "550 5.1.1" "Recipient not found.", when users exist.

User can send email out everywhere.
Users can send email to each other through localhost.
All external emails to users return the 550 5.1.1 error message.

I don't see any errors in the maillog file. I think I have read every thread on this site with "550" in it, but not of the answers seemed appropriate.  Does anyone know why known users are being reported as not found?
Here are my config files:
/etc/postfix/master.cf
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       n       -       -       smtpd
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628      inet  n       -       n       -       -       qmqpd
pickup    fifo  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       n       -       -       smtp
    -o smtp_fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache

/etc/postfix/main.cf
#soft_bounce = no

queue_directory = /var/spool/postfix

command_directory = /usr/sbin

daemon_directory = /usr/libexec/postfix

data_directory = /var/lib/postfix

mail_owner = postfix

#default_privs = nobody

# INTERNET HOST AND DOMAIN NAMES
#myhostname = host.domain.tld
#myhostname = virtual.domain.tld
mydomain = [MYACTUALDOMAINNAME].com
#myorigin = $myhostname
myorigin = $mydomain

inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost
#inet_interfaces = localhost

# Enable IPv4, and IPv6 if supported
inet_protocols = all

#proxy_interfaces =
#proxy_interfaces = 1.2.3.4

# See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS".
#
mydestination = localhost, localhost.$mydomain

unknown_local_recipient_reject_code = 550

# Specify "mynetworks_style = host" when Postfix should "trust"
# only the local machine.
#
#mynetworks_style = class
#mynetworks_style = subnet
#mynetworks_style = host

# INTERNET OR INTRANET

#relayhost = $mydomain
#relayhost = [gateway.my.domain]
#relayhost = [mailserver.isp.tld]
#relayhost = uucphost
#relayhost = [an.ip.add.ress]

# REJECTING UNKNOWN RELAY USERS
#relay_recipient_maps = hash:/etc/postfix/relay_recipients

# INPUT RATE CONTROL
# Specify 0 to disable the feature. Valid delays are 0..10.
#
#in_flow_delay = 1s

#alias_maps = dbm:/etc/aliases
alias_maps = hash:/etc/aliases
#alias_maps = hash:/etc/aliases, nis:mail.aliases
#alias_maps = netinfo:/aliases

# DELIVERY TO MAILBOX
home_mailbox = Maildir/

# The mail_spool_directory parameter specifies the directory where
# UNIX-style mailboxes are kept. The default setting depends on the
# system type.
#
#mail_spool_directory = /var/mail
#mail_spool_directory = /var/spool/mail

#mailbox_command = /some/where/procmail
#mailbox_command = /some/where/procmail -a "$EXTENSION"

#mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp

#mailbox_transport = cyrus

#luser_relay = $user@other.host
#luser_relay = $local@other.host
#luser_relay = admin+$local

#header_checks = regexp:/etc/postfix/header_checks

# FAST ETRN SERVICE
#fast_flush_domains = $relay_domains

# SHOW SOFTWARE VERSION OR NOT
#smtpd_banner = $myhostname ESMTP $mail_name
#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)

# PARALLEL DELIVERY TO THE SAME DESTINATION
#local_destination_concurrency_limit = 2
#default_destination_concurrency_limit = 20

# INSTALL-TIME CONFIGURATION INFORMATION
sendmail_path = /usr/sbin/sendmail.postfix

newaliases_path = /usr/bin/newaliases.postfix

mailq_path = /usr/bin/mailq.postfix

setgid_group = postdrop

# html_directory: The location of the Postfix HTML documentation.
#
html_directory = no

# manpage_directory: The location of the Postfix on-line manual pages.
#
manpage_directory = /usr/share/man

Here is the error message from GMail
Delivery to the following recipient failed permanently:

     [user@email.com]

Technical details of permanent failure:
Google tried to deliver your message, but it was rejected by the server for the recipient domain [domain.com] by smtp.secureserver.net. [68.178.213.37].

The error that the other server returned was:
550 5.1.1 <[user@email.com]> Recipient not found.  <http://x.co/irbounce>

A:

Delivery to the following recipient failed permanently: user@emailaddress.com Technical details of permanent failure: Google tried to deliver your message, but it was rejected by the server for the recipient domain user@emailaddress.com by smtp.secureserver.net. [68.178.213.37]. The error that the other server returned was: 550 5.1.1  Recipient not found.

From the bounce above, looks like your MX record still pointing to GoDaddy  email hosting: smtp.secureserver.net. Change your MX record so it points to your server.
More info: random Help Page on Internet and MX record wikipedia


Q:

Orientation in OpenGL MonoTouch game

Looking for the proper way to handle orientation in my MonoTouch game (although answers in Obj-C are fine).
We are looking to support LandscapeLeft and LandscapeRight orientations, but preserve the native OS orientation so the volume popup and notification center panel are not upside-down.
It is quite confusing, as there are several ways to accomplish what we need:

Info.plist settings
shouldrotate override in UIViewController
setting UIDevice.CurrentDevice.Orientation
or just hook into the NSNotificationCenter and perform rotation with OpenGL, translating touch events

The best I've gotten to work is using #1 and #4, which also seems to be recommended by Apple for performance reasons.  I read some documentation saying that rotating a view (via option #2) with OpenGL content can hurt perf, see here under performance section. (We'd like our game to run pretty well on even older iPod Touches)
My issue is that when rotated LandscapeRight, everything draws properly in my game, but the volume and notification center are upside down in the OS.
Is there a better way to go about this?
I took a look at what some other games appear to do:

Angry Birds - rotate with OpenGL, however works appropriately in LandscapeRight
Jump Out - rotates with UIViewController
Tiny Wings - doesn't rotate at all

I'd like to get rotation exactly like Angry Birds working in my app.

A:

I set the supported orientations in the project Target settings, but I'm only rotating a view without OpenGL.
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


Q:

Getting the updated value of Spin Control

Im using a spin button and want to read it's position.
I've overwritten OnDeltaposSpin(...) , but then i have to evaluate the NMHDR. If I set *pResult=0, it will do the calculations for me, but my value lags behind.
void CClass::OnDeltaposSpin(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
    *pResult = 0;
    UpdateData(TRUE);
    // I want to use the data here
}

So if the Spin is initially 0, the first click won't do anything to my data, the second click gets it to 1, and so on.
Is there another message i can handle that triggers after UDN_DELTAPOS that would work like EN_CHANGE for other controls? Or can i tell the spin control to use the *pResult to do it's calculations inside OnDeltaposSpin?

A:

It looks like UDN_DELTAPOS is used for overriding the position change amount, or preventing a change, but the actual change happens with a WM_VSCROLL (or WM_HSCROLL) message. I suspect those might be the messages you would need to handle to get the results....
(I'm basing this on this doc.)


Q:

How can I replace an Option within a Vec?

Here's the code (I also put it in a playpen here: http://is.gd/f9O3YG):
use std::mem;

pub struct Tree {
    children: Vec<Option<Box<Tree>>>,
    // other fields
}

impl Tree {
    pub fn mutate(&mut self, x: i64) {
        if self.is_base_case() {
            // base case
            unimplemented!();
        } else {
            // recursive case
            let idx: usize = unimplemented!();
            let mut subtree: Option<&mut Box<Tree>> = self.children.get_mut(idx).expect("child idx out of bounds").as_mut();
            match subtree {
                Some(ref mut subtree) => unimplemented!(),
                None => {
                    let mut new_tree = Tree::new();
                    // recurse on the new tree here
                    mem::replace(&mut subtree, Some(&mut Box::new(new_tree)));
                },
            }
        }
    }

    pub fn new() -> Tree {
        unimplemented!();
    }

    fn is_base_case(&self) -> bool {
        unimplemented!();
    }
}

fn main() {
    println!("it compiled!");
}

I'm writing a data structure which is a type of tree. It stores its subtrees in a Vec<Option<Box<Tree>>>, since it's not guaranteed to have a subtree in every position. I'm trying to write a method which mutates the tree, possibly creating one of the subtrees if it doesn't exist.
As you can see if you try to run the code in the playpen, my approach doesn't work. I'm not sure what the error message is telling me - my best guess is that it wants the newly created subtree to have the same lifetime as the subtree created on line 14, in order for the replacement to be safe. However, I'm not sure how to make it have that lifetime. It also made me think: since the new subtree will also need to be valid for the entire lifetime of the data structure, shouldn't it have the same lifetime as the parent tree? It might need to be shorter though, since there are other methods which can remove subtrees (I'm using Option::take for that, which works well enough - I checked the documentation for an opposite of that and couldn't find one). Is my approach flawed, and if not, how should I fix my implementation?

A:

You're trying to put an &mut inside some structure which lives longer than the thing &mut is pointing to. Here's a reduced example:
use std::mem;

pub struct Tree {
    children: Vec<Option<Box<Tree>>>,
}

impl Tree {
    pub fn mutate(&mut self, x: i64) {
        let idx: usize = unimplemented!();
        let mut subtree: Option<&mut Box<Tree>> =
            self.children.get_mut(idx).unwrap().as_mut();

        let mut new_tree = Tree::new();
        mem::replace(&mut subtree, Some(&mut Box::new(new_tree)));
    }

    pub fn new() -> Tree {
        unimplemented!();
    }
}

fn main() {}

The problem is that &mut Box::new(...) is a temporary reference, so you can't just copy it into another structure. Your use of as_mut on the Option is confusing; if you just don't do it your code works fine:
let mut subtree: &mut Option<Box<Tree>> =
    self.children.get_mut(idx).unwrap();

let mut new_tree = Tree::new();
mem::replace(subtree, Some(Box::new(new_tree)));

Here's it in the larger context. You can simplify it a bit, too.


Q:

QtWebEngine rendering native Qt widgets in DOM?

I am looking to rewrite a Qt application in HTML, and have QtWebEngine to render it for me.  I fully understand that a HTML page will display and run in QtWebEngine.
However, one thing I am really interested in, and am unable to find documentation on - apologies if I'm looking in the wrong places - is to know if QtWebEngine allows for elements of the DOM to be "swapped" for native Qt widgets.  For example, could a
 actually be a QOpenGLWidget?  Is this completely nonsensical?
e.g I'd love to be able to do:

Example

Some text

and magically have my QOpenGLWidget rendered in the DOM in the place of "myWidget".  My HTML could only ever be rendered by QtWebEngine, not necessarily by other browsers, so if there is a solution that means it wouldn't work in Chrome/Firefox/IE that is absolutely fine with me.
...Or would I have to use javascript running in the QtWebEngine instance to find out the position of "myWidget" and draw the QOpenGLWidget pixel data in that position myself?  I really don't want to go down this route as it does not allow for things like HTML dialogs over the top of "myWidget".
I'd really appreciate any info here.  An example  (if this is even possible) would be fantastic.  Many thanks in advance.

A:

Solution for QtWebKit:
You will need to subclass QWebPluginFactory and create your widget in its create method.
Then you could embed your widgets in HTML with <object> tag:
<object type="application/x-qt-plugin" name="myWdget" classid="QOpenGLWidget">
</object>

See example here
And another example here
...seems not valid anymore for new QtWebEngine.


Q:

ext3 file system failures after RAM upgrade

I have just added 2GB of RAM into my laptop and started getting problems with ext3 file system. I have tested the actual memory modules with MemTest86+, and they were fine.
This issue also happens when I add other 2GB module (different manufacturer), so it's unlikely that added module itself is faulty. Both modules are same frequency (PC2-5300).
If newly added 2GB module gets removed or replaced with 1GB one, issues disappear.
This is an example of error messages in dmesg:

[ 1113.347106] EXT3-fs error (device
  sda5) in ext3_reserve_inode_write: IO
  failure
[ 1113.347119] Aborting journal on device sda5.
[ 1113.348031] Remounting filesystem read-only
[ 1113.349228] EXT3-fs error (device sda5) in ext3_dirty_inode: IO failure
[ 1114.883303] EXT3-fs error (device sda5): ext3_readdir: bad entry in directory #1900599: inode out of bounds - offset=0, inode=1900599, rec_len=12, name_len=1

What could possibly be a problem and what are the ways to look for solution?
Thanks!
UPD: Strange thing - as soon as I go back to kernel 2.6.28-15 everything crashes again. However it's all fine on 2.6.31-020631-generic
Thanks for your answers.

A:

Memtest is software-based, and software memory testers can tell if if there is a problem, but can't tell you there isn't.
In other words if it finds an issue, there's a problem. If it doesn't, it might not have a problem. It's like asking your brain to objectively evaluate yourself. Doesn't work entirely well.
You don't mention the laptop manufacturer but you might want to doublecheck that it supports that much memory with that speed and size. Some laptops don't like it.
If it weren't the memory or the memory interface, you should continue to have issues when you remove the memory modules. That would mean you could look at filesystem or motherboard corruption issues.
If your hardware does indeed support that much memory then you may have an issue with the motherboard. Since it goes away when you don't have the additional memory in, then the hard drive and filesystem should be intact, leaving the culprits to most likely be the modules, the motherboard's memory interface for memory, or the motherboard itself has an obscure issue.
You might be able to check for BIOS/firmware updates for the laptop to see if this is an issue that is addressed with an upgrade.


Q:

Symfony Command Line Parse Error

Good afternoon,
I'm working on a symfony project and everything was going well until I received the following messages :

PHP Warning:  Unsupported declare 'strict_types' in .../vendor/ocramius/proxy-manager/src/ProxyManager/Configuration.php on line 19
PHP Parse error:  parse error, expecting ';'' or '{'' in .../vendor/ocramius/proxy-manager/src/ProxyManager/Configuration.php on line 97

These 2 messages appear whenever I try to use the command line in symfony.
I tried the following commands:
php app/console generate:doctrine:entity

and
php app/console cache:clear --env=prod.

I also tried to use php bin/console instead of app/console as I'm aware the new symfony versions use php bin/console.
I'm using Mamp with php version 7.1 and Symfony version 2.8 for the projects.
Thanks for your help!

A:

If someone runs into this issue it means that your php version is not 7.0 The issue I had was that the Mamp version was 7.1.1 and the symfony project was also running on 7.1.1 in the browser but when I checked the php version in the bash commands, it was 5.6 so make sure you're bash commands use php 7.0 instead of 5.6


Q:

download file on server progressbar pecl

I am using nginx upload module (http://www.grid.net.ru/nginx/upload.en.html) with this plugin https://github.com/drogus/jquery-upload-progress to upload files on my server successfully with progressbar. here is my form:
<form id="upload" enctype="multipart/form-data" action="/upload/" method="post">
    <input type="file" name="file_1">
        <input type="submit" value="Upload">
</form>

Now i wants to use an option to download remote files with progressbar so my form is this:
<form id="download" action="/upload/" method="post">
    <textarea rows="2" cols="20" name="links"></textarea>
        <input type="submit" value="Upload">
</form>

So if i give a file i.e http://domain.com/file.zip in links textarea and after hit submit it should display me progressbar for downloading files.
I notice from my first upload method there is some data being generated from a link (http://domain.com/progress?X-Progress-ID=0c1ecb6da3f3ffc3848ceb337541ab1d) like this for files being uploaded but i am not sure if i can use this to show download progressbar:
new Object({ 'state' : 'uploading', 'received' : 674808, 'size' : 2028876 } )

Thank you for any help.
Best Regards
EDIT FIX
Found the solution here, https://gist.github.com/1030450 need to use curl, save the progress in file then call with ajax to get current progress...will post my solution later on :)

A:

Found the solution here, https://gist.github.com/bdunogier/1030450 need to use curl, saved the progress in file then called with ajax to get current progress.


Q:

Push notification to android app through WordPress site

I'm in situation where I've a wordpress site and I'm building an android app and what i want is to send a notification to all users having that app.
The app is basically rendering that website into a webview.
Please anyone help me to achieve this by suggesting some standard ways/plugins/tutorials/libraries/anything will take me one step forward.
I'm new to wordpress!!

A:

For push notifications you can use OneSignal which is very simple and have a full featured dashboard for sending notifications.
Also if you want to send notifications from your wordpress site, have a look of this.


Q:

How to use selenium to run indicated versions of multi browsers

I now review the capabilities of selenium to do auto testing work.
I knew selenium can support parallel multi browsers testing by webdrivers. However, how can I specify the versions of browsers to test, such as ie8,ie9 , firefox27...?
Is it possible to do this in selenium?
Thanks for your attention.

A:

No you can not, the alternative would be to use multiple machines each with a different version of the browser.
Machine 1 - IE8.
Machine 2 - IE9.
Machine 3 - IE10.
And you can use the selenium server to test IE across all 3 machines in parallel.
See link below on how to use the selenium grid:
https://github.com/SeleniumHQ/selenium/wiki/Grid2


Q:

How to map HoldForm?

I'm trying to compare between Sqrt[3.] and Sqrt[3]. To display the result, I mapped HoldForm to display the expressions on the left hand column (code at end), but it seems like Sqrt[3.] had been evaluated before it was mapped on to. Is there any way to stop that to happen?

Grid[Prepend[{HoldForm[#], Precision[#],
     MachineNumberQ[#]} & /@ {Sqrt[3.], Sqrt[3]}, {"Number",
   "Precision[]", "MachineNumberQ[]"}],
 Frame -> All]

A:

Grid[Prepend[{HoldForm[#], Precision[#],
     MachineNumberQ[#]} & /@ {Unevaluated@Sqrt[3.],
    Sqrt[3]}, {"Number", "Precision[]", "MachineNumberQ[]"}],
 Frame -> All]


Q:

what happens if Amaterasu is cast on another Amaterasu?

Can the inextinguishable flames of Amaterasu burn the Amaterasu cast by another user? Will they both cease to exist or burn forever?

A:

To first answer this question; we must first look into "What can turn off Amaterasu"

Amaterasu lasts 7 days and 7 nights
Amaterasu can be turned off by the user's will
Amaterasu is turned off when the material projected onto it has been burned

With that being said, Amaterasu 2 will not "burn out" Amaterasu 1, they will simply burn for 7 days and 7 nights before they will both cease to exist.
Here you can read more about Amaterasu


Q:

Add custom token in joomla 2.5

I need to add a custom token in this JS script, when using Joomla 2.5. What is the correct way to add a token? This (**CUSTOM_TOKEN**) doesn't work and I can't find relevant documentation about this.
I don't know if is relevant, bus I am using the language manager and the section Overrides to add the string value.
if (element) {
    $('.content').after('
▲▼
'**CUSTOM_TOKEN**'');
}

A:

Load the Joomla JavaScript framework
<?php
JHtml::_('behavior.framework', true);

Make string available to Javascript (you need to define all strings you want to use (I don't know if it's somehow possible to load them all. I just needed 2-3 so I didn't bother to search further.
JText::script('COM_HELLOWORLD_TEXT_DEMO');

Use it in JavaScript
Joomla.JText._('COM_HELLOWORLD_TEXT_DEMO')

I've seen once a docu page with this stuff, but I can't seem to find it how.
Let me know if this helps.


Q:

Azure Devops - Azure powershell task find release/deployment directory

I'm running Azure devops where i have a pipeline and a release (running on a self hosted agent), and the release is set to send up to an azure app service.  The deployment works fine, the only issue is that i'd also like to be able to (based on some of my release variables) edit the web.config of the site AFTER it has already been deployed to the azure website.
I'm using the Azure Powershell task ( https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-powershell?view=azure-devops ) ,and i can't find anywhere in the release variables ( https://docs.microsoft.com/en-us/azure/devops/pipelines/release/variables?view=azure-devops&tabs=batch ) that shows the directory of where the site exists.  Looking through Kudu, it's pretty basic, like d:\home\site\wwwroot\ , but using that doesn't work at all.
Is this post config that i'm looking for not really possible, or should i be approaching it a different way?

A:

I think you can use powershell task to call Kudu api to get the deployed web.config and edit it using Magic Chunks task or File Transform task in your release pipeline. Then using Kudu api to upload the changed web.config to azure website again.
1, Below script shows how to get web.config from azure website.
$srcResGroupName = "Test"
$srcWebAppName = "tstest12"
$outwebconfig="$(System.DefaultWorkingDirectory)\tempfolder\web.config"

# Get publishing profile for SOURCE application
$srcWebApp = Get-AzWebApp -Name $srcWebAppName -ResourceGroupName $srcResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $srcWebApp
# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

$apiBaseUrl = "https://$($srcWebApp.Name).scm.azurewebsites.net/api/vfs/site/wwwroot/web.config"

# Download the web.config file to $outwebconfig

Invoke-RestMethod -Uri "$apiBaseUrl" `
                    -Headers @{UserAgent="powershell/1.0"; `
                     Authorization=("Basic {0}" -f $base64AuthInfo)} `
                    -Method GET `
                    -OutFile $outwebconfig

Above script will download the web.config from the azure website and save it to $(System.DefaultWorkingDirectory)\tempfolder\web.config, where you can edit it with transform task later.
Above scripts get the username and password with scripts, you can also get them in the publish profile by going to the Overview blade on your App Service, clicking ...More at the top of the blade, and then clicking Get publish profile
2, Then you can add a config transform task to change your web.config according.
3, Last add a powershell task to upload the changed web.config to azure website
$srcResGroupName = "Test"
$srcWebAppName = "tstest12"
$webconfig="$(System.DefaultWorkingDirectory)\tempfolder\web.config"

# Get publishing profile for SOURCE application
$srcWebApp = Get-AzWebApp -Name $srcWebAppName -ResourceGroupName $srcResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $srcWebApp
# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

 $apiUrl = "https://$($srcWebApp.Name).scm.azurewebsites.net/api/vfs/site/wwwroot/web.config";

Invoke-RestMethod -Uri $apiUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $webconfig -ContentType "application/xml";

For more usage of Kudu api you can check here.


Q:

Optimizing IO in C++

I'm having trouble optimizing a C++ program for the fastest runtime possible.
The requirements of the code is to output the absolute value of the difference of 2 long integers, fed through a file into the program. ie:
./myprogram < unkownfilenamefullofdata

The file name is unknown, and has 2 numbers per line, separated by a space. There is an unknown amount of test data. I created 2 files of test data. One has the extreme cases and is 5 runs long. As for the other, I used a Java program to generate 2,000,000 random numbers, and output that to a timedrun file -- 18.MB worth of tests.
The massive file runs at 3.4 seconds. I need to break that down to 1.1 seconds.
This is my code:
int main() {
long int a, b;
while (scanf("%li %li",&a,&b)>-1){
  if(b>=a)
    printf("%li/n",(b-a));
  else
    printf("%li/n",(a-b));
  } //endwhile
return 0;
}//end main

I ran Valgrind on my program, and it showed that a lot of hold-up was in the read and write portion. How would I rewrite print/scan to the most raw form of C++ if I know that I'm only going to be receiving a number? Is there a way that I can scan the number in as a binary number, and manipulate the data with logical operations to compute the difference? I was also told to consider writing a buffer, but after ~6 hours of searching the web, and attempting the code, I was unsuccessful.
Any help would be greatly appreciated.

A:

What you need to do is load the whole string into memory, and then extract the numbers from there, rather than making repeated I/O calls. However, what you may well find is that it simply takes a lot of time to load 18MB off the hard drive.


Q:

Accidental up voting

I just by accident up voted an answer that my first choice was to down vote. After the down voting i pressed the up arrow so to "cancel" my down vote and that registered as an up vote. At this time i didn't noticed and i come back after a small amount of time (8 min) and i try to cancel my up vote by pressing again the up arrow but it notifies me that "after 8 min you can't cancel an up vote unless the answer is edited". I don't understand this rule, why an accidental up vote can not be cancelled?

A:

This has already been asked on Meta.SE. Jeff Atwood himself gave this reason:

would you also like the ability to change your vote after the president has been elected? Sorry, but vote undos have historically been our #1 source of gaming and exploits. The window is very limited for a reason, so vote carefully.

Whether or not his election analogy is useful, it is pretty obvious how that can be a source of exploits.


Q:

How to cope with going back to work as a stay at home dad with two working parents

I was mostly a stay at home dad for the first year and a half of my son's life. By mostly I mean I was a full time student and we had some daycare for a couple hours a day starting very young so I could study and working up to 5-6 hours a day after he was a year old. Then I got a job. Its a decent job, but my wife is also working full time on an erratic schedule. Due to contract restrictions she can't just "quit," nor does she want to.
We have about 10 months left until our situation changes completely, and 6 months until things get easier from a scheduling perspective. So our situation seems like it may be temporary.
While at daycare my son looked at the "family wall" where they have family pictures for the kids and stared for a minute before starting to cry. However, overall my son is a pretty happy guy. I'm travelling right now. Him and his mom were visiting family for two weeks, home for a week, and then I left for business for the week. But this is the reality of our schedule for the next few months. I come home, my wife leaves, she comes home, we have a couple days or maybe a week together as a family and then one of us will be travelling again.
Has anyone out there been faced with this sort of situation?
Does anyone have any suggestions for how to teach my son (now 21 months) how to identify how he's feeling and keep things in perspective?
Is anyone aware of any long term consequences of a lifestyle like this (besides the counter intuitive greater sense of security he may gain in learning that we do come back and those times are great)?

A:

It's hard for them to understand why someone they love goes away.  And at that age when you tell them "Mommy is going to be back in a week" or "Daddy will be back in three days", they can't understand.  They might be able to count to three, but the concept of three as applied to the passage of time is probably beyond their comprehension.
I used to have some of the same issues when my husband was gone on business trips, usually lasting a week or so.  My daughter missed him so much.  The daycare providers would ask me why she was so subdued; they were worried about her.  I suggested that they verbalize for her (she has aphasia, and so was unable to speak for herself), saying "I know that your Daddy is gone for a while, and I think you must be very sad about that."  Just sharing that sorrow with her helped a lot.  Once it was expressed, she was able to move on past it better.
Here's another thing that helped a little at home.
I had photo-copied a number of airplane pictures.  If he was going to be gone six days I hung six airplanes on three to five inch yarn strings, and hung them on her bed.  Every night we got out the scissors and snipped the string for one of the airplanes.  She knew that after the last string was snipped, her Daddy would be in the house when she woke up the next morning.
Not only did it give her a very easily understood way of knowing when Daddy would be back home, it made her feel as if she had a tiny bit of control over it, I think.  By snipping the strings it felt like she was bringing Daddy home little by little.


Q:

How do I calculate correlated color temperature correctly?

How can I calculate the color temperature(CCT) of the light source illuminating a given raw image correctly?
The method I used is proposed by McCamy, and the algorithm was also described in the Wikipedia. The problem is that I don't know whether should I apply white balance process before calculating CCT.
If it should not, how do I get the conversion matrix that convert the current device-dependent RGB color space to CIE XYZ to calculate the algorithm correctly?

A:

The problem is that I don't know whether should I apply white balance process before calculating CCT.

Definitely not. Afterwards, the light source would have a completely different color profile, depending on how you implement white balance, and hence, a different color temperature.

If it should not, how do I get the conversion matrix that convert the current device-dependent RGB color space to CIE XYZ to calculate the algorithm correctly?

Get the color profile (which might be much more complex than a simple matrix) of your device; usually, that means getting the ICC file for your camera/scanner/sensor, and applying that to convert your image from the device color space to something canonical.
If your camera/scanner/sensor doesn't have such a profile, you will need to calibrate it first.


Q:

Custom scrollbar

Is it possible to replace standard scrollbar (only appearance) with some custom one (the one from http://scripterlative.com/files/autodivscroll.htm to look like the top-left example from http://www.dyn-web.com/code/scroll/demos.php?demo=vert) so the script will still work and scrollbar behave like it wasn't modified?
Thanks!

A:

Webkit supports it so it is possible in Safari and in Chrome. I tried it once, it works well.
My only problem: Doesn't support showing the scrollbar at the left or the top of the container.


Q:

How to create a full-text index using properties of subclasses in MongoDB

Let's say I have an abstract class Animal, and subclasses Dog and Cat.
My MongoDB table stores all animals, and uses a the _t type discriminator field in documents.
What I want to do is create a full-text index on 2 properties, one that exists only in Dog documents, and one that exists only in Cat documents. The JSON is straightfoward enough:
{
    "dog_only_field" : "text",
    "cat_only_field" : "text"
}

But I'd like to do this with the official C# driver. I tried this:
var builder = Builders<Animal>.IndexKeys;
var keys = builder.Text(x => ((Dog)x).MyText).Text(x => ((Cat)x).MyText);
col.Indexes.CreateOne(keys);

But got Unable to determine the serialization information for x => Convert(x).Message.

A:

I got this working by using field definitions that specify the JSON property name as a string:
var dogFieldDef = new StringFieldDefinition<Animal>("dog_only_field");
var catFieldDef = new StringFieldDefinition<Animal>("cat_only_field");

var builder = Builders<Animal>.IndexKeys;

var key = builder
    .Text(dogFieldDef)
    .Text(catFieldDef);

col.Indexes.CreateOne(key);


Q:

Running unit tests with chutzpah on real browser

Is there a way to setup Chutzpah to run test with other browser than phantomjs, preferably real browser, not headless.
I'm using chutzpah as Visual Studio extension and runner 4.2.1 for CI
Please let me know if more information needed.

A:

Today you can use the OpenInBrowser command and chutzpah will open the harness in a real browser. I am also working on supporting headless chrome but not sure when it will be ready.


Q:

Does mongodb's find() return objects missing a field from the specified projection?

If I have a mongodb containing this:
{ _id:ObjectId(0), name:"foo", hits:5 }
Will it get returned by this query:
find({name:"foo"}, {hits:1, flow:1})
If so, what will the returned object look like?

A:

Yes it will, and it will look like this:
{ "_id": ObjectId("000000000000000000000000"), "hits": 5 }

name is omitted because it's not included in the projection, but _id is included by default.


Q:

Unexpected identifier when accessing django variable in jquery

I'm just trying to set a variable in jquery so I can change some html and I'm getting the following error:

(index):208 Uncaught SyntaxError: Unexpected identifier

I have checked everything a lot, I have a feeling it will just be an infuriating typo somewhere but I need help I can't stare at it any longer. Here is my jquery:

I've taken a lot out so it's easy to look at. The script worked just fine until I added the last 3 lines so it must be there. For now this script is in the html document, I plan to move it later. I pass person to the template in the view that renders it as shown below:
def holiday(request):
    user = request.user
    # get persons username
    person_id = Person.objects.get(user_name_check=request.user)

    #....

    context = {
        "person": person_id,
        "start_dates": start_list,
        "end_dates": end_list,
        "people": person_list,
    }
    return render(request, "tande/calendar.html", context)

Thanks!

A:

If the variable isn't a JSON object it should be in quotes. see: https://stackoverflow.com/a/4153424/5433407
i.e.
var the_person = "{{ person }}";

For now this script is in the html document, I plan to move it later.

Using django template variables won't work if you take this out of the html, see: https://stackoverflow.com/a/32998283/5433407


Q:

Convert Akamai Edgescape header data into array

I'm using Akamai to detect Geolocation. Akamai returns the following data in the header:
X-Akamai-Edgescape: georegion=279,country_code=US,region_code=OR,city=BEAVERTON,dma=820,pmsa=6440,msa=6442,areacode=503,county=WASHINGTON,fips=41067,lat=45.4908,long=-122.8046,timezone=PST,zip=97005-97008+97075-97077,continent=NA,throughput=vhigh,bw=5000,network=comcast,asnum=33490,network_type=cable,location_id=0

I'm converting this data into an array using PHP explode.
Array
(
  [0] => georegion=279
  [1] => country_code=US
  [2] => region_code=OR
  [3] => city=BEAVERTON
  [4] => dma=820
  [5] => pmsa=6440
  [6] => msa=6442
  [7] => areacode=503
  [8] => county=WASHINGTON
  [9] => fips=41067
  [10] => lat=45.4908
  [11] => long=-122.8046
  [12] => timezone=PST
  [13] => zip=97005-97008+97075-97077
  [14] => continent=NA
  [15] => throughput=vhigh
  [16] => bw=5000
  [17] => network=comcast
  [18] => asnum=33490
  [19] => network_type=cable
  [20] => location_id=0
)

Getting the key value pairs is pretty easy, however, in order to make this future proof I don't want to grab the values with the current keys because the order of the items returned by Akamai could be changed by them.
What's the best way to go about converting this array and/or data into something more like the following?
Array
(
  georegion => 279
  country_code => US
  ...
  location_id => 0
)

A:

There are a few ways to parse the string into a key value pair.
Using explode() and a foreach loop:
<?php
$str = 'georegion=279,country_code=US,region_code=OR,city=BEAVERTON,dma=820,pmsa=6440,msa=6442,areacode=503,county=WASHINGTON,fips=41067,lat=45.4908,long=-122.8046,timezone=PST,zip=97005-97008+97075-97077,continent=NA,throughput=vhigh,bw=5000,network=comcast,asnum=33490,network_type=cable,location_id=0';

$array = explode(',', $str);

foreach ($array as $key => $value) {
    $v = explode('=', $value);
    $array[$v[0]] = $v[1];
    unset($array[$key]);
}

Using explode() and array_map():
<?php
$str = 'georegion=279,country_code=US,region_code=OR,city=BEAVERTON,dma=820,pmsa=6440,msa=6442,areacode=503,county=WASHINGTON,fips=41067,lat=45.4908,long=-122.8046,timezone=PST,zip=97005-97008+97075-97077,continent=NA,throughput=vhigh,bw=5000,network=comcast,asnum=33490,network_type=cable,location_id=0';

$array = explode(',', $str);

array_map(function ($value, $key) use (&$array) {
    $v = explode('=', $value);
    $array[$v[0]] = $v[1];
    unset($array[$key]);
}, $array, array_keys($array));

Using regex to match key and value, then array_combine():
<?php
$str = 'georegion=279,country_code=US,region_code=OR,city=BEAVERTON,dma=820,pmsa=6440,msa=6442,areacode=503,county=WASHINGTON,fips=41067,lat=45.4908,long=-122.8046,timezone=PST,zip=97005-97008+97075-97077,continent=NA,throughput=vhigh,bw=5000,network=comcast,asnum=33490,network_type=cable,location_id=0';

preg_match_all("/([^,=]+)=([^,=]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);

Using str_replace() to switch , for &, then parse_str():
<?php
$str = 'georegion=279,country_code=US,region_code=OR,city=BEAVERTON,dma=820,pmsa=6440,msa=6442,areacode=503,county=WASHINGTON,fips=41067,lat=45.4908,long=-122.8046,timezone=PST,zip=97005-97008+97075-97077,continent=NA,throughput=vhigh,bw=5000,network=comcast,asnum=33490,network_type=cable,location_id=0';

parse_str(str_replace(",", "&", $str), $array);

All methods will produce the same array structure:
Array
(
    [georegion] => 279
    [country_code] => US
    [region_code] => OR
    [city] => BEAVERTON
    [dma] => 820
    [pmsa] => 6440
    [msa] => 6442
    [areacode] => 503
    [county] => WASHINGTON
    [fips] => 41067
    [lat] => 45.4908
    [long] => -122.8046
    [timezone] => PST
    [zip] => 97005-97008+97075-97077
    [continent] => NA
    [throughput] => vhigh
    [bw] => 5000
    [network] => comcast
    [asnum] => 33490
    [network_type] => cable
    [location_id] => 0
)


Q:

Convert an iteration over dictionaries into a pandas dataframe

I have generated 2 dictionaries from 2 input files using conditional statements (not shown). I then aimed to use these 2 dictionaries to identify overlapping values. I would then like to use the output from the iteration as a pandas dataframe directly. To do that, I am first outputting the iteration/for loop  into a file (Output.xls) and then I read the file as pandas dataframe. While this works well, I was wondering if there is a way to use my 'newline' from iteration below directly as an input to an empty pandas dataframe. I couldn't find an option on Python that does that except dataFrame.from_dict . However, this takes in 1 dictionary but I have multiple dictionaries that I am joining together, as well as other variables that I am utilizing.

exp1_dict.items() is:
[('lnc3', ['SPATA1', 'AHNAK', 'FGG', 'ERAP1', 'HZ', 'SAASDAS', 'NLRC5', 'HUWE1']), ('lnc2', ['SPATA1', 'FGG', 'TMEM68', 'ATP6AP', 'HUWE1']), ('lnc1', ['SPATA1', 'AHNAK', 'FGG', 'TMEM68', 'ERAP1', 'ATP6AP', 'SAASDAS', 'RAD17', 'HUWE1'])]

exp2_dict.items() is:
[('lnc3', ['SPATA1', 'AHNAK', 'TMEM68', 'ERAP1', 'HZ', 'RAD17', 'NLRC5', 'HUWE1']), ('lnc2', ['SPATA1', 'FGG', 'ERAP1', 'HZ']), ('lnc1', ['SPATA1', 'AHNAK', 'FGG', 'TMEM68', 'ERAP1', 'HZ', 'ATP6AP', 'RAD17']), ('lnc4', ['ERAP1', 'PRSS16', 'HZ', 'NLRC5'])]

The code to iterate over dictionaries and generates a 'newline' is:
out = open("Output.xls", "w") #generates an empty output file
out.write('Header1\tHeader2\tHeader3\tHeader4\tHeader5\tHeader6\tHeader7\tHeader8\tHeader9\tHeader10\tHeader11\n')#Adds header to output file

intersection_dict={} #empty intersection header
for key, value1 in exp1_dict.items(): #reiterates over the 2 dictionaries
        if key in exp2_dict.keys():
                intersection_dict[key]=list(set(value1).intersection(exp2_dict[key]))
                newline=key, str(f_exp1_dict[key]), str(f_exp2_dict[key]), str('|'.join(value1)), str(len(exp1_dict[key])), str(len(exp1_corr.index)), str('|'.join(exp2_dict[key])), str(len(exp2_dict[key])), str(len(exp2_corr.index)), str('|'.join(intersection_dict[key])), str(len(intersection_dict[key]))
                out.write('\t'.join(newline)+'\n')

I then read the Output.xls file using pandas dataframe:
out.close()
new_input=pd.read)table("Output.xls", index_col=0)

Instead of creating an output file then inputting it as a pandas dataframe, I was wondering if there is a way to write "newline" above to an empty pandas dataframe with the headers above directly.
The Output.xls file looks like this:

Header1 Header2 Header3 Header4 Header5 Header6 Header7 Header8 Header9 Header10    Header11
lnc3    4   4   SPATA1|AHNAK|FGG|ERAP1|HZ|SAASDAS|NLRC5|HUWE1   8   12  SPATA1|AHNAK|TMEM68|ERAP1|HZ|RAD17|NLRC5|HUWE1  8   12  HZ|ERAP1|AHNAK|HUWE1|NLRC5|SPATA1   6
lnc2    2   3   SPATA1|FGG|TMEM68|ATP6AP|HUWE1  5   12  SPATA1|FGG|ERAP1|HZ 4   12  SPATA1|FGG  2
lnc1    1.5 2   SPATA1|AHNAK|FGG|TMEM68|ERAP1|ATP6AP|SAASDAS|RAD17|HUWE1    9   12  SPATA1|AHNAK|FGG|TMEM68|ERAP1|HZ|ATP6AP|RAD17   8   12  ERAP1|RAD17|AHNAK|TMEM68|ATP6AP|SPATA1|FGG  7

A:

Create a list of lists which you then use to create your dataframe:
df = []
for key, value1 in exp1_dict.iteritems():
    if key in exp2_dict:
        dict_union = list(set(value1).intersection(exp2_dict[key]))
        col1 = key
        col2 = str(f_exp1_dict[key])
        col2 = str(f_exp2_dict[key])
        col3 = str('|'.join(value1))
        col4 = str(len(exp1_dict[key]))
        col5 = str(len(exp1_corr.index))
        col6 = str('|'.join(exp2_dict[key]))
        col7 = str(len(exp2_dict[key]))
        col8 = str(len(exp2_corr.index))
        col9 = str('|'.join(dict_union))
        col10 = str(dict_union)
        df.append([col1, col2, col3, col4, col5, col6, col7, col8, col9, col10])

df = pd.DataFrame(df)


Q:

quicksort algorithm stability

Quicksort is not stable, since it exchanges nonadjacent elements.

Please help me understanding this statement.
I know  how partitioning works, and what stability is. But I cant figure out what makes the above as the reason for this to be not stable?
Then I believe the same can be said for merge sort - though it is quoted to be a stable algorithm.

A:

Consider what happens during the partition for the following array of pairs, where the comparator uses the integer (only). The string is just there so that we have two elements that compare as if equal, but actually are distinguishable.
(4, "first"), (2, ""), (3, ""), (4, "second"), (1, "")

By definition a sort is stable if, after the sort, the two elements that compare as if equal (the two 4s) appear in the same order afterwards as they did before.
Suppose we choose 3 as the pivot. The two 4 elements will end up after it and the 1 and the 2 before it (there's a bit more to it than that, I've ignored moving the pivot since it's already in the correct position, but you say you understand partitioning).
Quicksorts in general don't give any particular guarantee where after the partition the two 4s will be, and I think most implementations would reverse them. For instance, if we use Hoare's classic partitioning algorithm, the array is partitioned as follows:
(1, ""), (2, ""), (3, ""), (4, "second"), (4, "first")

which violates the stability of sorting.
Since each partition isn't stable, the overall sort isn't likely to be.
As Steve314 points out in a comment, merge sort is stable provided that when merging, if you encounter equal elements you always output first the one that came from the "lower down" of the two halves that you're merging together. That is, each merge has to look like this, where the "left" is the side that comes from lower down in the original array.
while (left not empty and right not empty):
    if first_item_on_left <= first_item_on_right:
       move one item from left to output
    else:
       move one item from right to output
move everything from left to output
move everything from right to output

If the <= were < then the merge wouldn't be stable.

A:

It will be like a user has a sorted array, and sorts by another column, does the sort algorithm always preserve the relative order of the elements that differ for the previous sort key but have the same value in the new sort key?
So, in A sort algorithm which always preserves the order of elements (which do not differ in the new sort key) is called a "stable sort".


Q:

How can I construct HTML using NameValuePair in android?

I'm trying to implement VPOS in my android application. I have C# implementation. I am trying to change according to Android. In C# code;
NameValueCollection parameters = new NameValueCollection();
parameters.Add("mode", strmode); //just one of parameter.
RedirectAndPOST(this, "url", parameters);
public static void RedirectAndPOST(Page page, string destinationUrl, NameValueCollection data)
    {
        string strForm = PreparePOSTForm(destinationUrl, data);

        page.Controls.Add(new LiteralControl(strForm));
    }

    private static String PreparePOSTForm(string url, NameValueCollection data)
    {
        string formID = "PostForm";

        StringBuilder strForm = new StringBuilder();

        strForm.AppendFormat("<form id=\"{0}\" name=\"{0}\" action=\"{1}\" method=\"POST\">", formID, url);

        foreach (string key in data)
        {

            strForm.AppendFormat("<input type=\"hidden\" name=\"{0}\" value=\"{1}\">", key, data[key]);

        }

        strForm.Append("</form>");

        StringBuilder strScript = new StringBuilder();

        strScript.Append("<script language=\"javascript\">");

        strScript.AppendFormat("document.{0}.submit();", formID);

        strScript.Append("</script>");

        return strForm.ToString() + strScript.ToString();

    }

In my Java code, first, I created NameValuePair, then, I create preparePOSTMethod method for construct HTML. After, I send HTTP POST Request.
ArrayList<NameValuePair> parameter = new ArrayList<NameValuePair>();
 parameter.add(new BasicNameValuePair("mode", strmode));
 parameter.add(new BasicNameValuePair("cardnumber", cardNumber));
 parameter.add(new BasicNameValuePair("cardexpiredatemonth", cardExpireDateMonth));
 parameter.add(new BasicNameValuePair("cardexpiredateyear", cardExpireDateYear));
 parameter.add(new BasicNameValuePair("cardcvv2", CardCvv2));
post = preparePOSTForm("url", parameter);
private static String preparePOSTForm(String url, ArrayList<NameValuePair> data)

    {
        String formID = "PostForm";

        StringBuilder strForm = new StringBuilder();

        strForm.append(String.format("<form id=\"{0}\" name=\"{0}\" action=\"{1}\" method=\"POST\">", formID, url));

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

            strForm.append(String.format("<input type=\"hidden\" name=\"{0}\" value=\"{1}\">", data.get(i).getName(), data.get(i).getValue()));

        }

        strForm.append("</form>");

        StringBuilder strScript = new StringBuilder();

        strScript.append("<script language=\"javascript\">");

        strScript.append(String.format("document.{0}.submit();", formID));

        strScript.append("</script>");

        param = strForm.toString() + strScript.toString();
        System.out.println("result:  "+param);
        return strForm.toString() + strScript.toString();
    }

However, I cannot construct HTML.
Result: <form id="{0}" name="{0}" action="{1}" method="POST"><input type="hidden" name="{0}" value="{1}"><input type="hidden" name="{0}" value="{1}"><input type="hidden" name="{0}" value="{1}"><input type="hidden" name="{0}" value="{1}"><input type="hidden" name="{0}" value="{1}"><input type="hidden" name="{0}" value="{1}"></form><script language="javascript">document.{0}.submit();</script>

How can I construct HTML using Name-Value Pair and StringBuilder or something else?

A:

 strForm.append(String.format("<input type=\"hidden\" name=\"{0}\" value=\"{1}\">"
      , data.get(i).getName(), data.get(i).getValue()));

As you see the parameters are not filled in. You just get that format string unchanged.
Use %s instead of {0} and {1}.


Q:

MySQL group by calculated field

I have members that have to pay for their membership. And I store: payment date, and membership length (they can pay for 1 month or several).
Now I'd like to know which payments are overdue, or soon to be.
My logic was: get an expiration date for each membership (last payment date + membership length) and then just look at the highest value of that for each member.
Here's my query, but I did want to explain my reasoning, as you may want to question that or even the format of the DB (but please don't ask me to store the expiration date).
SELECT tbl.company AS company,
       MAX(ADDDATE( paydate, INTERVAL paylength MONTH ))) AS expiration,
       tbl.id
FROM tblPayments
JOIN tbl ON tblPayments.comp_id = tbl.id
GROUP BY expiration
ORDER BY expiration ASC

I've read that grouping by calculated fields may not be possible, but my knowledge of MySQL is not strong enough to understand the workarounds. I'd appreciate any help you can provide! Thanks!

A:

You are grouping by the aggregated result of your group which is not possible and not what you intended. Based on your explanation I would think you are trying to do this
SELECT
    tbl.company AS company,
    MAX(ADDDATE( paydate, INTERVAL paylength MONTH )) AS expiration,
    tbl.id
FROM tblPayments
JOIN tbl
    ON tblPayments.comp_id = tbl.id
GROUP BY tbl.company , tbl.id
HAVING expiration < NOW()
ORDER BY expiration ASC

And @dleiftah brings up a good point, you cannot always use the alias although MySQL seems to let you in a GROUP BY whereas MSSQL never does. I forget exactly when...


Q:

Best way to avoid pipe freeze in exterior wall?

We have an exterior wall framed with 2x6's. We are running PEX piping to a pot filler faucet through this wall to go above the stove top. Is there any precaution we should be taking besides standard install? We live in KS so winters can get cold, but not horrible.

A:

Bear in mind that even though precautions are made, it is still possible for the pipes to freeze in a particularly harsh winter.
You are going to want a shut off valve with a built in drain on it. This will allow you to winterize it. The shutoff should be located in an accessible place which is below where the tap will be. If you are on the first floor, then the shutoff should go in the basement/crawl space.
When you install the plumbing, you will want to keep the supply pipes as close to the inside wall as possible. In a 2 x 6 wall, you would want to bore the holes in the studs slightly off center, approx. 1" to 1 1/2" from the inside instead of dead center. You will also need to install a nail protection plate on the studs where the pipe passes through, so the pipe would not get pierced when the drywall is installed. It would also be a good idea to add a tile backsplash which completely covers the area where the pipe is, so someone won't drive a nail or a screw into the pipe later on.
This will allow you to add more insulation behind the pipe. The best insulation for this is closed cell foam, since it acts as a vapor barrier as well. You will want to eliminate any possible cold drafts that could hit the pipe. Also, when you insulate, you will want to leave the side of the pipe facing the inside uninsulated. This will allow more heat from the house to come in contact with the pipe.
If you can live without the pot filler during the winter months, the safest thing would be to winterize it. That way there is no chance that the pipes would freeze. You can also leave the water on a tiny bit and let it drip slowly on the coldest days to prevent it from freezing up. The good thing about PEX is that it can survive being frozen from time to time, but it is possible that the fittings themselves can fail.


Q:

Determining if a sum is complex differentiable

Given $ \ f:\mathbb{C} \rightarrow \mathbb{C}\ , \ f(z) = \sum_{k=1}^N 2^k |z|^{2k}$
Is $ \ f \ $ complex differentiable?
Now, if I can differentiate each individual term, then I can say that $ \ f \ $ is complex differentiable?

A:

No non-constant real-valued function is complex differentiable.


Q:

Put javascript directly in views instead of assets/javascript in Rails?

When we generate a model, such as Fruit, it auto generates assets/javascripts/fruits.js
However, say if we have javascript callbacks for only a paragraph element in views/fruits/show.html, should it be placed directly in show.html? Is it more conventional or faster to put it in fruits.js?

A:

You can use content_for to achieve it.
<%# views/layouts/application.html.erb %>
<head>
  <title>My Website</title>
  <%= yield :script %>
</head>

<%# views/fruits/show.html %>
<% content_for :script do %>
  <%= javascript_include_tag :fruits %>
<% end %>


Q:

Why Angular.js different version has different structure?

I am new in Angular and I am going to use it with a famous PHP Framework what named Laravel, I downloaded some video tutorial from here that was about Angular, that include some video tuterial from Lynda, Tutsplus and pluralsight But unfortunately the code what the teacher said on that video tutorials and when I do it with the latest version of Angular, The codes not working with that version.
my questions:
1-Why library programmer change the structure of their libraries or programs? (Laravel changed too)
2-Where can I learn Angular from video?

A:

Actually there is lot of migrations in angular versions which includes some syntax changes as well
1.2 -> 1.3 (Doc)
So just keep your self update.