text:
Q: Rolling up items in D3? So let's say hypothetically I have a json array like this:
[{"country":"Argentina", "impressions":199},
{"country":"Peru", "impressions":100},
{"country":"Brazil", "impressions":500}
{"country":"Argentina", "impressions":201},
{"country":"Peru", "impressions":504},]

and I want to use D3.js to create a table where each country is only listed once. Is there anything like "select distinct" in SQL for D3? I have all the code for the table already, and it generates a table that lays out my data exactly as it appears above, but I need the data rolled up.
Thanks for any help you guys can give me!

A: -- d3.nest with a rollup --
var nested_data = d3.nest()
  .key(function(d) {
    return d.country;
  })
  .rollup(function(o){
    return d3.sum(o,function(d){
      return d.impressions;
    });
  })
  .entries(data);

Returns:

Full working code:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>

<body>
  <script>
    var data = [{
      "country": "Argentina",
      "impressions": 199
    }, {
      "country": "Peru",
      "impressions": 100
    }, {
      "country": "Brazil",
      "impressions": 500
    }, {
      "country": "Argentina",
      "impressions": 201
    }, {
      "country": "Peru",
      "impressions": 504
    }];

    var nested_data = d3.nest()
      .key(function(d) {
        return d.country;
      })
      .rollup(function(o){
        return d3.sum(o,function(d){
          return d.impressions;
        });
      })
      .entries(data);

    d3.select('body').html(JSON.stringify(nested_data));
  </script>
</body>

</html>


text:
Q: AJAX upload file I know there is a ton of questions like this but I can't get things to work :(
In script below only "test=bla" is posted and file is not. What am I doing wrong?
Thanks!!!
<input type="file" name="fileUpload" id="fileUpload" onchange="fileUploadChange(this);"   />

function fileUploadChange(e) {
    var mydata = new FormData();
    mydata.append("test", "bla");
    mydata.append("fff", e.files[0]);

    $.ajax({
        type: "POST",
        url: "TestApp/Home/fileUpload",
        contentType: false,
        processData: false,
        data: mydata,
        success: function (data) {
            alert("success");
        }
        error: function (error) {
            alert("error");
        }
    });
}

After further investigation I have figured it out: in .NET MVC, Controller.Request object has Form property and Files property. Simple data items like strings, integers etc can be found in the Form.Keys, Files are located in Request.Files

A: u missed , between success and error methods.
$.ajax({
        type: "POST",
        url: "TestApp/Home/fileUpload",
        contentType: false,
        processData: false,
        data: mydata,
        success: function (data) {
            alert("success");
        },
        error: function (error) {
            alert("error");
        }
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return the list values from this haskell snippet I know it is verbose but that is how I am learning the syntax.  With this line at
(abCombo' a 2 lst) ... I want to return the 'list' and/or print the list but I am having trouble extracting the list with this return type, ' Writer [String] [Int]'.
-- Loop through several integer values
-- and calculate the power of a^b, append to list
abCombo' :: Int -> Int -> [Int] -> Writer [String] [Int]
abCombo' a b lst
    | b == maxB = do
        tell [ "  ... x-Done(1): a^b = " ++ show (a^b) ++ " // " ++ show lst  ]
        return ((a^b):lst)
    | otherwise = do
        tell [ "  ... x-Processing: a^b = " ++ show (a^b) ++ " // " ++ show lst ]
        abCombo' a (b+1) ((a^b):lst)

-- Loop through several integer values
-- and calculate the power of a^b, append to list
abCombo :: Int -> [Int] -> Writer [String] [Int]
abCombo a lst
    | a == maxA = do
        tell [ "- Done(2): a=" ++ show a ]
        abCombo' a 2 lst
    | otherwise = do
        (abCombo' a 2 lst) <<<<<<<<<<<<<<<<<<<<<< line of interest, here
        tell ["- Processing: a=" ++ show a]
        abCombo (a + 1) lst

...
That is the current code above, I want to change it to:
abCombo :: Int -> [Int] -> Writer [String] [Int]
abCombo a lst
    | a == maxA = do
        tell [ "- Done(2): a=" ++ show a ]
        abCombo' a 2 lst
    | otherwise = do
        let res = (abCombo' a 2 lst) <<<<<<<<<<<<<<<<<<<<<< line of interest, here
        tell ["- Processing: a=" ++ show a]
        abCombo (a + 1) (flatten snd res)

A: To bind the result of an action in a do-block you need to use <- instead of let.
res <- abCombo' a 2 lst      -- res :: [Int]

This is because with let, you're just putting a name on the action itself.
let res = abCombo' a 2 lst   -- res :: Writer [String] [Int]


text:
Q: Custom UIView - autolayout not applied My registration scene has a custom UIView on the scene. There are autolayout constraints applied as per the following screen. The yellow indicates the custom view.

The custom view is set in identity inspector to RegisterView. The RegisterView class simply loads a XIB:
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    NSBundle.mainBundle().loadNibNamed("RegisterUserView", owner: self, options: nil)
}

The XIB has autolayout applied so as it renders as follows:

However, when I run the application it appears that autolayout constraints haven't been applied:

Do I need to add code to force the layout constraints to apply?

A: I tried something like the below and it worked
override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        self.customSubView = CustomView1.loadFromNibNamed("CustomView") as! CustomView1

        customSubView.frame = _CustomSubView.frame
        customSubView.frame.origin = CGPoint(x: 0, y: 0)
        self._CustomSubView.addSubview(customSubView)
    }

Hope it helps


text:
Q: ActiveRecord where OR clause. Can equal nil or a time earlier than Time.now I have a Food model with an expired_at field. If the food is not expired, the expired_at field is set to nil. If it is expired, the field is set to a time earlier than Time.now. It can be set to a time in the future, and the food is not expired yet.
If I'm trying to write a scope that gives me back non-expired food, what can I do? I want something like:
scope :non_expired, -> { where(expired_at: nil OR expired_at > Time.now)

The above doesn't work. What can I do?

A: If you are using rails version less than 5, there is no support for or.
For exmaple
Rails 4
scope :non_expired, ->{ where('expired_at = ? OR expired_at >', nil, Time.now) }

Rails 5
{ where('expired_at = ?', nil).or(Food.where('expired_at > ?', Time.now) }


text:
Q: how to make custom alert in jquery mobile? can you please tell me how to make custom alert in jquery mobile?I am able to make confirm in JQM.
http://jsfiddle.net/EELLj/31/
I need same type of alert having message with ok button as in jquery ?
A alert having "title", "message" and ok button ? can we make this custom alert.
function confirmDialog(text, callback) {
    var popupDialogId = 'popupDialog';
    $('
 \

\

Alert
\

\

\

' + text + '
\
                            Yes\
                            No\

\

')
        .appendTo($.mobile.pageContainer);
    var popupDialogObj = $('#' + popupDialogId);
    popupDialogObj.trigger('create');
    popupDialogObj.popup({
        afterclose: function (event, ui) {
            popupDialogObj.find(".optionConfirm").first().off('click');
            var isConfirmed = popupDialogObj.attr('data-confirmed') === 'yes' ? true : false;
            $(event.target).remove();
            if (isConfirmed && callback) {
                callback();
            }
        }
    });
    popupDialogObj.popup('open');
    popupDialogObj.find(".optionConfirm").first().on('click', function () {
        popupDialogObj.attr('data-confirmed', 'yes');
    });
}

$('#testButton').on('click', function () {
    confirmDialog("Are you sure?", function(){
        alert('Confirmed');
    });
});


text:
Q: SQL query execution - different outcomes on Windows and Linux The following is generated query from Hibernate (except I replaced the list of fields with *):
select *
from
    resource resource0_,
    resourceOrganization resourceor1_
where
    resource0_.active=1
    and resource0_.published=1
    and (
        resource0_.resourcePublic=1
        or resourceor1_.resource_id=resource0_.id
        and resourceor1_.organization_id=2
        and (
            resourceor1_.resource_id=resource0_.id
            and resourceor1_.forever=1
            or resourceor1_.resource_id=resource0_.id
            and (
                current_date between resourceor1_.startDate and resourceor1_.endDate
            )
        )
    )

Currently I have 200+ records in both the Windows and Linux databases and currently for each record, the following happens to be true:
active = 1
published = 1
resourcePublic = 1
When I run this directly in a SQL client, this SQL query gets me all the matching records on Windows but none on Linux. I've MySQL 5.1 on both Windows and Linux.
If I apply the Boolean logic, (true and true and (true or whatever)), I expect the outcome to be true. It indeed is true on Windows but false on Linux!!!
If I modify the query as the following, it works on both Windows and Linux:
select *
from
    resource resource0_
where
    resource0_.active=1
    and resource0_.published=1
    and (
        resource0_.resourcePublic=1
    )

So, just the presence of conditions related to resourceOrganization is making the query bring 0 results on Linux and I expected that since it is the second part of an 'or' condition whose first part is true, the outcome should be true.
Any idea why this difference in behavior between the 2 OSs and why what should obviously work on Linux doesn't!
Thanks in advance!

A: *

*Check the case sensitivity and collation sets (Collation issues)

*Check the table case sensitivity. In particular note that on windows the table names are case-insensitive and on Linux they are case-sensitive.

*Have you tried a simple test case on both system?

A: Check that current_date() returns the same format in both plataforms

A: Also don't forget to check the collation and case sensitivity, if one server uses a different collation to the other then you will have this same issue.

A: I notice that the second test query only consults the resource table not the resourceOrganisation table.
I suspect that the table resourceOrganisation is populated differently on the two machines, and the corresponding rows may not exist in your Linux MySQL.
What does this query return?
select *
from
    resource resource0_,
    resourceOrganization resourceor1_
where
    resource0_.active=1
    and resource0_.published=1
    and (
        resource0_.resourcePublic=1
        or resourceor1_.resource_id=resource0_.id
        and resourceor1_.organization_id=2
    )


text:
Q: aws s3 sync cli ignoring multipart upload config when syncing between buckets I'm trying to sync a large number of files from one bucket to another, some of the files are up to 2GB in size after using the aws cli's s3 sync command like so
aws s3 sync s3://bucket/folder/folder s3://destination-bucket/folder/folder

and verifying the files that had been transferred it became clear that the large files had lost the metadata that was present on the original file in the original bucket.
This is a "known" issue with larger files where s3 switches to multipart upload to handled the transfer.
This multipart handeling can be configured via the .aws/config file which has been done like so
[default]
s3 =
    multipart_threshold = 4500MB

However when again testing the transfer the metadata on the larger files is still not present, it is present on any of the smaller files so it's clear that I'm heating the multipart upload issue.
Given this is an s3 to s3 transfer is the local s3 configuration taken into consideration at all?
As an alternative to this is there a way to just sync the metadata now that all the files have been transferred?
Have also tried doing aws s3 cp with no luck either.

A: You could use Cross/Same-Region Replication to copy the objects to another Amazon S3 bucket.
However, only newly added objects will copy between the buckets. You can, however, trigger the copy by copying the objects onto themselves. I'd recommend you test this on a separate bucket first, to make sure you don't accidentally lose any of the metadata.
The method suggested seems rather complex: Trigger cross-region replication of pre-existing objects using Amazon S3 inventory, Amazon EMR, and Amazon Athena | AWS Big Data Blog
The final option would be to write your own code to copy the objects, and copy the metadata at the same time.
Or, you could write a script that compares the two buckets to see which objects did not get their correct metadata, and have it just update the metadata on the target object. This actually involves copying the object to itself, while specifying the metadata. This is probably easier than copying ALL objects yourself, since it only needs to 'fix' the ones that didn't get their metadata.

A: Finally managed to implement a solution for this and took the oportunity to play around with the Serverless framework and Step Functions.
The general flow I went with was:

*

*Step Function triggered using a Cloudwatch Event Rule targetting S3 Events of the type 'CompleteMultipartUpload', as the metadata is only ever missing on S3 objects that had to be transfered using a multipart process

*The initial Task on the Step Function checks if all the required MetaData is present on the object that raised the event.

*

*If it is present then the Step Function is finished

*If it is not present then the second lambda task is fired which copies all metadata from the source object to the destination object.

This could be achieved without Step Functions however was a good simple exercise to give them a go. The first 'Check Meta' task is actually redundant as the metadata is never present if multipart transfer is used, I was originally also triggering off of PutObject and CopyObject as well which is why I had the Check Meta task.


text:
Q: Converting TIFF to JPEG using .NET I need to convert a TIFF to JPEG using .NET.
I have already done this succesfully using Windows 7 with a simple Bitmap.Save(). But it seems that this doesn't work on Windows XP (Windows 7 has more complete support for TIFF images).
I saw that there is a .NET library called LibTiff.Net that works well with TIFF, but I didn't find any example code.
Any ideas? Any sample code to convert JPEG to TIFF?
Really thanks

A: I assume that you want to convert TIFF to JPEG (as stated in title of the question) and not JPEG to TIFF (as stated in the question body)
Here is a sample that creates System.Drawing.Bitmap from a TIFF.
You can save the bitmap as a JPEG file.


text:
Q: pulseaudio module causes asserts on 32 bit machines (max_latency <= (10*((pa_usec_t)) I am compiling module-virtual-sink.c that comes with pulseaudio 1.1 on Ubuntu 32 and 64 bit platforms running pulseaudio-1.1.
When I load the module on 32 bit machines I get the following assertion:
Dec 15 07:57:53 ubuntu pulseaudio[12541]: [alsa-sink] sink.c: Assertion 'max_latency <= (10*((pa_usec_t) 1000000ULL))' failed at pulsecore/sink.c:2971, function pa_sink_set_latency_range_within_thread(). Aborting.

In module-virtual-sink.c:
pa_sink_set_latency_range_within_thread(u->sink, i->sink->thread_info.min_latency, i->sink->thread_info.max_latency);

Is passing over wrong values.
i->sink->thread_info.min_latency, i->sink->thread_info.max_latency are passing over 0 and 500 instead of 500 and 100000.
There are 32 bits missing in the thread_info struct which my gcc is generating compared to the struct created by pulseaudio in pa_sink_new right before soft_volume
thread_info.soft_volume

causing wrong values being read and passed on to pa_sink_set_latency_range_within_thread.
struct {
    pa_sink_state_t state;
    pa_hashmap *inputs;
    pa_rtpoll *rtpoll;
    pa_cvolume soft_volume;
    pa_bool_t soft_muted:1;

typedef struct pa_cvolume {
  uint8_t channels;                     /**< Number of channels */
  pa_volume_t values[PA_CHANNELS_MAX];  /**< Per-channel volume */
} pa_cvolume;

(gdb) x /100xb &(u->sink->thread_info)
0x8b6c634:  0x00    0x00    0x00    0x00    0xfe    0xff    0xff    0xff
0x8b6c63c:  0x08    0xd0    0xb6    0x08    0x00    0x00    0x00    0x00
0x8b6c644:  0x02    0x00    0x00    0x00    0x00    0x00    0x01    0x00

(gdb) print (u->sink->thread_info)
$5 = {state = PA_SINK_RUNNING, inputs = 0xfffffffe, rtpoll = 0x8b6d008, soft_volume = {channels = 0 '\000', values = {2,65536, 65536,

thread_info.soft_volume.channels is 0 instead of 2. The compiled code is looking at the wrong position - address 0x8b6c640 instead of 0x8b6c644
I suspect a compiler configuration problem or source mismatch.
Needless to say that this was tested using GCC after creating the config.h file using ../configure
Any ideas what might cause this behavior?


text:
Q: Can i sort query set return objects in order to function result I am writing a web based music application and I want implement some feature that user can see most favor album in last week-month-year.
so this is my model :
class album(models.Model):
   def get_weely_count():
      ...
   def get_monthly_count():
      ...

   def get_yearly_count():
      ...

class like(models.Model):
   created_at = models.DateField()
   albumID = models.ForeignKey(Album)

Now I want to receive albums that most liked in last week or last month or last year,I want done some thing like this(but I can not):
Album.objects.all().order_by('get_weekly_count')

can any one help me to fix it or give another approach to achieve that goal??

A: The order_by method translates into an SQL ORDER BY, therefore it works only with model fields, which correspond to table columns. It won't work if you intend to sort your elements by a model's method.
So, if you want to accomplish something like
Album.objects.all().order_by('get_weekly_count')

You'll have to do it the python way
sorted(Album.objects.all(), key=lambda x: x.get_weekly_count())

Performance-wise, this means you'll get your elements with a query and then you'll sort them with python (that's different from getting a sorted queryset in one shot).
Otherwise, if it's possible for you to turn get_weekly_count into raw SQL, you could use it with a Count() or an extra modifier, that would make order_by usable, i.e.:
Album.objects.all().extra(
    select={'weekly_count': "<some SQL>"},
    select_params=(<you params>,),
).order_by('weekly_count')

Have a look at https://docs.djangoproject.com/en/1.8/ref/models/querysets/#extra

A: According to the documentation, you should use:
from django.db.models import Count
like.objects.filter(created_at__gt=START_OF_MONTH, created_at__lt=Datetime.now()).values('albumID').annotate(count=Count('albumID')).order_by('count')

This will get results for you in single db query. For more details visit https://docs.djangoproject.com/en/dev/topics/db/aggregation/.


text:
Q: Display content based on checkbox - jquery I have 8 divs.initially 4 of them are displayed and remaining 4 are styled as dislay:none.
The FIDDLE code is here
First 4 checkbox correspond to the first 4 divs. When 1st checkbox is unchecked the first div is disabled and default div empty is enabled. similarly when 2nd checkbox is unchecked the 2nd div is diabled and default div empty is enabled. similarly 3rd and 4th divs.
The last 4 checkbox correspond to last 4 divs. These checkbox must be enabled to check or uncheck only if any of the first 4 divs are disabled and when any of these 4 checkbox are enabled the corresponding div must be displayed in the place of default div.
for example checkbox with name=box1 is unchecked then div_box_1 must be disabled and div empty must be enabled. After this if checkbox with name=box6 is checked then div empty must be disabled and div_box_6 must be enabled.

A: The way jQuery selectors work, is for every peice of text you add, it'll think its another child node or w/e.
The problem is :
$("input.css-checkbox:checkbox").click(function(){
Your selecting the  with the class "css-checkbox" already. With the :checkbox it assumes something MORE after that. ( I forget what this selector does TBH ) But when you remove the ":checkbox" it hides and shows.
$("input.css-checkbox").click(function(){


text:
Q: Will you be labeled a warmonger if keep recapturing an enemy city? While playing on Emperor difficulty, I decided to take an enemy city. The notification said I would only receive a "minor" penalty, which I thought was no big deal. Turns out the enemy had at least 20 units hanging around nearby. Over the next 15 turns, I lost the city at least 7 times and ended up having to recapture it 8 times. That being said, does that mean a "minor" penalty is added every time I try to capture a city? I'm not a warmonger... just stubborn.

A: Quote from the wiki : about warmonging points

These points are only applied if you capture a city that was not founded by you

So as you're not the original owner you will suffer multiple penalties. However the larger the map is, the less the penalty is
(see the wiki for the math calculation).

A: Actually, yes. You will receive a penalty each time a city you did not found is captured by you. It doesn't matter if it was retaken in the last turn. You capture a city = You gain warmonging points.
If you want to avoid being a warmonger, clear out the enemy units first and surround the city as fast as possible in order to protect it from melee units which are the only one able to capture a city.


text:
Q: difference of at least 4 between two numbers In how many ways we can select two numbers from first $10$ natural numbers so that difference between them is at least four?
If we select the numbers from the interval $[1,10]$, will the answer change?  Here $[1,10]$ means the interval containing all real numbers from $1$ to $10$.  I have tried it using geometrical probability.

A: There are ambiguities in your question, as many have pointed out.
I am working out a way for natural #s $1$ thru $10$, you can easily adapt it to whatever you had in mind.
Take $7$ unnumbered balls, and a block of $3$ balls.
Choose any two from the seven unnumbered balls in $\binom72 = 21$ ways,
insert the block of $3$ immediately after the leftmost of the two chosen balls,
now number the balls serially.
All such configurations will satisfy the stipulations, thus ans $=\fbox{21}$


text:
Q: Invalid Directory Name - Your app contains a directory name that is already reserved Just submitted my app for review and was then emailed this error message:
Invalid Directory Name - Your app contains a directory name that is already reserved: 'Frameworks'. You must rename this directory.
Anyone have experience with this?
edit for a little more info: The only thing I have changed recently which may have caused this is to use Cocoapods.  I'm opening and compiling from the xcworkspace.  I do notice that a library called 'QuickDialogs' which I use had a Group called 'Frameworks' which I renamed.

A: Try following steps:

*

*find and open ${YOUR_PROJECT_ROOT}/Pods/Pods-resources.sh

*search ${FRAMEWORKS_FOLDER_PATH} and replace with ${UNLOCALIZED_RESOURCES_FOLDER_PATH}

*clean your project and delete derived Data(organizer-projects)

*achive your application again
I met this problem when I add extra frameworks by cocoapods. App store's response told me that there was a directory named Frameworks, which is reserved.
This folder is created at Copy Pods Resources step in Build Phases,

A: I have found that using ShareKit with Cocoapods was adding a Frameworks to my binary. That's why I substituted:
pod "ShareKit"

with:
pod "ShareKit/Facebook"
pod "ShareKit/Twitter"
pod "ShareKit/GooglePlus"

as I only use these services.
In order to see the folder created go to your binary and see the contents of the archive generated in the Applications folder.
Hope that helps!


text:
Q: MongoDB : Aggregate and Match duplicated values in two fields I have the collection with the following data in in
 {_id: 1, a : 12345, b : [2,3]},
 {_id: 2, a : 666},
 {_id: 3, a : 6, b : [15, 20]},
 {_id: 4, a : 1111, b : [12345, 156]}

I need to match same values that are present in a and b. For the following data the aggregation should return 12345.
I use the next code to get all values from b
 db.collection.aggregate([
        {$unwind: "$b"},
        {$project: {_id: "$b"}}
 ])

But stuck on what to do next and how to compare results with a field.
Ty for your help.


text:
Q: Sci fi story involving a competition between two authors composing stories in a stadium This story was told from one author's perspective. He was the underdog going up against an old pro. The competition was held in a stadium and as each author typed his story it was projected on a screen for the audience. Just as the protagonist feels he's about to lose, the old pro author types "I can't write this shit anymore" and quits.

A: I think this is probably "Prose Bowl" (1979) by Barry N. Malzberg and Bill Pronzini.
A summary of the story on the NESFA recursive fiction database reads:

In the future writers compete as professional athletes. In the prose bowl, two writers vie to see who will complete 10,000 words first (in four quarters of 2,500) while 100,000 paying fans look on. Rex Sackett, the young challenger picks the topic "Mid-Twentieth Century Detective" while the defending champion Leon Culp (the Cranker) gets "Futuristic Love-Adventure."  In the fourth quarter, Culp finally realizes that what they are doing is garbage and he stops writing. Sackett wins but decides that Culp is right and he, too, will retire from the field.

Culp has a breakdown near the end of the tournament:

I finished page thirty-six, pulled it out blindly, and reached for another sheet of paper. Just as I brought it into the platen, Culp's machine unlocked and he hit the keys again.
But not for long.
I CAN'T WRITE THIS SHIT ANY MORE.
Lock into silence. Penalty flag.

You can read the story in the July 1979 issue of The Magazine of Fantasy & Science Fiction at the Internet Archive.


text:
Q: Show Products Special From Date - Optimize Magento Script I am trying to list all products that have a special from date that is within the last 72 hours. The script works fine except over 400 products it times out.
I think I am loading too many collections or not correctly utilizing the ones that are loaded so I really just need some optimization advice please.
Here is the script:
<?php

set_time_limit(0);
require_once 'app/Mage.php';
Mage::app('default');

try
{
    $products = Mage::getModel('catalog/product')->getCollection()
        ->setStoreId(1);
    $products->addAttributeToFilter('status', 1);
    $products->addAttributeToFilter('visibility', 4);
    $products->addAttributeToSelect('*');
    $prodIds=$products->getAllIds();
    $product_count = 0;
    $products_changed = 0;

    //$product = Mage::getModel('catalog/product');

    echo "Price Changes Last 72 Hours

";

    foreach($prodIds as $productId)
    {
        $product_count++;
        //$products->load($productId);

        // load product data
        $product = Mage::getModel('catalog/product')->load($productId);

        $special_price = round($product->getSpecialprice(),2);
        $human_readable_date = $product->getSpecialFromDate();
        $sku = $product->getSku();
        $specialPriceFromDate = strtotime($human_readable_date);
        $time_now = microtime(true);
        $product_link = "http://www.mydomain.com.au/".$product->getUrlPath();
        $date_array = explode( ' ', $human_readable_date);
        $short_date = $date_array[0];

        if (($time_now - $specialPriceFromDate) < 259200)
        {
            $products_changed++;
            echo "SKU: " . '' . $sku . '' . "  Date Changed: " . $short_date . " New Price $" . $special_price . "
";
        }
        //if ($product_count == 400) exit;
    }
}

catch(Exception $e){
    $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    error_log($e->getMessage(), 1, 'me@mydomain.com.au', $headers);
    die($e->getMessage());
}

?>

A: You're first loading a complete collection and then are loading all the products again, one by one. This will result in a huge memory consumption and will be slow.
Additionally you're loading all product attributes (which can be hundreds), but mainly seem to be only interested in just a few of them.
To optimize both issues, I'd recommend to directly filter for only the products of interest:
$iNow = strtotime(date('Y-m-d H:i:s'));
$iFrom = $iNow - (60 * 60 * 24 * 3);
$oProductCollecion = Mage::getModel('catalog/product')
    ->getCollection()
    ->setStoreId(1)
    ->addAttributeToSelect(array('sku', 'special_price', 'url_path'))
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter(
        'special_from_date',
         array('from' => date('Y-m-d H:i:s', $iFrom))
    );

foreach($oProductCollecion as $oProduct) {
    $product_link = "http://www.mydomain.com.au/" . $oProduct->getUrlPath();
    $sku = $oProduct->getSku();
    $short_date = $oProduct->getSpecialFromDate();
    $special_price = round($oProduct->getSpecialPrice(), 2);
    echo "SKU: " . '' . $sku . '' . "  Date Changed: " . $short_date . " New Price $" . $special_price . "
";
}


text:
Q: python function for creating pairs based on ordered items in list dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]

Using python, I am trying to create a conversation pair dataset where each pair in the set will have speaker 1 and the subsequent response from speaker 2.
With the example dat above, I would need to iterate through the list and 1) merge sentences from the same speaker if they are subsequent and 2) create the pair as below example;
Output:
((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))

How do I write a function that takes in sequential data like this to create conversation pairs?

A: conv = []
ls, lm = dat[0]
for s, m in dat[1:]:
    if s == ls:
        lm += ' ' + m
    else:
        conv.append((ls, lm))
        ls, lm = s, m
else:
    conv.append((ls, lm))
    if conv[-1][0] == 1:
        conv.append((2, None))
output = tuple([(conv[i], conv[i+1]) for i in range(0,len(conv) - 1, 2)])

Output:
[((1, 'hello how are you?'), (2, 'I am doing well, thanks!')), ((1, 'Do anything fun this weekend?'), (2, 'I mostly slept but I also played games')), ((1, 'That sounds fun'), (2, None))]

use this snippet of code, hope this solves your purpose

A: def combine_speaker_lines(id_part_iter):
    conversation = []
    last_speaker, part = id_part_iter[0]
    for speaker, fragment in id_part_iter[1:]:
        if speaker != last_speaker:
            conversation.append((last_speaker, part.lstrip()))
            part = ''
        part += ' ' + fragment
        last_speaker = speaker
    conversation.append((speaker, part.lstrip()))
    return conversation
    return conversation


text:
Q: how to compare two array collection using action script how to compare two arraycollection
 collectionArray1 = ({first: 'Dave', last: 'Matthews'},...........n values
 collectionArray = ({first: 'Dave', last: 'Matthews'},...........n values

how to compare..if equal just alert nochange if not alert chaged

A: If you just want to know if they are different from each other, meaning by length, order or individual items, you can do the following, which first checks to see if the lengths are different, then checks to see if the individual elements are different.  This isn't terribly reusable, it's left as an exercise for the reader to split this apart into cleaner chunks :)
public function foo(coll1:ArrayCollection, coll2:ArrayCollection):void {
    if (coll1.length == coll2.length) {
        for (var i:int = 0; i < coll1.length; i++) {
            if (coll1[i].first != coll2[i].first || coll1[i].last != coll2[i].last) {
                Alert.show("Different");
                return;
            }
        }
    }

    Alert.show("Same");
}

A: /* elements need to implement valueOf
public function valueOf():Object{}
*/
public static function equalsByValueOf(
    first:ArrayCollection,
    seconde:ArrayCollection):Boolean{

    if((first==null) != (seconde==null) ){
        return false;
    }else if(!first && !seconde){
        return false;
    }

    if(first.length!=seconde.length){
        return false;
    }

    var commonLength:int = first.length;
    var dictionary:Dictionary = new Dictionary();
    for(var i:int=0;i<commonLength;i++){
        var item1:Object = first.getItemAt(i);
        var item2:Object = seconde.getItemAt(i);
        dictionary[item1.valueOf()]=i;
        dictionary[item2.valueOf()]=i;
    }

    var count:int = 0;
    for (var key:Object in dictionary)
    {
        count++;
    }
    return count==commonLength;
}

/* valueOf sample
 * something like javaObject.hashCode()
 * use non changing fields(recommended)
 */

public function valueOf():Object{
 return "_"+nonChangeField1+"_"+nonChangeField2+"...";
}

A: I was going to say this.
if(collectionArray === collectionArray1)

But that wont work (not triple = signs). As === is used to see classes.

*

*I would write a function called check if object exists in array.

*Create an array to hold elements that are not found. eg notFound

*in Collection1 go through all the element and see if they exist in Collection2, if an element does not exist, add it to the notFound array. Use the function your created in step1

*Now check Collection2, if an element is not found add it to the notFound array.

*There is no 5.

A: Dude, use the mx.utils.ObjectUtil... the creators of actionscript have already thought about this.
ObjectUtil.compare(collection1, collection2) == 0;


text:
Q: FFmpeg libx264 Gamma Issue I'm aware that the gamma issue exists for both Quicktime's native H264 format as well as ffmpeg's equivalent libx264 format. My question is has anyone figured out a fix for it that's more programmatically automated than doing the manual Straight Alpha fix in Quicktime?
Either a command-line argument to perform the Straight Alpha and Save fix in QT or perhaps the magical command in ffmpeg's libx264 presets would work for me. Unfortunately, all I've read so far has seemed to indicate that I'm out of luck. Hopefully I'm wrong. Thanks!


text:
Q: How to store CloudKit zone change tokens? So I currently use the following methods to get and set zone change tokens:
private func zoneChangeToken(for zoneID: CKRecordZoneID) -> CKServerChangeToken? {
    let cacheKey = self.name(for: self.database) + "." + zoneID.zoneName + "." + zoneID.ownerName
    if let data = UserDefaults.standard.data(forKey: cacheKey) {
        return NSKeyedUnarchiver.unarchiveObject(with: data) as? CKServerChangeToken
    } else {
        return nil
    }
}

private func setZoneChangeToken(changeToken: CKServerChangeToken?, for zoneID: CKRecordZoneID) {
    let cacheKey = self.name(for: self.database) + "." + zoneID.zoneName + "." + zoneID.ownerName

    if changeToken == nil {
        UserDefaults.standard.removeObject(forKey: cacheKey)
    } else {
        let data = NSKeyedArchiver.archivedData(withRootObject: changeToken!)
        UserDefaults.standard.set(data, forKey: cacheKey)
    }
}

I try to uniquely target the zone by creating a path from database to zone. However since the shared database might have multiple zones with the same zone name, I appended the zone owner name.
The question is, is this a proper way to store the zone change tokens or is there a better, more efficient, way?


text:
Q: How to solve $\int\frac{dx}{\sqrt[3]{1+x^3}}$? I have:
$$\int\frac{dx}{\sqrt[3]{1+x^3}}$$
It seems easy but neither $t^3=1+x^3$ nor $t = \sqrt[3]{1+x^3}$ nor $t = x^3$ made integral easier. What is the way to solve it then?

A: This integral in fact has elementary antiderivative.
Let $x=1/u$, $dx=-du/u^2 $, we have
$$\int \frac{1}{\sqrt[3]{1+x^3}}dx = -\int\frac{1}{u^2\sqrt[3]{1+\frac{1}{u^3}}} du = -\int\frac{u^2}{u^3 \sqrt[3]{1+u^3}} du = -\frac{1}{3}\int\frac{d(u^3)}{u^3 \sqrt[3]{1+u^3}}$$
Letting $1+u^3 = t^3$, the original integral is transformed into
$$-\int\frac{t}{t^3-1} dt$$
from which I believe you can continue.


text:
Q: Can we use for loop with switch statement..? I am trying to iterate for loop by using switch statement. I want to print particular data from that switch statement.
I am taking data in one array, like 5,6 and i am iterating loop with this array length by switch statement. it should print 5 and 6th values only from switch statement. But it's not working.
it's giving below out put::::
Concatination of String value
Print 11
Concatination of String value
Print 1
public class String_Concat {

public void concat(int n){
    System.out.println("Concatination of String value");

     switch (n)
        {
            case 1 :
                System.out.println("Print 1");
                break;
            case 2 :
                System.out.println("Print 2");
                break;
            case 3 :
                System.out.println("Print 3");
                break;
            case 4 :
                System.out.println("Print 4");
                break;
            case 5 :
                System.out.println("Print 5");
                break;
            case 6 :
                System.out.println("Print 6");
                break;
            case 7 :
                System.out.println("Print 7");
                break;
            case 8 :
                System.out.println("Print 8");
                break;
            case 9 :
                System.out.println("Print 9");
                break;
            case 10 :
                System.out.println("Print 10");
                break;

            default :
                System.out.println("Print 11");

        }
}

public static void main(String[] rags){
    String[] nums={"5","6"};
    String_Concat st=new String_Concat();
    for(int i=0;i<nums.length;i++){
        st.concat(i);
    }
}
}

A: Where you have it wrong
Your issue is in the below:
for(int i=0;i<nums.length;i++){
    st.concat(i);
}

You're passing in the counter as the argument, i.e. st.concat(0), which then goes into the default: option in your switch statement, printing out a value of 11. In the second iteration you are passing in st.concat(1) which prints out a value of 1.
How to Fix
You should instead pass in nums[i], which returns you a 5 in the first iteration.
Also, because your concat method accepts an int, you need to do a quick conversion:
st.concat(Integer.parseInt(nums[i]));
To make it simpler, just declare and populate nums as an array of int instead:
int[] nums= { 5, 6 };

A: you should change the loop like this:
for(int i=0;i<nums.length;i++){
            st.concat(Integer.valueOf(nums[i]));
        }

In your code you are calling this:
st.concat(0);
st.concat(1);

so the output is right.

A: Let us first understand what's going on in this code . In the first iteration the value of i is 0, with which it goes to concat method and it tries to match against the switch cases but it finds none (as the cases are from 1 to 9) and goes for default case and hence prints print 11 . After that in second iteration the value of i becomes 1 and it again goes in concat method , where it finds a exact match with case 1 and hence prints print 1 .
Now to get what you expect from this code , you need to pass the value of array elements in each iteration of for loop. And also you need to convert the values of nums from string to integer as your method expects int datatype.

st.concat(Integer.parseInt(nums[i]))


text:
Q: condense pyqtproperties I'm writing a script in Python and have a bit of a problem:
class LightDMUser(QObject):
  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

  @pyqtProperty(QVariant)
  def background(self):      return self.user.get_background()

  @pyqtProperty(QVariant)
  def display_name(self):    return self.user.get_display_name()

  @pyqtProperty(QVariant)
  def has_messages(self):    return self.user.get_has_messages()

  @pyqtProperty(QVariant)
  def home_directory(self):  return self.user.get_home_directory()

  @pyqtProperty(QVariant)
  def image(self):           return self.user.get_image()

  @pyqtProperty(QVariant)
  def language(self):        return self.user.get_language()

  @pyqtProperty(QVariant)
  def layout(self):          return self.user.get_layout()

  @pyqtProperty(QVariant)
  def layouts(self):         return self.user.get_layouts()

  @pyqtProperty(QVariant)
  def logged_in(self):       return self.user.get_logged_in()

  @pyqtProperty(QVariant)
  def name(self):            return self.user.get_name()

  @pyqtProperty(QVariant)
  def real_name(self):       return self.user.get_real_name()

  @pyqtProperty(QVariant)
  def session(self):         return self.user.get_session()

As you can see, this code is horribly redundant. I tried condensing it like this:
class LightDMUser(QObject):
  attributes = ['background', 'display_name', 'has_messages', 'home_directory', 'image', 'language', 'layout', 'layouts', 'logged_in', 'name', 'real_name', 'session']

  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

    for attribute in self.attributes:
      setattr(self, attribute, pyqtProperty(QVariant, getattr(self.user, 'get_' + attribute)))

PyQt4, however, expects the class methods to be present for the class itself, not an instance. Moving the setattr code out of the __init__ block didn't work either because self wasn't defined for the class, so I don't really know what to do.
Can anyone see a way to condense this code?

A: There are number of ways to do it: class decorator, metaclass, Mixin.
Common helper function:
def set_pyqtproperties(klass, properties, proxy='user'):
    def make_prop(prop):
        def property_(self):
            return getattr(getattr(self, proxy), 'get_' + prop)
        property_.__name__ = prop
        return property_

    if isinstance(properties, basestring):
       properties = properties.split()
    for prop in properties:
         setattr(klass, prop, pyqtProperty(QVariant, make_prop(prop)))

Class decorator
def set_properties(properties):
    def decorator(klass):
        set_pyqtproperties(klass, properties)
        return klass
    return decorator

Usage

@set_properties("display background")
class LightDMUser(QObject): pass

if there is no support for class decorators then you could try:
class LightDMUser(QObject):
    pass
LightDMUser = set_properties("display background")(LightDMUser)

Metaclass
def set_properties_meta(properties):
    def meta(name, bases, attrs):
        cls = type(name, bases, attrs)
        set_pyqtproperties(cls, properties)
        return cls
    return meta

Usage

class LightDMUser(QObject):
    __metaclass__ =  set_properties_meta("display background")

Note: you could reuse the same metaclass if you set the list of properties as a class attribute:
def MetaClass(name, bases, attrs):
    cls = type(name, bases, attrs)
    set_pyqtproperties(cls, attrs.get('properties', ''))
    return cls

class LightDMUser(QObject):
    properties = "display background"
    __metaclass__ = MetaClass

Also you could manipulate attrs directly: attrs[name] = value before calling type() instead of setattr(cls, name, value).
The above assumes that QObject.__class__ is type.
Mixin
def properties_mixin(classname, properties):
    #note: create a new class by whatever means necessary
    # e.g., even using exec() as namedtuple does
    # http://hg.python.org/cpython/file/3.2/Lib/collections.py#l235

    # reuse class decorator here
    return set_properties(properties)(type(classname, (), {}))

Usage

PropertiesMixin = properties_mixin('PropertiesMixin', 'display background')
class LightDMUser(PropertiesMixin, QObject): pass

I haven't tried any of it. The code is here to show the amount and the kind of code it might require to implement the feature.

A: You could attach these methods from еру outside of the class definition:
class LightDMUser(QObject):

  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

The simplest way is to create a closure for each property, override its __name__ (just for case if @pyqtProperty needs it) and to bind it to the class:
for attribute in [
        'background',
        'display_name',
        'has_messages',
        'home_directory',
        'image',
        'language',
        'layout',
        'layouts',
        'logged_in',
        'name',
        'real_name',
        'session'
      ]:

  def delegating(self):
    return getattr(self.user, 'get_' + attribute)()

  delegating.__name__ = attribute
  delegating = pyqtProperty(QVariant)(delegating)

  setattr(LightDMUser, attribute, delegating)

A: I'm pretty sure this can work if you move your loop out of the class, and create a closure to hold each of the attribute names:
class LightDMUser(QObject):
    attributes = ['background', 'display_name', 'has_messages',
                  'home_directory', 'image', 'language', 'layout',
                  'layouts', 'logged_in', 'name', 'real_name', 'session']

    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user

for attribute in LightDMUser.attributes:
    closure = lambda self, attribute=attribute : getattr(self.user,
                                                         'get_' + attribute)()
    setattr(LightDMUser, attribute, pyqtProperty(QVariant, closure))

I've not tested this with the actual QT based classes you're dealing with, but a simpler version using regular Python property instances worked perfectly. I'm also not sure this is a good idea, since it would be pretty hard to figure out what's going on if you are not already familiar with it.

A: I'm not convinced I like this, but it's a possible option, isn't too difficult to understand, and removes the need for getattr's... The following can be used a bit like a macro - but might need tweaking... (eg. take funcs from a class definition that startwith get, or from an existing object etc...) One could also add a repr in there to describe it's a supporting class for interfacing with properties to user objects or whatever...)
def get_properties(name, funcs):
    get_text = """
class {name}(QObject):
""".format(name=name)
    for func in funcs:
        get_text += (
              "\n\t@pyqtProperty(QVariant)\n"
              "\tdef {func}(self): return self.user.get_{func}()\n"
              ).format(func=func)

    print get_text # this should be exec...

>>> get_properties('UserProperties', ['display', 'background'])

class UserProperties(QObject):

    @pyqtProperty(QVariant)
    def display(self): return self.user.get_display()

    @pyqtProperty(QVariant)
    def background(self): return self.user.get_background()

When that exec'd, you get the ability to write your main class as:
class LightDMUser(QObject, UserProperties):
    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user

A: I tested the solution below, for Python 3.  It uses the metaclass keyword
# A bit of scaffolding

def pyqtProperty(cls, method):
    return method

class QObject:
    pass

class QVariant:
    pass

class User:
    def __init__(self, name="No Name"):
        self.name = name
    def get_background(self):
        return self.name
    def get_display_name(self):
        return self.name
    def get_has_messages(self):
        return self.name
    def get_home_directory(self):
        return self.name
    def get_image(self):
        return self.name
    def get_language(self):
        return self.name
    def get_layout(self):
        return self.name
    def get_layouts(self):
        return self.name
    def get_logged_in(self):
        return self.name
    def get_name(self):
        return self.name
    def get_real_name(self):
        return self.name
    def get_session(self):
        return self.name

# The Meta Class
class MetaLightDMUser(type):
    @classmethod
    def __prepare__(cls, name, baseClasses):
        classdict = {}
        for attribute in ['background', 'display_name', 'has_messages', 'home_directory', 'image', 'language', 'layout', 'layouts', 'logged_in', 'name', 'real_name', 'session']:
            classdict[attribute] = eval("lambda self: pyqtProperty(QVariant, getattr(self.user, 'get_" + attribute +"'))()")
        return classdict

    def __new__(cls, name, baseClasses, classdict):
        return type.__new__(cls, name, baseClasses, classdict)

# The class itself
class LightDMUser(QObject, metaclass = MetaLightDMUser):
    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user

Alternatively I could have created the classdict entries like this
classdict[attribute] = lambda self, attr=attribute: pyqtProperty(QVariant, getattr(self.user, 'get_' + attr))()
but that presents an attr argument.  With eval() we hard-core this argument
As well we could have used functools.partial:
classdict[attribute] = functools.partial(lambda self, attr: pyqtProperty(QVariant, getattr(self.user, 'get_' + attr))(), attr=attribute)
but then the call must be u.method(u).  It cannot be u.method()
The call LightDMUser.method(u) works with all 3 implementations
Regards

A: It's tricky to cut down on boilerplate for pyqtProperty using a metaclass or class decorator, but this is something we just got to work here that will help as a starting point.  The downside, I suppose, is that you no longer get to use the @decorator syntax, but it seems like rolling this into a single line of code is more desirable in this situation.
You can set this up to call through to your user object instead of just self, or you could implement custom getattr behavior for LightDMUser that will call through to self.user automatically.
from PyQt4.QtCore import pyqtProperty
from PyQt4.QtGui import QWidget, QColor
from functools import partial

def pyqtPropertyInit(name, default):
    def _getattrDefault(default, self, attrName):
        try:
            value = getattr(self, attrName)
        except AttributeError:
            setattr(self, attrName, default)
            return default
        return value
    ga = partial(_getattrDefault, default)
    return pyqtProperty(
        default.__class__,
        fget=(lambda s: ga(s, name)),
        fset=(lambda s, v: setattr(s, name, v)),
    )

class TestClass(QWidget):
    def __init__(self, *args, **kwargs):
        super(TestClass, self).__init__(*args, **kwargs)

    stdoutColor = pyqtPropertyInit('_stdoutColor', QColor(0, 0, 255))
    pyForegroundColor = pyqtPropertyInit('_pyForegroundColor', QColor(0, 0, 255))


text:
Q: setInterval is not working in YUI I am trying to use SetInterval and clearInterval in YUI
The code is written so it will create element every second and on mouse hover of div it should stop creating element.
http://jsbin.com/awadek/5
Please let me know what is wrong with my code?

A: You should pass an anonymous function as a handler to "mouseover".  Otherwise, Javascript will attempt to evaluate and call the return from clearInterval (in this case, an integer!).  The following code will work:
 YUI().use("console", "console-filters", "substitute", "node-event-simulate",
   function(Y) {
     console.log("YUI is ready");

     var doSomething = function(e) {
       Y.one("#seconds").append("
I am number four
");
     };

     IntervalId = setInterval(doSomething, 1000);
     //Notice the anonymous function below:
     Y.one("#clearInt").on('mouseover', function() { clearInterval( IntervalId ) });
 });

Here is your JSBin, ftfy.  Enjoy!


text:
Q: The identifier id is missing for a query of PrManagerBundle\Entity\eb_user i'm trying to delete an object by the id from my database using
<button class="btn btn-danger" (click)="removeUser()"> Delete</button></td> in the frontend but the link does not work. I get an error:
The identifier id is missing for a query of PrManagerBundle\Entity\eb_user.

here is my entity:

namespace PrManagerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * eb_user
 *
 * @ORM\Table(name="eb_user")
 * @ORM\Entity(repositoryClass="PrManagerBundle\Repository\eb_userRepository")
 */
class eb_user
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

/**
 * @var string
 *
 * @ORM\Column(name="nom", type="string", length=255)
 */
private $nom;

/**
 * @var string
 *
 * @ORM\Column(name="prenom", type="string", length=255)
 */
private $prenom;

/**
 * @var int
 *
 * @ORM\Column(name="tel", type="string", nullable = true)
 */
private $tel;

/**
 * @var string
 *
 * @ORM\Column(name="mail", type="string", length=255, nullable = true)
 */
private $mail;

/**
 * @var string
 *
 * @ORM\Column(name="domaine", type="string", length=255, nullable = true)
 */
private $domaine;

/**
 * @ORM\ManyToOne(targetEntity="PrManagerBundle\Entity\eb_role", inversedBy="eb_user")
 */
private $x_eb_role;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set nom
 *
 * @param string $nom
 *
 * @return eb_user
 */
public function setNom($nom)
{
    $this->nom = $nom;

    return $this;
}

/**
 * Get nom
 *
 * @return string
 */
public function getNom()
{
    return $this->nom;
}

/**
 * Set prenom
 *
 * @param string $prenom
 *
 * @return eb_user
 */
public function setPrenom($prenom)
{
    $this->prenom = $prenom;

    return $this;
}

/**
 * Get prenom
 *
 * @return string
 */
public function getPrenom()
{
    return $this->prenom;
}

/**
 * Set tel
 *
 * @param integer $tel
 *
 * @return eb_user
 */
public function setTel($tel)
{
    $this->tel = $tel;

    return $this;
}

/**
 * Get tel
 *
 * @return int
 */
public function getTel()
{
    return $this->tel;
}

/**
 * Set mail
 *
 * @param string $mail
 *
 * @return eb_user
 */
public function setMail($mail)
{
    $this->mail = $mail;

    return $this;
}

/**
 * Get mail
 *
 * @return string
 */
public function getMail()
{
    return $this->mail;
}

/**
 * Set domaine
 *
 * @param string $domaine
 *
 * @return eb_user
 */
public function setDomaine($domaine)
{
    $this->domaine = $domaine;

    return $this;
}

/**
 * Get domaine
 *
 * @return string
 */
public function getDomaine()
{
    return $this->domaine;
}
/**
 * Set xEbRole
 *
 * @param \PrManagerBundle\Entity\eb_role $xEbRole
 *
 * @return eb_user
 */
public function setXEbRole(\PrManagerBundle\Entity\eb_role $xEbRole = null)
{
    $this->x_eb_role = $xEbRole;

    return $this;
}

/**
 * Get xEbRole
 *
 * @return \PrManagerBundle\Entity\eb_role
 */
public function getXEbRole()
{
    return $this->x_eb_role;
}

}
the controller:
public function removeAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $userInfo = json_decode( $request->request->get("user") );
        $eb_user = $em->getRepository('PrManagerBundle:eb_user')->find($request->request->get('id'));
        $em->remove($eb_user);
        $em->flush();
        $em->clear();
        return $this->returnJsonResponse($eb_user);

        /* $repository = $this->getDoctrine()->getRepository(eb_user::class);
        $editUser = $repository->find($id);
        return $this->returnJsonResponse($editUser);*/
    }

and the routing is here:
pr_manager_remove:
    path:     /user/remove/{id}
    defaults: { _controller: PrManagerBundle:User:remove }
Actually the id is not found. I expect the link work correctly

A: You are passing the userId as a route parameter. That's why it's missing from the request.
The id should be passed as an argument to the the function PrManagerBundle:User:remove.
/**
 * @Route("/user/remove/{id}", name="pr_manager_remove")
 */
public function remove($id)
{
    ...
    $eb_user = $em->getRepository('PrManagerBundle:eb_user')->find($id);
    ...
}


text:
Q: Rails 2.3.5 - ".find" function doesn't work with (:condition =>"date") option What I want to do is finding specific records that have been used over the last 60 days.
I am using Oracle (9i),
Rails v: 2.3.5,
Ruby v: 1.8.7
My Code to define the date interval is:
date =(((Time.now - 60.days).strftime("%d-%b-%y"))...(Time.now.strftime("%d-%b-%y")))

and here is how I use it:
conditions = {}
conditions[:start_date] = date
conditions[:account_no] = account_number

results = MyModel.find(:all, :conditions => conditions)

to see what is selected, I basicly do:
results.each {|r|
  if (!(r.column_name.nil?))
     #do something here
  end
}

Result:
Code is working but the "results" is empty
However, when I copy and paste the query that generated by the "MyModel.find..." to sqlDeveloper, I can definitly see what I want.
What should be the reason that I can't get the same results with SQL Developer, Although I use the same query that is generated by above code

A: The following should work given start_date is a Date
date =((DateTime.now - 60)...(DateTime.now))
conditions = {}
conditions[:start_date] = date
conditions[:account_no] = account_number

results = MyModel.find(:all, :conditions => conditions)

This will cause date to be a range of Dates as opposed to a range of strings.
Right now if you run date.to_a it returns an empty array because it is an improper range.
If you run the above with date.to_a it will return an array of dates back 60 days exclusive of today's date. Which will create a proper IN statement in the generated SQL


text:
Q: How to skip verification process for Google API Projects that works only in the sandbox mode? Google started the OAuth developer verification process a few months back which forces the developers having OAuth applications to apply for verifications if they don't want their users to see a warning screen and to have an unlimited number of users using the OAuth flow.
I'm facing a problem due to this verification process when I have to use the projects in a local environment. There is no way I can verify the apps for local environments since the policies and T&Cs cannot be hosted.
Q1. Is there any way to skip the verification process and sandbox the OAuth application?
Q2. What is the exact limit for the accounts? (Since I use 5-10 Gmail accounts, but do multiple signups per day from those accounts and I still hit the limit quite often)

A:
Q1. Is there any way to skip the verification process and sandbox the OAuth application?

If you check the side of the consent screen it answers some of your questions.

you can learn more here

Q2. What is the exact limit for the accounts? (Since I use 5-10 Gmail accounts, but do multiple signups per day from those accounts and I still hit the limit quite often)

If you add these accounts as users on the project in the developer console they should be able to use it while you are testing.


text:
Q: ng-repeat does not work well I'm new to angularjs, and trying this, but not sure why is it not working. I used quite a number of solutions found here, but none works.
Here is my array that is assigned to $scope.data_params

Here is my code in HTML:-

              {{item.name}}

Code in JS:-
    $scope.data_params.push(result_params.dealers);
   console.log($scope.data_params);

Any idea what went wrong?

A: It seems that you need to access to the 0 element,
Try:

              {{item.name}}

Hope it helps,

A: From the looks of it your data_params is a 1 length array that houses a 10 length array with the objects you want. You need to repeat over the 10 length array, not the 1 length.

      {{item.name}}

A: It looks like your data is an array that contains an array of your items. Try ng-repeating on the inner-array:

      {{item.name}}

A: You need to track by $index:

          {{item.name}}


text:
Q: passing SDL windows by reference/address I don't want to use global variables for the SDL_Window and SDL_Renderer and any textures.
So i declared the window, renderer and texture at the top of main() and passed them to my init() function:
   bool init(SDL_Window* &window, SDL_Renderer* &renderer, const int height, const int width)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        std::cout << "SDL_Init() failed SDL error: " << SDL_GetError() << '\n';
        return false;
    }
    else
    {
        window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0);
        if (window == NULL)
        {
            std::cout << "SDL_CreateWindow() failed SDL error: " << SDL_GetError() << '\n';
            return false;
        }
        else
        {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL)
            {
                std::cout << "SDL_CreateRenderer() failed SDL error: " << SDL_GetError() << '\n';
            }
        }
    }

    return true;

}

the caller in main():
if (!init(window, renderer, WINDOW_HEIGHT, WINDOW_WIDTH))
{
    std::cout << "init() failed SDL error: " << SDL_GetError() << '\n';
}

declarations at the top of main():
    SDL_Texture* texture{};
    SDL_Window* window{};
    SDL_Renderer* renderer{};
    int WINDOW_HEIGHT = 480;
    int WINDOW_WIDTH = 640;

as you can see in my init() function, it takes the window and renderer as arguments and puts them into one of these: SDL_Window* &window;
initially i tried putting them in : SDL_Window* window;
however this would result in the renderer and window being null when the program returned to main().
I don't understand why my initial method did not work but using SDL_Window* &window; does work
As far as i understand window is a pointer (a variable which holds an address) to a SDL struct called SDL_Window and therefore when i pass window to parameter SDL_Window* window, it should give the parameter the address to my window i declared in main() and therefore any changes made to the window in init() should also be made to it in main(), however this was not true and SDL_Window* &window as parameter ended up having the desired effect.
If possible could someone explain why this is?

A: I think due do this being the first complex library I've used i became slightly confused about the nature of how and when objects were being created. Thanks to HolyBlackCat you made it obvious to me.
SDL_CreateWindow gives my window pointer an address which points to the created window, what i am passing in to init() is a default initialised pointer. for some reason i thought that declaring a pointer to an SDL_Window was also creating a space in memory for a window, its obvious due to the way that pointers work that this makes no sense


text:
Q: Structuremap all instances of abstract Using Net 4.5.1 and StructureMap 3.1.4
I have services that extending an abstract class:
 public abstract class Charting<T> {

   protected readonly String baseConfigurationString;

   public Charting(String baseConfigurationString)
   {
      this.baseConfigurationString = baseConfigurationString;
   }

   ...
 }

For every concrete service I want to set the baseConfigurationString.  Right now I am doing it individually per service:
 public class MyRegistry : Registry
 {
    public MyRegistry()
    {
        Profile("Development", x => {
            ForConcreteType<AveragePartySizeChart>().Configure.Ctor<String>("baseConfigurationString").Is(MyDbConfiguration.getBaseConnectionString());

            ...next service....about 6 total
        });
    }
 }

Is there anyway to do this generally acting against the abstract class despite it having a generic qualifier?

A: This does not solve your abstract constructor argument setting via Profile problem but I would like to suggest that you avoid taking dependencies on primitive types like System.String and use an abstraction instead.
You could have an type IDatabaseSettings which gets the connection settings you desire for either environment variables or application settings.
public interface IDatabaseSettings
{
  string DbConnectionString { get; set; }
}

public class DatabaseSettings : IDatabaseSettings
{
  public string DbConnectionString { get; set; }
}

public class DatabaseRegistry : Registry
{
  public DatabaseRegistry()
  {
    For<IDatabaseSettings>().Use(c =>
    {
        var setting = c.GetInstance<DatabaseSettings>();

        setting.DbConnectionString =
            System.Configuration.ConfigurationManager.AppSettings["DatabaseSettings.DBConnectionString"];

        return setting;
    });
  }
}

Important: Your project will need to reference System.Configuration.
If you have a lot of settings you may want to conventionalize this pattern. We use the SettingsProvider out of FubuCore to make this a breeze. You simply have objects that end in Settings which get their properties automatically populated out of application settings. Chad Myers has a nice blog post on it.

A: My suggestion, and what we did with StructureMap for configuration within FubuMVC, is to create a class something like:
public class ConnectionSettings
{
    public string Connection {get;set;}
}

and resolve that through StructureMap as a singleton. Then in any class that needs the connection string, just do:
public abstract class DatabaseConnectionUser
{
    public DatabaseConnectionUser(ConnectionSettings settings){}
}

Autowiring will connect your ConnectionSettings object to all the class objects that take in
that object in their constructor function.
You could try using a custom IPluginGraphConfiguration class in StructureMap 3 to set the ctor argument explicitly on all Instance's that build a subclass, but I think that would be more work.


text:
Q: How to link Wordpress heartbeat to ajax form I have a form that $_POSTs an input value, and user's ID that saves the data to the database:
// frontend form
<form id="form">
    <input type="radio" name="location" id="name1" value="1">
    Label 1

    <input type="radio" name="location" id="name2" value="2">
    Label 2

    <input type="radio" name="location" id="name3" value="3">
    Label 3

    <input type="hidden" name="userid" value="{userid}">
</form>

// footer script

// validation snippet
<?php
    $location = isset( $_POST['location'] ) ? $_POST['location'] : '';
    $userID   = isset( $_POST['userid']   ) ? $_POST['userid']   : '';
    update_user_meta( $userID, 'location_current',  $location );
?>

When the users sets the radio location from their desktop, it send the form to the server, and saves it.
Each user also has a display (tablet) that has no input but echoes out the location value.
I currently have the tablet refreshing every 5 minutes, but wanted it to be more of a push with WP heartbeat.
I tried using this example: https://gist.github.com/strangerstudios/5888123
But wasnt sure how to have the value of the data['client'] = 'marco'; be data['client'] = '<?= $_POST['location']; ?>'; each time as it is printed once and not refreshed once the page is loaded or the location changed.

A: Saving data
Based on Heartbeat API, you can add custom data to the sent heartbeat on heartbeat-send event in js. This would be used instead of the ajax function you have in your code example.
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
  // Grab the required form data
  data.location = jQuery('input[name="location"]:checked').val();
  data.userid = jQuery('input[name="userid"]').val();
});

You can then use the data in PHP with hearbeat_recieved filter. There's also the heartbeat_nopriv_received filter for no-privilege environments.
add_filter( 'heartbeat_received', 'myplugin_save_location_on_heartbeat', 10, 2 );
function myplugin_save_location_on_heartbeat( $response, $data ) {
  // data required
  if ( empty( $data['location'] ) || empty( $data['userid'] ) ) {
    return $response;
  }
  // validate
  if ( ! is_numeric( $data['location'] ) || ! is_numeric( $data['userid'] ) ) {
    return $response;
  }
  // sanitize
  $location = absint( $data['location'] );
  $userID = absint( $data['userid'] );
  // update
  update_user_meta( $userID, 'location_current',  $location );
  // optional response
  $send_data_back = true;
  if ( $send_data_back ) {
    $response['location'] = $location;
    $response['userid'] = $userID;
  }
  // send response
  return $response;
}

You can access the data (response from hearbeat_recieved) again on heartbeat-tick event in js,
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
  // Check for our data, and use it.
  if ( ! data.location || ! data.userid ) {
    return;
  }
  // use the response as needed
  console.log("location: " + data.location);
  console.log("user: " + data.userid);
});

Get data
With couple of tweaks you can get just the location data instead of saving it.
First send user id with heartbeat-send in js,
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
  data.userid = jQuery('input[name="userid"]').val();
});

Then respond with current location user meta in PHP on hearbeat_recieved,
add_filter( 'heartbeat_received', 'myplugin_get_location_on_heartbeat', 10, 2 );
function myplugin_get_location_on_heartbeat( $response, $data ) {
  // data required
  if ( empty( $data['userid'] ) ) {
    return $response;
  }
  // validate
  if ( ! is_numeric( $data['userid'] ) ) {
    return $response;
  }
  // sanitize
  $userID = absint( $data['userid'] );
  // update
  $location = get_user_meta( $userID, 'location_current',  true );
  // send response
  return $response['location'] = $location;
}

EDIT 1: I think you could also use get_current_user_id() inside the php response function to get the user id, if you don't want to or can't send it in js on heartbeat-send event.
Last, update your view with the recieved data on heartbeat-tick in js,
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
  // Check for our data, and use it.
  if ( ! data.location ) {
    return;
  }
  // if using radio buttons
  jQuery('input[name="location"][value='"+data.location+"']').prop('checked', true);
  // if you want to show result in somewhere else
  jQuery('#location-output-element').text(data.location);
});

I hope this helps and answers your question.

A: To send value using HTTP methods, the page must submit data. Only page refresh will not work. Your page must send a post request with the data location and you are using ajax to send form data.
In the API data['client'] = 'marco'; you can use your own data object send from your ajax request.
data['client'] = your formdata;

or you can use your PHP code same as you mentioned above:
data['client'] = '<?php echo $_POST['location']; ?>'; // make sure you validate data first.

If this doesn't help, please show the full implementation of API and usage of your ajax data.


text:
Q: sql selecting minimum date relative to another column's group I have some data that looks like this, I am trying to find the minimum corresponding next_start_date with each unique cancel_date.

group_id
individual_id
race
color_of_eye
cancel_date
next_start_date

1
001
A
@@
2017-11-06
2018-04-16

2
002
B
$$
2017-06-26
2017-06-26

2
002
B
$$
2017-06-26
2018-01-23

2
002
B
$$
2017-06-26
2019-02-16

3
002
C
<<
2017-12-28
2018-01-23

3
002
C
<<
2017-12-28
2019-02-16

4
003
B
**
2010-01-26
2011-01-23

4
003
B
**
2010-01-26
2019-02-16

5
004
K
@@
2017-12-28
2018-01-23

Desired output:

group_id
individual_id
race
color_of_eye
cancel_date
next_start_date

1
001
A
@@
2017-11-06
2018-04-16

2
002
B
$$
2017-06-26
2017-06-26

3
002
C
<<
2017-12-28
2018-01-23

4
003
B
**
2010-01-26
2011-01-23

5
004
K
@@
2017-12-28
2018-01-23

I tried using a window function with
SELECT
      *,
      MIN(next_start_date) OVER (PARTITION BY individual_id, cancel_date) AS minimum_next_start_date
FROM table
ORDER BY
    individual_id, cancel_date, minimum_next_start_date

The results looks like this

group_id
individual_id
race
color_of_eye
cancel_date
minimum_next_start_date

1
001
A
@@
2017-11-06
2018-04-16

2
002
B
$$
2017-06-26
2017-06-26

2
002
B
$$
2017-06-26
2017-06-26

2
002
B
$$
2017-06-26
2017-06-26

3
002
C
<<
2017-12-28
2018-01-23

3
002
C
<<
2017-12-28
2018-01-23

4
003
B
**
2010-01-26
2011-01-23

4
003
B
**
2010-01-26
2011-01-23

5
004
K
@@
2017-12-28
2018-01-23

Should I do a Min for minimum_next_start_date, and group by every other column there is? Please help.

A: From what I can tell, you want aggregation:
select group_id, individual_id, race, color_of_eye, cancel_date,
       min(next_start_date)
from t
group by group_id, individual_id, race, color_of_eye, cancel_date;

In Postgres, distinct on often has better performance.  If the group by defines the groups without the other columns, then you can use:
select distinct on (group_id, individual_id) t.*
from t
order by group_id, individual_id, next_start_date;


text:
Q: How to fix ./configure command does not exist error on ubuntu 14.10? I was installing tar.bz2 application (OpenFM) on my Ubuntu 14.10 and I followed steps listed on this website: http://www.makeuseof.com/tag/compile-install-tar-gz-tar-bz2-files-ubuntu-linux/ .
When I had to run the "./configure" command I saw this:
bash: ./configure: No such file or directory

On this website there were a note if my system does not have the ./configure command I can skip to the next chapter of the guide what contained executing "make" command.
When I executed "make" command without executing "./configure" command I saw this:
make: *** * ***No targets specified and no makefile found.  Stop.

Please answer to me how to fix this error or how to install .tar.bz2 application without "./configure" command.
Sorry for my terrible English and thanks for help!

A: configure is a script (file) located in the source tree of a source distribution.
Check if it exists in the source tree of OpenFM and that is it executable.


text:
Q: NOT receiving DMARC reports from AOL / HOTMAIL / MSN / OUTLOOK / LIVE My DMARC DNS record looks like this: (domain name is redacted)

_dmarc.domain.com TXT "v=DMARC1; p=none; sp=none; rua=mailto:dmarc@domain.com; ruf=mailto:dmarc@domain.com; rf=afrf;
  pct=100; ri=86400"

Now, I receive aggregate DMARC and forensic DMARC reports from Gmail, Comcast, Yahoo, Emailsrv, etc.
But I'm not receiving any reports from Aol, Hotmail, Msn, Outlook, Live.
Any ideas why? (I'm certain that email IS being sent to addresses on those ESPs, and both SPF and DKIM pass)
Any suggestion to make DNS record format more ESP-inclusive?
Thanks in advance.

A: Your DMARC record looks great (assuming the obfuscated "domain.com" isn't hiding a typo, but since it works for some I'd guess not)  and I've had issues in the past with particular mail hosts not sending DMARC reports.
But do remember that external mail agents aren't required to send DMARC reports to you.  Nothing says they must use DMARC or report on their DMARC evaluations.  Only that if they do report, they must use the specified addresses.  It'd be nice if they did send reports as that helps you [us] see where mail & spam problems are coming from, and fix them.  But that isn't a guarantee.
Looking at my logs I don't see HoTMaiL, MSN, or Live.com reports for a while.  But I do see Outlook.com and domains that I know are O365 hosted.  Are you still having problems?  If so, you may be seeing the result of should and may versus shall and must in the specifications.


text:
Q: ¿Como puedo agregar mas input a mi codigo? sin que me afecte lo que se logro? Primero quiero explicarles que hace mi codigo: al hacer click solo el input type checkbox ejecuta la funcion myfuncion y me cambia el id por una class para el div, y al final si uno refresca la página o sale de ella, el localStorage recuerda el estado de el checkbox y se ejecuta
    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <input id="id-01" name="myFunction" type="checkbox" onchange="myFunction()">
This
            is a DIV element.

Mi problema? solo puedo hacerlo con un solo input checkbox, y necesito que realice lo mismo que con un input pero con 5. muchas gracias por su tiempo

A: No sé mucho de Javascript pero se me ocurre esto, creo que solo faltaría en la funcion MyFuntion recibir según la selección, pero no se como hacerlo, actualmente escribí var element = document.getElementById("myDIV-"+i); pero no funciona:


text:
Q: Unable to login into AWS EC2 ubuntu AMI using SSH I'm trying to connect with the standard guidlines provided here by aws.
$chmod 400 key.pem
$ssh -i absolute_path_to_key/key.pem ubuntu@public_dns

Throws an error
ssh: Could not resolve hostname public_dns: nodename nor servname provided, or not known

Now I tried using public_ip instead of public_dns,
Again, throws an error
ssh: connect to host public_ip port 22: Connection refused

I checked security group on my ubuntu server, its inbound was ssh enabled for all ip addresses and was listening on port 22. I tried to copy key.pem content to .ssh/id_rsa file on my local machine. No success yet. I think something is wrong with my local machine ssh configuration.
Local machine: MacBook Air
Any suggestion/resources are appreciated. It would also be great if someone can point me to resources on ssh client configuration So I can have a closer look. Thankyou
******UPDATES******
Output after using -vvv
OpenSSH_6.9p1, LibreSSL 2.1.8
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug1: /etc/ssh/ssh_config line 103: Applying options for *
ssh: Could not resolve hostname public_dns: nodename nor servname provided, or not known

This is how my ssh_config file looks like:
#   $OpenBSD: ssh_config,v 1.26 2010/01/11 01:39:46 dtucker Exp $

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

Host *
   SendEnv LANG LC_*

# Configuration options and default values (see ssh_config(5) for their meaning):
#
#   Host # (no default)
#   AddressFamily any
#   AskPassGUI yes # (Apple only)
#   BatchMode no
#   BindAddress # (no default)
#   ChallengeResponseAuthentication yes
#   CheckHostIP yes
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour
#   ClearAllForwardings no
#   Compression no
#   CompressionLevel 6
#   ConnectionAttempts 1
#   ConnectTimeout # (no default)
#   ControlMaster no
#   ControlPath  # (no default)
#   ControlPersist no
#   DynamicForward
#   EnableSSHKeysign no
#   EscapeChar ~
#   ExitOnForwardFailure no
ForwardAgent yes
ForwardX11 yes
ForwardX11Timeout 1200
ForwardX11Trusted no
XauthLocation xauth
# Default is to search $PATH.  It is recommended that a full path be provided.
#   GatewayPorts no
#   GlobalKnownHostsFile /etc/ssh/ssh_known_hosts,/etc/ssh/ssh_known_hosts2
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   HashKnownHosts no
#   HostbasedAuthentication no
#   HostKeyAlgorithms ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss
#   HostKeyAlias # (no default)
#   HostName # (set by command at run-time)
#   IdentitiesOnly no
#   IdentityFile .ssh/id_rsa,.ssh/id_dsa
#   IPQoS lowdelay
#   KbdInteractiveAuthentication yes
#   KbdInteractiveDevices # (no default)
#   KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
#   LocalCommand  # (no default)
#   LocalForward  # (no default)
#   LogLevel INFO
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-sha1-96,hmac-md5-96,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96
#   NoHostAuthenticationForLocalhost no
#   NumberOfPasswordPrompts 3
#   PasswordAuthentication yes
#   PermitLocalCommand no
#   PKCS11Provider # (no default)
Port 22
#   PreferredAuthentications gssapi-with-mic,hostbased,publickey,keyboard-interactive,password  # (set by ssh at run-time)
#   Protocol 2
#   ProxyCommand # (no default)
#   PubkeyAuthentication yes
#   RekeyLimit 0
#   RemoteForward # (no default)
#   RequestTTY auto
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   SendEnv # (no default)
#   ServerAliveCountMax 3
#   ServerAliveInterval 0
#   StrictHostKeyChecking ask
#   TCPKeepAlive yes
#   Tunnel no
#   TunnelDevice any:any
#   UsePrivilegedPort no
#   User # (set by command at run-time)
#   UserKnownHostsFile ~/.ssh/known_hosts,~/.ssh/known_hosts2
#   VerifyHostKeyDNS no
#   VisualHostKey no
#   XAuthLocationi xauth

# XAuthLocation added by XQuartz (http://xquartz.macosforge.org)
Host *
    XAuthLocation /opt/X11/bin/xauth


text:
Q: Expectation of the Sum of K Numbers without replacement We have n cards numerated from 1 to $n$. We draw $k < n$ random cards one after another without putting back. Let $X$ be a random variable that is a sum of $X_i$ - random variable responsible for a number on the i$\small th$ card that we draw. What is the expected value $\mathbb{E}[X]???$
I know that $X = X_1 + X_2 + ... + X_k \Rightarrow \mathbb{E}[X] = \mathbb{E}X_1 +...+ \mathbb{E}X_k$ $\, ,\:$ and $\mathbb{E}X_1 = \frac{N+1}{2} \:$, but i don't understand how to find $\mathbb{E}X_i$ for $i = \overline{2,n}$.
Who thinks that $\mathbb{E}X_2 =...= \mathbb{E}X_k = \mathbb{E}X_1 = \frac{N+1}{2}$ explain me please why does it work? Because each time we don't put card back and in our case random variables are dependent and each time we have 1 card less left than before.


text:
Q: General relativity: Why don't these two differentials commute? I encountered some metric today defined by
$$
ds^2 = - \left( 1 - \frac{2GM}{r} \right) dv^2 + (dv dr + dr dv) + r^2 d \Omega^2
$$
In all education I've done until now $$dv dr = dr dv.$$ Why is this no longer the case? I suspect this has something to do with tensors, but I am not sure why.

A: This is the Eddington-Finkelstein metric for a Schwarzschild geometry, and the differentials do commute. I believe they put the line element in this form in order to highlight the that the components of the metric are
$$g_{vv}=\left(1-\frac{2GM}{r}\right),\hspace{0.5cm}\,g_{vr}=g_{rv}=-1$$
$$g_{\theta\theta}=-r^2,\hspace{0.5cm}g_{\phi\phi}=-\sin^2{\theta}$$
(Note that I'm using a $(+,-,-,-)$ signature.) If this is an introductory text, then the author may have done this to show that off-diagonal elements of the metric have to be halved when being read off from the line element.
I hope this helps!

A: Another way of thinking about this:
In general, tensors with "down" indices are maps from the space of vectors${}^{1}$ to the space of functions.  So, a tensor $\bf T$ is a function that takes two vectors and spits out a real number, and you can think of it in the "index-free" manner as:
$${\bf T}\left({\vec v_{1}}, {\vec v_{2}}\right) = f(x^{a})$$
There is also a further restriction on $T$: it is multilinear in both of its coordinates. So, if you multiply either vector by a scalar, you multiply $f$ by the same scalar; and if you replace either vector by a sum of two other vectors, the result is the sum of the tensor acting on the individual vectors.  This forces $T$ to be representable as a matrix, which leads us to the familiar notation:
$$f(x^{c}) = v_{1}^{a}T_{ab}v_{2}^{b}$$
Now, it should be obvious that ${\bf T}$ can, in principle, act differently on $v_{1}$ and $v_{2}$, and this happens if $T_{ab}$ is not symmetric.
Now, what does this have to do with differentials?  Well, remember that we can express the basis of the vector space with partial derivatives, so that:
$${\vec v} = v^{a}\frac{\partial}{\partial x^{a}}$$
which makes $\vec v$ acting on a function $f$ the directional derivative of $f$ along $\vec v$.  So, partial derivatives are the basis of our "up" space of vectors.  What is the basis of the "down" space of vectors?  Well, we need something that has an index, let's call it $e^{a}$, we also need:
$$\frac{\partial}{\partial x^{a}}e^{b} = \delta^{b}{}_{a}$$
Well, if we choose $e^{a} = dx^{a}$, this should be obviously true.  So, just like we can express:
$${\vec v} = v^{a}\frac{\partial}{\partial x^{a}}$$
we can also express:
$${\bf T} = T_{ab}dx^{a}dx^{b}$$
And the only way we can also have a $\bf T$ that acts differently on its first and second argument is if we also have $dx^{a}dx^{b} \neq dx^{b}dx^{a}$ when $a \neq b$
Finally, note that a lot of this is moot, because metric tensors are defined to be symmetric:  the basal requirement for a dot product is that ${\vec v} \cdot {\vec w} = {\vec w} \cdot {\vec v} = g_{ab}v^{a}w^{b} = g_{ab}w^{a}v^{b}$
${}^{1}$ Yes, I know we're talking about vector fields and tensor fields, rather than vectors and tensors, but let's not complicate this by making that distinction right now.

A: Written out explicitly (see this Wikipedia article):
$$v=t+r^{*}$$
$$dr^{*}=(1-{\frac {2GM} r})^{-1}dr$$
so
$$dv=dt+dr^{*}=dt+(1-{\frac {2GM} r})^{-1}dr$$
Then
$$dvdr=(dt+(1-{\frac{2GM} r})^{-1}dr)dr=dtdr+(1-{\frac{2GM}{r}})^{-1}d^2r$$
and$$drdv=dr(dt+(1-{\frac{2GM} r})^{-1}dr)=drdt+(1-{\frac{2GM} r})^{-1}dr^2$$
wich are equal because the infinitesimal increments $dr$ and $dt$ are infinitesimal increments in numbers and $r$ is a number too.
So $$dvdr=drdv$$
which is why the metric in the article has a $2dvdr$ term.

A: *

*More generally, a metric tensor
$$\mathbb{g} ~\in~ \Gamma\left( {\rm Sym}^2(T^{\ast}M)\right)$$
is a section in the symmetric tensor product
$${\rm Sym}^2(T^{\ast}M)~=~T^{\ast}M\odot T^{\ast}M$$
over the cotangent bundle $T^{\ast}M$.
In other words, $\mathbb{g}$ is a symmetric $(0,2)$ covariant tensor field.

*In a coordinate chart $U\subseteq M$, it takes the form
$$\mathbb{g}|_U ~=~ g_{\mu\nu}\mathrm{d}x^{\mu}\odot \mathrm{d}x^{\nu},$$
with the manifest rule
$$ \mathrm{d}x^{\mu}\odot \mathrm{d}x^{\nu}~=~\mathrm{d}x^{\nu}\odot \mathrm{d}x^{\mu}, $$
cf. OP's question.

A: That is the Eddington-Finkelstein metric (one of the forms) and it can indeed be written as:
$$ ds^2 = - \left( 1 - \frac{2GM}{r} \right) dv^2 + 2dv dr + r^2 d \Omega^2 $$
Why your book doesn't write it that way I don't know - you'd have to ask the author.

A: In multilinear algebra, there are several ways to construct new vector spaces from old ones: for a given (real, finite dimensional) vector space $V$, we can construct its dual $V^\ast$, given vector spaces $V$ and $W$ we can construct $V\otimes W$, and we can construct $V\odot V$, $V\wedge V$ (and many more of course). Also these constructions can be repeated.
Typically the latter, $V\odot V$, $V\wedge V$, are constructed by mathematicians as quotients of $V\otimes V$, which works much more generally than for finite dimensional vector spaces over a field. In our special case however (over a field), they can also be constructed as subspaces of $V\otimes V$, in the symmetric case the subspace generated by elements of the form $v\otimes v' + v'\otimes v$, and the alternating case by elements of the form $v\otimes v' - v'\otimes v$.
Physicists, by historical accident, by the lack of need for more generality or by the emphasis on calculation, focus on the second approach. If you make use of several natural isomorphisms like $V^{\ast\ast} \cong V$, $\text{Hom}(V,V) \equiv V^\ast\otimes V$, you get quite far in describing all kinds of derived vector spaces purely in terms of tensor products and duals. When $V = T_xM$, the tangent space of a manifold, the elements of the resulting objects are called tensors. One ugly artefact of this approach that I am aware of, is that the one-dimensional top-exterior power $\Lambda^nV$ of an $n$-dimensional vector space $V$ is viewed as something that is almost like a scalar, but not quite; its elements are called tensor densities.
Another approach popular under physicists is to consider the new vector spaces as multilinear maps $V\times\cdots V\times V^\ast\times\cdots\times V^\ast\to\Bbb R$. If you allow restrictions on these maps, like symmetry or antisymmetry in some of the arguments, and you make use of $V\otimes W \cong W\otimes V$, you can describe most tensors of interests to physicists.
Finally, a metric tensor is a section $g$ of $T^\ast M\odot T^\ast M$, like Qmechanic said. Here $T^\ast M$ can be seen as the union of all $T_x^\ast M$ (along with a given differentiable structure), and a section assigns an element $g(x)\in T_x^\ast M\odot T_x^\ast M$ to each $x\in M$. Depending on your explicit construction, you view elements of $T_x^\ast M\odot T_x^\ast M$ as being generated by $\alpha\otimes\beta + \beta\otimes\alpha$, for $\alpha,\beta\in T_x^\ast M$, i.e. $drdv + dvdr$ in your case, or as products $\alpha\odot\beta$ or $\alpha\beta$ with the understanding that $\alpha\odot\beta = \beta\odot\alpha$ and $\alpha\beta = \beta\alpha$.


text:
Q: Need help with Riemann sum Find $$\int_{a}^{b} x^m dx$$ where $0<a<b$ and $m\neq -1$.
The answer goes as follows : but I get lost in the calculations which I need help with pinning down precisely:
We choose the points of devision of the segment $[a,b]$ as $x_i=x_0q^i; x_n=b; x_0=a; \implies q=({b\over a})^{1\over n};x_i=a ({b\over a})^{i\over n}$
Then: $$S_n=\sum_{i=0}^{n-1}f(x_i)(x_{i+1} - {x_i}) = a^{m+1} ({b\over a})^{1\over n}-1) \sum _{i=0}^{n-1} ({b\over a})^{i(m+1)\over n} $$

A: As you note, the points are chosen to form a geometric progression $x_i=aq^i$, with $q=\left(\dfrac ba\right)^{1/n}$. Thus we have $x_{i+1}-x_i=qx_i-x_i=(q-1)x_i$.
The Riemann sum is
$$\sum_{i=0}^{n-1}x_i^m(x_{i+1}-x_i)=(q-1)\sum_{i=0}^{n-1}x_i^{m+1}=(q-1)a^{m+1}\sum_{i=0}^{n-1}q^{i(m+1)}=(q-1)a^{m+1}\frac{q^{n(m+1)}-1}{q^{m+1}-1}\\
=\frac{q-1}{q^{m+1}-1}a^{m+1}\left(\left(\frac ba\right)^{m+1}-1\right).$$
The fraction can be simplified as $\dfrac1{q^m+q^{m-1}+\cdots1},$ which will tend to $\dfrac1{m+1}$ as $q\to1$.
The final value is
$$\frac{b^{m+1}-a^{m+1}}{m+1}.$$

A: Because $x\to x^m$ is incresing the min value and max value of this function on$[x_{i-1},x_{i}]$ is :
$$A_{\min,i}=a^mq^{(i-1)m}\ \ \ \ \ \ A_{\max,i}=a^mq^{im} $$ now we have to compute the lower sum and the upper one:
$$A_{\min}=\sum_{i=1}^nA_{\min,i}(x_i-x_{i-1})=a^{m+1}\sum_{i=1}^nq^{(i-1)r}q^{m}(q-1) =a^{m+1}(q-1)\sum_{i=1}^{n}q^{(i-1)(m+1)}=a^{m+1}(q-1)\frac{q^{i(m+1)-1}}{q^{m+1}-1}$$
and similarly you can compute the upper bound too:
$$A_{max}=a^{m+1}(q-1)q^m\sum_{i=1}^{n}q^{(i-1)(m+1)}=a^{m+1}(q-1)q^m\frac{q^{n(m+1)-1}}{q^{m+1}-1} $$
an the two sums can be simplified to:
$$A_{\min}=(b^{m+1}-a^{m+1})\frac{1}{\frac{q^{m+1}-1}{q-1}}\ \ \ A_{\max}=(b^{m+1}-a^{m+1})\frac{q^m}{\frac{q^{m+1}-1}{q-1}} $$
from here we have to compute the limit $\lim_{q\to 1} A_{\max}$ and $\lim_{q\to 1} A_{\min}$ and we hwill use:
$$\lim_{x\to 1}\frac{x^r-1}{x-1}=r+1 $$


text:
Q: Laravel Sanctum - sanctum/csrf-cookie (204 "No content") Laravel sanctum has been a bit of a headache for me as i have spent hours trying to figure out why sanctum/csrf-cookie route returns no content. initially the same route return 404 not found but after adding 'prefix' => 'api/sanctum' config/sanctum.php it seems to work except that it outputs nothing and no cookie is set in my browser.
Here are some of my codes
.env
SANCTUM_STATEFUL_DOMAINS=localhost:8080
SPA_URL=http://localhost:8080
SESSION_DOMAIN=localhost

--config/cors.php
'paths' => [
        'api/*',
        'login',
        'logout',
        'register',
        'user/password',
        'forgot-password',
        'reset-password',
        'sanctum/csrf-cookie',
        'user/profile-information',
        'email/verification-notification',
      ],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

axios
export const authClient = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  withCredentials: true, // required to handle the CSRF token
});

and having done all of that, if i tried to generate a token using
axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});

i get 204 no content response
i have also added the api middleware in kernel.php as instructed in the doucmentation  but still wont set the cookie. and when i try to make request to another route protected by sanctum i 419 token mismatch.
i have also run a fresh installation of laravel, php artisan optimize, cleared my brower history, checked the endpoints in postman but still thesame 204 and 419 exceptions

A: I was struggling with the same issue for days and then founded a way that worked.
so :
The '/sanctum/csrf-cookie' route return a 204 response when successfull, the  then you have to send your post request with credentials. i used to get a 419 reponse status.
so after followed laravel docs here is what i added :

*

*SPA
make sure you set the withCredentials header to true

*API

.env
SESSION_DRIVER=cookie
SESSION_DOMAIN='.localhost'
SANCTUM_STATEFUL_DOMAINS='localhost,127.0.0.1'

.kernel.php
add in your middleware array : \Illuminate\Session\Middleware\StartSession::class

A: Hey I don't know whether you've found the answer or not but that request meant to have empty response body. Your CSRF token is available in the header of the response ;D

A: From HTTP Specification:

The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site.

According to specification 204 is the exptected response from server.

A: You can insert in bootstrap.js file
import axios from 'axios';
window._ = _;

window.axios = axios;
window.axios.defaults.baseURL = "/api/";
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


text:
Q: echo a variable whose value is * why does embedding the variable in quotes result in printing the filenames on different lines?  ls
> file1 file2 file3

echo *
> file1 file2 file3

foo=$(ls)
echo $foo
> file1 file2 file3

echo "$foo"
> file1
> file2
> file3

In the last example, why are the filenames displayed on separate lines? Would you explain the steps that the shell (bash) goes through in processing it, please?


text:
Q: Adding a new column in Angular I have:
export class Column {
constructor(public name: string, public tasks: string[]) {} }

and
import { Column } from './column.model';

export class Board {
constructor(public name: string, public columns: Column[]) {}}

Here is my typescript code:
     import { Component, OnInit } from '@angular/core';
    import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
    import { Board } from 'src/app/models/board.model';
    import { Column } from 'src/app/models/column.model';

    @Component({
      selector: 'app-main-view',
      templateUrl: './main-view.component.html',
      styleUrls: ['./main-view.component.scss']
    })
    export class MainViewComponent implements OnInit {
    newcolumn: string;
      constructor() { }

      board: Board = new Board('Test Board', [
        new Column('First', [
          "one",
          "two"
        ])
      ]);

      ngOnInit() {
      }

      drop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
          moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
        } else {
          transferArrayItem(event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex);
        }
      }
  addColumn() {
    this.board.columns.push(this.newcolumn);
  }

    }

Error: Property 'name' does not exist on type 'Column[]
I have trouble with adding a function that adds a new column to my board.
There is also a bug when using board.column.name. Please help. I've been trying to do this for several hours.


text:
Q: Is it possible to use Require.js in Onsen UI framework? I like to use require.js cordova app in Onsen UI framework. but before i need to know is it possible to use require.js in onsen ?

A: It shouldn't be a problem to use require.js in an Onsen UI project. Onsen UI is just a library after all.
Just note that Onsen UI includes not only javascript, but also css styles, which you will need to add in order for it to work.
If all else fails you can also just load Onsen UI via a script tag and then use require.js for the rest of the project.
Anyway it should be possible - if you run into any trouble feel free to make a question about the specific problem at hand. :)

A: As of july 2018, it does not work due to a bug in Onsen UI: https://github.com/OnsenUI/OnsenUI/issues/2360