text:
Q: How to check if mail is sent successfully or canceled? I create an Outlook mail like this:
 Outlook.Application outlookApp = new Outlook.Application();
 Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
 mailItem.Subject = mailSubject;
 mailItem.To = "";
 mailItem.Attachments.Add(totalPath);
 mailItem.Body = mailBody;
 mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
 mailItem.Display(true);
 //Mail is send succesfully?

Is it possible to check if the mail is sent successfully or canceled?
When I execute the following code, the error appears

'the item is moved or deleted'

Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = mailSubject;
mailItem.To = "";
mailItem.CC = "EDI.Orders@trust.com";
mailItem.Attachments.Add(totalPath);
mailItem.Body = mailBody;
mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
mailItem.Display(true);
//Mail is send succesfully?
if (mailItem.Sent)
{
   MessageBox.Show("Sended");
}
else
{
   MessageBox.Show("canceled");
}

The error appears at mailItem.Sent.

A: The mailItem.Sent property shows if the E-Mail has been sent.
Additionally you can attach to the mailItem.Write event. (But take care - will also get called on just saving & so on)
mailItem.Write += mailItem_Write;

void mailItem_Write(ref bool Cancel)
    {
       //your code...
    }

A: MailItem.Sent property returns a Boolean value that indicates if a message has been sent.

A: For your question;

MailItem.Sent Property (Outlook)
Returns a Boolean value that indicates if a message has been sent.
  Read-only.

https://msdn.microsoft.com/EN-US/library/office/ff868242.aspx
When checking this property after Display has been called, I suspect that as the item is no longer Active, the call to Sent is failing. One way you could potentially confirm if the mail has indeed been Sent is by handling the ItemSend event of the Outlook.Application class.
        Outlook.Application outlookApp = new Outlook.Application();

        outlookApp.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(outlookApp_ItemSend);

        Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
        mailItem.Subject = "Test";
        mailItem.To = "a.b@c.com";
        mailItem.CC = "";

        mailItem.Body = "Test Message";
        mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
        mailItem.Display(true);

And in the Send event handler check the message;
void outlookApp_ItemSend(object Item, ref bool Cancel)
{
    if (Item is Outlook.MailItem)
    {
        string subject = ((Outlook.MailItem)Item).Subject;

        if (subject == "Test")
        {
            //Item sent
        }

    }
}

A: Here is a solution that will not block outlook.
class Class1
{
    static bool mailWasSent = false;
    private static System.Windows.Forms.ApplicationContext _context;
    static void Main(string[] args)
    {
        Outlook.Application outlookApp = new Outlook.Application();
        Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
        mailItem.Subject = "My Subject";
        mailItem.To = "";
        mailItem.Attachments.Add(@"C:\test.pdf");
        mailItem.Body = "This is my Body-Text";
        mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
        ((Outlook.ItemEvents_10_Event)mailItem).Close += MailItem_onClose;
        ((Outlook.ItemEvents_10_Event)mailItem).Send += MailItem_onSend;

        //mailItem.Display(true);   // This call will make mailItem MODAL -
        // This way, you are not allowed to create another new mail, ob browse Outlook-Folders while mailItem is visible

        // Using ApplicationContext will wait until your email is sent or closed without blocking other Outlook actions.
        using (_context = new System.Windows.Forms.ApplicationContext())
        {
            mailItem.Display();
            System.Windows.Forms.Application.Run(_context);
        }
        if (mailWasSent)
        {
            System.Windows.Forms.MessageBox.Show("Email was sent");
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Email was NOT sent");
        }
    }

    private static void MailItem_onSend(ref bool Cancel)
    {
        mailWasSent = true;
    }

    private static void MailItem_onClose(ref bool Cancel)
    {
        _context.ExitThread();
    }
}

A: I had the same task and none of the suggestions above cover all cases. Some are outright wrong.
We know that Outlook.MailItem in C# is a mere RCW (Runtime Callable Wrapper) which is very loosely coupled with the COM object, so when the object is gone it will throw COMException "The item is moved...".
When we create Outlook.MailItem in C# the only unique identifier is the reference to the RCW (no EntryID, no whatever other ID on the COM object - NONE!). When the code calls Display() on the object it is a non blocking call the RCW reference will be lost if not assigned upon exit from the calling routine. Display(true) will block.
There are also 2 Send events to hook up to: one on the MailItem itself and another on the Application as suggested in the earlier posts. The one on MailItem is raised first and then followed by Application's event. Since there is no default item ID on the MailItem object it can only identified by some secondary custom properties. Note that RCW of the Item in Application.Send event handler is different and not equal to the original MailItem RCW.
Problem solved?
Not quite! Due to the parasite apps (SendGuard etc.) which feast on the same event.
There is a chance that user will revert sending by responding to the prompts of the parasite apps which will result any suggestions incorrectly marking the item as sent. The solution in this case is probably attaching and handling Close event of the Outlook.MailItem. Booth the problem and the feature here is that if the e-mail is sent the reference to the COM object Outlook.MailItem will be gone. RCW will throw exception when trying to access any property of it in Close handler. This is understandable, because Microsoft is protecting stability of their app and is removing reference to COM object upon successfully completing send. The wrong here is that Cancelled parameter in the handler will not have any effect in this case. If the user simply decides to Close Outlook.MailItem the RCW in Close handler will have the reference to the Outlook.MailItem and Cancelled will prevent close if set to True in the handler.
To confuse more, the user may Save the Outlook.MailItem for later sending and close it. If there is no reference to RCW the object will no longer be accessible. If the reference is maintained in the program, whenever user reopens saved draft it will handle the events normally. To capture that you may use Inspector.Close and Outlook.MailItem.Write events.
So what worked for me was:

*

*Maintain RCW to the created MailItem object in the program.

*Attach Send, Write and Close events handlers to MailItem.

*Attach Close event handler to the Inspector to capture if the modified e-mail has been saved for later sending

*Make Sent/Not Send decision and dereferencing of RCW (and COM object if user closed e-mail) in Close handlers of the MailItem (Sent) and Inspector
(Not saved.)

A: The problem is that Outlook only gives you a loosely coupled reference,
            Outlook.MailItem eMail = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

As soon as you've executed eMail.Display(true) you can no longer use the eMail object, this is because Outlook has moved the email to the 'outbox'
I have a Boolean called 'display' which is true if the caller wants to display the email to the user. If false the Send() method can be called without problems.
Please note that if the user has Outlook running there's no need to call the 'send' method, once it's in the 'outbox' Outlook will pick it up and send it.  The rest of the code only has to deal with the case of the user not having Outlook open.
But if true I get a new reference to Outlook, and check whether 'outbox' contains items, and whether it contains more items than before. The user might not have pressed 'send', he/she might have closed the email without saving it.  I ran into a permissions error when trying to send the email, so made a copy, sent that, and deleted the original from the 'outbox' and then also deleted it from the bin.
            if (display)
            {
                eMail.Display(true);  //true = modal (a pop-up window).  True makes it a blocking call, but after the email has been displayed the 'eMail' object can no longer be used
                                      //if calling Display(false) the email flashes briefly on the screen, and the .Send() method executes without error, but it doesn't send, it just leaves the email in Outbox.
            }
            else
            {
                eMail.Send();
            }
            oNS.Logoff();

            if (display)
            {
                Boolean success = false;
                do
                {
                    try
                    {
                        oApp = new Outlook.Application(); //this fails if Outlook is running a background process (disposing of the email window resources)
                        success = true;
                    }
                    catch (System.Exception ex)
                    {
                        Thread.Sleep(10);
                    }
                }
                while (!success);
                oNS = oApp.GetNamespace("mapi");
                success = false;
                do
                {
                    try
                    {
                        outlookAlreadyOpen = oNS.CurrentProfileName?.Length != null; //it's a way to check whether Outlook application is open
                        success = true;
                    }
                    catch (System.Exception ex)
                    {
                        Thread.Sleep(10);
                    }
                }
                while (!success);

                if (!outlookAlreadyOpen) //if it's open Outlook will send the email and move it from 'outbox' to 'sent items'
                {
                    //if Outlook is not open we need to send it outselves, otherwise it stays in the 'outbox'
                    oNS.Logon(contractsDatabase.properties.emailProfile, Missing.Value, true, true);

                    outboxFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox);

                    if (outboxFolder.Items.Count > 0 && outboxFolder.Items.Count > countOutboxFolder)
                    {
                        eMail = outboxFolder.Items.GetLast(); //last is the most recent, i.e. the email that the user pressed 'send'.
                        eMail.Copy().Send(); //we don't have permission to send the original email, so send a copy instead
                        MAPIFolder deletedItemsFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems);
                        int countDeletedItemsFolder = deletedItemsFolder.Items.Count;
                        eMail.Delete();
                        if (deletedItemsFolder.Items.Count > 0 && deletedItemsFolder.Items.Count > countDeletedItemsFolder)
                        {
                            //first check that an item came to deleted items, because outlook could be set set to not move emails to deleted items folder according to user preferences
                            deletedItemsFolder.Items.GetLast().Delete();
                        }
                    }

                    oNS.Logoff();
                }
            }


text:
Q: Copying a registry key I am trying to make a simple PowerShell script that copies some registry folders and substrings in these folders to it's own folder on the C:\ drive.
How can I do this?  I've tried export command, and Copy-Item -Path command but without luck.
For example copy the files (registry files) in the keys
HKLM\software\Norton
HKLM\software\Wow6432Node\Norton
to the folder C:\backupNorton.

A: You can do
Get-ChildItem HKLM:\SOFTWARE\Norton

And then export or save the object you get from that - either as plain text or using something like Export-Clixml.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert JSON to CSV I'm working on storing around 200 000 Json objects into a CSV file. But the problem is that any 2 JSON Objects might be different (having different key names).
I thought about creating a HashSet and traverse through all objects once so as to get column names for my CSV file. But this process is apparently taking too much time.
Is there another way to add columns to a CSV file dynamically?

A: One approach would be to use jq ("Json Query"):
def tocsv:
  if length == 0 then empty
  else
    (.[0] | keys_unsorted) as $keys
    | (map(keys) | add | unique) as $allkeys
    | ($keys + ($allkeys - $keys)) as $cols
    | ($cols, (.[] as $row | $cols | map($row[.])))
    | @csv
  end ;

tocsv

For example, assuming the above is in a file named json2csv.jq and that the input is in in.json:
jq -r -f json2csv.jq in.json

The above program constructs the header line by starting with the key names of the first object (in the order in which they appear there), and then extends the header line as required.
For more about jq, see https://stedolan.github.io/jq
Another approach would be to use in2csv, part of the csvkit tookit -- see https://csvkit.readthedocs.org


text:
Q: OAuthOptions.Scope Cannot Be Assigned To I'm trying to implement LinkedIn/OAuth authentication in my ASP.NET Core 2.0 app and I need to set the scope to { "r_basicprofile", "r_emailaddress" } so that I can user's email, profile image, etc.
When I try to set the scope in the following code, I'm getting the following error:

Property or indexer 'OAuthOptions.Scope' cannot be assigned to -- it's
  read-only.

Here's the code:
services.AddOAuth(CookieAuthenticationDefaults.AuthenticationScheme, options => {

   options.SignInScheme = "LinkedIn";
   options.ClientId = "1234567890";
   options.ClientSecret = "1234567890";
   options.CallbackPath = "/linkedin-callback";

   // Configure the LinkedIn endpoints
   options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization",
   options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken",
   options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,picture-urls::(original))",

   options.Scope = { "r_basicprofile", "r_emailaddress" };

   options.Events = new OAuthEvents
   {
        OnCreatingTicket = OnCreatingTicketLinkedInCallBack,
        OnTicketReceived = OnTicketReceivedCallback
   };
})

Any idea how I can set the scope?
P.S. I tried to adapt the code from my ASP.NET Core 1.1. This code was working fine in the ASP.NET Core 1.1 app.

A: The Scope = { "r_basicprofile", "r_emailaddress" } syntax is only available when using object initialization. Here, the options object is not instantiated from your code but directly provided by ASP.NET Core so you can't use this syntax.
The good news is that Scope property is a collection (internally, a hash set) so you can simply do:
options.Scope.Add("r_basicprofile");
options.Scope.Add("r_emailaddress");

If you want to get rid of the default scopes, you can remove them using options.Scope.Remove("scope") or options.Scope.Clear().


text:
Q: Ubuntu 16.04 LTS very slow at everything - How to fix? I've been using Ubuntu 14.04 LTS for about a year and a half now and I've loved it.  I hadn't yet done the upgrade to 16.04 because I didn't have the time.  I made some time the other day and opened the terminal and ran sudo apt-get do-release-upgrade.  Quite frankly, I'm extremely disappointed.  After taking 5 and a half hours to upgrade, my computer took nearly 5 minutes to reboot.  I thought it was just a one-time thing (setting things up after the upgrade, similar to the Win10 upgrade).  But it takes that long every time.  Below are some before/after comparisons (14.04 vs 16.04).

*

*Boot time: Before - approx. 1 minute; After - approx. 5 minutes

*Login time: Before - approx. 15 seconds; After - approx. 2 minutes

*Shutdown time: Before - approx. 5 minutes; After - approx 7 minutes

*Memory usage at idle: Before - approx. 60%; After - approx. 80%

*CPU usage at idle: Before - approx. 20%; After - approx. 75%

*CPU temp at idle: Before - approx. 40C; After - approx. 55C

I have no idea why its so slow at everything now but I think it may have something to do with some packages not being installed correctly, or perhaps some old ones hanging around sucking up processing power, however, I've run sudo apt update, sudo apt upgrade, and sudo apt auto-remove multiple times each.  Is there a way to clean up my system and make it run better?

A: There's an excellent chance that your problem was caused by the upgrade from 14.04 to 16.04.  An operating system is a complex beast, with thousands of components, and Ubuntu runs on a staggering variety of hardware configurations; it's impossible for the writers of the upgrade script to test the script against all the variations of hardware and software found in the field before releasing it.  The upgrade script seems simple and convenient, but it causes lots of problems, and unfortunately many people don't seem to know how dangerous it can be.  (Don't feel bad, I learned the hard way too.)
I'm sure that you'd prefer a targeted fix that neatly solves your problem, but if the root of the problem is a flawed OS installation, then you might be forced to use a blunter instrument: wiping the hard drive, and installing 16.04 from scratch (after backing up all your important files, of course).
Here's the outline of how to do it:

*

*In a terminal, do aptitude search '~i!~M' > ~/top-level-packages-before.txt.  (You'll need the aptitude package, if it isn't installed.)  This creates a file containing a list of all the installed packages, not including dependencies.  (Kudos to this answer.)

*If you don't have /home in its own partition, back up the entire /home hierarchy.  Also back up /etc/X11/xorg.conf, if it exists, and /var/www if you use your computer as a web server.  Back up /usr/local/bin, if you have local scripts in there.

*If you dual-boot another OS, then boot to an Ubuntu install DVD or USB stick, choose "Try Ubuntu", run GParted, and use it to delete the Ubuntu partitions (except the partition that mounts /home, if /home has its own partition).  If you're not dual-booting then skip this step, because the Ubuntu installer needs to see how the computer boots.

*Install Ubuntu.  Use the installer to wipe out any partitions from the old Ubuntu installation that weren't wiped already, except the partition that mounts /home, if /home has its own partition.

*Copy your important files from the backup to the new installation.  Unfortunately lots of programs pollute your home folder /home/<username> with junk (type Ctrl+H in Nautilus to see the hidden files and folders; that's where most of the junk is), and copying old config files blindly can cause problems, so you should probably just copy what you need, rather than restoring every last file.

*Install aptitude if it isn't installed, and do aptitude search '~i!~M' > ~/top-level-packages-after.txt.  Restore ~/top-level-packages-before.txt that you created in the first step, if you haven't already.  Do diff ~/top-level-packages-before.txt ~/top-level-packages-after.txt to compare the two files, or use diffuse (kudos to this answer) to discover which packages were installed previously that aren't now.  Consider installing those packages.

By the way, many people choose to have /home mounted in its own partition, because it makes installing a new version of the OS from scratch easier.  (The popularity of this approach with experienced users shows that many people have come to distrust the upgrade script.)  If you're taking my advice and installing the new version of Ubuntu from scratch, you might choose to give /home its own partition while you're installing Ubuntu, just to make the process easier next time.  If for some reason you want to move /home to its own partition before installing Ubuntu from scratch, then there is a procedure to do so, but it's a lot of work, and in my opinion it's easier to move /home to its own partition as part of the process of installing the new version of Ubuntu from scratch.
The gist of this answer is borrowed from this Ubuntu forums thread, which has more information.  Good luck.

A: Have you run htop or top to look for heavy processes?
Also, are you running an SSD or HDD? A quick disk speed check could be worth it. I've hard computers that just crawl because of a bad, or even just old and slow disk. This should do the trick, replacing sda with your drive, of course.
sudo hdparm -Tt /dev/sda

and
sudo hdparm -v /dev/sda


text:
Q: How to add 5 to every number of an array with Bash? I am trying to create an array of user inputs and then add to each element in the array:
read number
for i in 1 2 3
  read array[$i]
done
let position=0
for i in "${array[@]}"
do
   let array[position]+=($i+$number)
   let "position++"
done
for (( i=0; $i<3; i=$1+1 ))
do
   echo ${array[$1]}

So, the user will enter "5" for number and then three more numbers for the array(90, 80, 70). The results should be array(95, 85, 75), but the output I'm getting is array(95, 175, 155).

A: A saner way to write this would be:
read -r number
read -r -a array

for idx in "${!array[@]}"; do
  (( array[$idx] += number ))
done

printf '%s\n' "${array[@]}"

*

*Instead of assuming that the indexes start at 0 (which they didn't, originally, because you were explicitly assigning to positions 1, 2 and 3), using "${!array[@]}" finds the actual indexes, and thus works correctly even with sparse arrays or ones not indexed starting at position 0.

*Instead of duplicating $i (aka the values from your array) on the right-hand side of +=, it only adds the number itself.

*Instead of iterating over indexes (again) to print the values, it just asks the array to dump all its values in index order with "${array[@]}".

See this in operation at https://ideone.com/WTLJSu
There is a behavioral difference insofar as it expects all the array values to be passed on a single line of input.  If you don't want that, see the version at https://ideone.com/3OQtt3 instead.


text:
Q: How to use an Iif Statement in an Expression I have this line of code in c#
I keep getting this error=>
Syntax error: Missing operand before '&' operator.
Find below is my code
ds.Tables[0].Columns.Add("RESULTS").Expression = "Iif(((ActualWeight >= (.96 * TargetWeight)) && (ActualWeight <= (1.04 * TargetWeight))),[GOOD] )";

A: You are missing the false part of the expression as well as Iif is not syntactically correct. so try something like this
ds.Tables[0].Columns.Add("RESULTS").Expression = "IIF(((ActualWeight >= (.96 * TargetWeight)) And (ActualWeight <= (1.04 * TargetWeight))),[GOOD], [BAD])"

A: DataTable Expressions are more like VB than C#.  The && is not supported by And is:
ds.Tables[0]
  .Columns
  .Add("RESULTS")
  .Expression = "Iif(((ActualWeight >= (.96 * TargetWeight)) And (ActualWeight <= (1.04 * TargetWeight))),[GOOD],null)";

Note that I also added a false condition to complete the expression.


text:
Q: Does Polymorphic Slicing occur when Derived Object declares no New Members Does slicing occur in polymorphism, if you store a derived class by value, but the derived class has no extra members?
For example, if I have a class Base. But I want a custom constructor, so I implement Custom, like so:
class Base{
public:
    int a;
    int b;
    Base(int a)
        : a(a)
    { b = 2; }
};
class Custom : public Base{
public: // Note: no new members or functions!
    Custom(int bb)
        : Base(1)
    { b = bb; }
};

If I run it with the following code, it all works as it should. The two instances of Base is initialized correctly. They
#include <stdio.h>
int main(){
    Base base = Base(1);
    Base sliced = Custom(2);
    Custom custom = Custom(2);

    // Some printing of `a`, `b`, and sizeof(base), etc
}

It prints out the following, as you would expect:
         |   a |   b | Size
-----------------------------
    base |   1 |   2 |   8
  sliced |   1 |   2 |   8
  custom |   1 |   2 |   8

So, if I could ask more specifically:

*

*Will this always work? I.e. will I lose information of a or b? (any members/functions of Base)

*If not, why not? Does a derived object store extra information?

*If this will always work, is it bad practice?

I have looked into using strong types, as described by this blog by FluentCpp. This will also work for my implementation, but I feel this makes the code more bloated.

A:
Does slicing occur in polymorphism, if you store a derived class by value, but the derived class has no extra members?

Yes.
It's quite another matter that you don't see any significant loses in your posted code. The metrics you are using to compare the objects indicate as though nothing got lost because of object slicing. However, if you look at the objects in a debugger, you will most likley notice that objects are of different types. The effects of object slicing become apparent in that environment.
I would recommend not creating a derived class just for the convenience of constructing an object of the base class. Use of one or more non-member functions is more appropriate.
class Base
{
   public:
      int a;
      int b;
      Base(int a, int b = 2) : a(a) , b(b) {}
};

Base fromA(int a)
{
   return {a};
}

Base fromB(int b)
{
   return {1, b};
}

A: Using inheritance for the task that you seem to be using it for is not a good idea. Note that from c++20, you can solve the problem you've shown with designated initializers:
class Base
{
  public:
    int a = 1;
    int b = 2;
};

int main()
{
    Base a = Base{.a = 10};  // default b
    Base b = Base{.b = 20};  // default a
    Base c = Base{.a = 10, .b = 20};
}

A: The main reason for having derived classes is to have virtual functions. With your code, once the object is sliced, the virtual functions will start calling the base class versions:
https://godbolt.org/z/WoT5qb
#include <iostream>

class Base{
public:
    int a;
    int b;
    Base(int a)
        : a(a)
    {
        b = 2;
    }

    virtual void foo()
    {
        std::cout << "Base" << std::endl;
    }
};
class Custom : public Base{
public: // Note: no new members!
    Custom(int bb)
        : Base(1)
    { b = bb; }

    virtual void foo()
    {
        std::cout << "Custom" << std::endl;
    }
};

int main(){
    Base base = Base(1);
    Base sliced = Custom(2);
    Custom custom = Custom(2);

    base.foo();
    custom.foo();
    sliced.foo();
}

which outputs:
Base
Custom
Base

So, slicing is still very much undesirable.


text:
Q: XMLHttpRequest cannot load error When we have GeoServer and WebServer on same domain I have Geoserver and webserver on same domain (Windows XP with IIS). But when i tried to get WMS feature info, i got this error in chrome. If Geoserver and webserver on same orgin, no need of proxy i think. so please suggest me to overcome this issue. Thanks in advance
XMLHttpRequest cannot load http://localhost:8080/geoserver/cite/wms?LAYERS=cite%3Aplym_p1_examplec…e%2Fpng&INFO_FORMAT=application%2Fvnd.ogc.gml&SRS=EPSG%3A27700&X=596&Y=160. Origin http://localhost:3890 is not allowed by Access-Control-Allow-Origin.

A: The port is considered part of the site so http://localhost:3890 and http://localhost:8080 are not the same. From the first paragraph here

In computing, the same-origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number1 – to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.1 Same-origin policy also applies to XMLHttpRequest and to robots.txt.[2]


text:
Q: How can I disable the USB power supply from Mac when it goes to sleep mode (including when it's installing updates at night)? I have a USB mouse that has some rainbow-like LED colors (gaming mouse). I keep it connected to my Mac via USB.
At night I just leave the Mac as it is (in sleep mode). The monitor switches off which is fine for me. But what happens is that the USB power is on. This mouse doesn't have a concept of sleep mode. So the mouse remains on throwing the light all across the room. I sleep in the same room where my Mac is kept.
Is there any way I can get Mac to disable the USB power supply whenever it goes to sleep mode? I want to keep it disabled at night somehow so that I can sleep without disturbance. I've heard that Mac wakes up in the middle of the night usually to install updates. I don't want the USB mouse to switch on when Mac is installing updates in the middle of sleep.
I've been searching for a solution to this but I'm not finding anything. How can I disable the USB power supply from Mac when it goes to sleep mode?


text:
Q: Maskedtextbox Mask change depending to OS language Hello I have created maskedtextbox in my WinForms app with mask: 0/0 AAAAA and when I do install this on PC where Czech language is set as default it converts the backslash into dot so I have 0.0 AAAAA
May I ask if is there any way to avoid this automatic change?
Thank you for your time.

A: The / character in the Mask property is the date separator.  It is automatically localized, in Czech the . character is the date separator.
You'll need to escape the character to let it know that you meant the literal.  Use 0\/0 AAAAA instead.  Note that added backslash.

A: Try setting the Culture property of your MaskedTextBox to English culture (because you don't care about the local culture):
yourMaskedTextBox.Culture = new CultureInfo("en-US");
//or set it to an InvariantCulture
yourMaskedTextBox.Culture = CultureInfo.InvariantCulture;

A: You can change this behaviour thru the Control Panel configuration window "Region and Language" settings.


text:
Q: Laravel Echo.join working only Echo.channel and Echo.private not working I am using laravel 5.4 and pusher for event broadcasting. I create a  private channel  "chatroom".
Echo.join('chatroom')  /// Work Well
   .listen('MessagePosted', (e) => {
           this.messages.push({
           body: e.message.body
       });
});

But this is not working with Channel and Private...
 Echo.channel('chatroom')   OR
 Echo.private('chatroom')   //// Not Working

Getting following error

A: You need to put this inside mounted() method. Because error answered that .here is not a function
  mounted(){
    Echo.private('chat')
    .listen('ChatEvent', (e) => {
      console.log(e);
    });

    //Make function for joining and leaving for any users
    Echo.join('chat')
    .here((users) => {
        console.log(users)
    })
    .joining((user) => {
        console.log(user.name)
    })
    .leaving((user) => {
        console.log(user.name)
    });

  }

And if you make private chat , then in routes/channels.php , you've to define/register a channel named chat like this -
Broadcast::channel('chat', function($user){
  return ['name' => $user->name]; //Return data as your need
});

Hope, it will help someone.


text:
Q: Syncing two videos in opencv python I was working on a project which involves synchronization of two videos.
For example, let's say I have two videos which display timestamps,
in the first video timestamp is 11:59:03, in the second video timestamp is 11:59:17, so the difference will be 14 seconds. Now I have to somehow make the shorter video(11:59:03) jump to 11:59:17 and run from this point simultaneously, therefore the two videos will be synchronized.
What i have tried so far:
frameDelay = 14 #FPS of video
delay = 0
frameNum = 0
x = 0

shortCap.set(cv2.CAP_PROP_POS_FRAMES, frameDelay*difference) #skipping that much frames
longCap.set(cv2.CAP_PROP_POS_FRAMES, 0)

while True:

    ret1, frame1 = shortCap.read() #running fast, cam3
    ret2, frame2 = longCap.read()

    frame1 = cv2.resize(frame1, (600, 600))
    frame2 = cv2.resize(frame2, (600, 600))

    cv2.imshow('cam3', frame1)
    cv2.imshow('cam1', frame2)

    key = cv2.waitKey(1)&0xff

    if key == 27:
        break

shortCap.release()
longCap.release()
cv2.destroyAllWindows()

I was able to skip the initial difference frames but after that, as the time increases, the shorter video was running fast (overtaking the second video).

A:
waitKey(0) will display the window infinitely until any keypress (it
is suitable for image display). waitKey(25) will display a frame for
25 ms, after which display will be automatically closed.

so you have to calculate the difference in ms.
(fps1-fps2)*ms_for_each_frame

My proposal would be re capturing contents in same FPS. If that's not possible then you can use a 3rd party application to alter FPS rates such as FFMPEG. Lastly you can start video playbacks on separate synchronized threads with adjusted waitkey(n) values but that would involve also thread synchronization and more complexity. Pick your poison :D.


text:
Q: JSF 2.0 custom composite controls & nesting Greetings,
I'm trying to implement my custom TAB control.
I'd like it to be based on new composite components feature of JSF 2.0:
<i:tabControl width="480" height="320" value="#{backingBean.someIterable}" var="tab" >
    <i:tabItem href="#{tab.href}" caption="#{tab.caption}"/>
<i:tabControl/>

The problem is I don't know how to implement repeater for Composite component.
How to get access to nested element?

A: I don't think you can really iterate over the child components. Check
<composite:insertChildren/>, <composite:renderFacet .../> and <composite:insertFacet .../> tags for child/facet processing.


text:
Q: Docusign ID Check feature not working via API I'm working an envelope with ID Check, I'm sending the following xml for the recipient.
<Recipient>
    <ID>1</ID>
    <UserName>Test Username</UserName>
    <Email>test@email.com</Email>
    <Type>Signer</Type>
    <AccessCode xsi:nil="true"/>
    <IDCheckConfigurationName>ID Check $</IDCheckConfigurationName>
    <CaptiveInfo>
        <ClientUserId>1</ClientUserId>
    </CaptiveInfo>
    <IDCheckInformationInput>
        <AddressInformationInput>
            <AddressInformation>
                <Street1>109 Righter Road</Street1>
                <City>SUCCASUNNA</City>
                <State>NJ</State>
                <Zip>07876</Zip>
            </AddressInformation>
        </AddressInformationInput>
        <DOBInformationInput>
            <DOBInformation>
                <DOB>2000-01-01T00:00:00</DOB>
            </DOBInformation>
        </DOBInformationInput>
        <SSN9InformationInput>
            <SSN9Information>
                <SSN9>788888888</SSN9>
            </SSN9Information>
        </SSN9InformationInput>
    </IDCheckInformationInput>
</Recipient>

My envelope is created along with the recipient, however the ID Check prompt is not displated, not sure why this is not working.
I did notice that the xml doesn't include the property
"requireIdLookup": "true",

This property might be required, however I'm setting that property to true in my code (C#). Could this be an API bug?
Additionally, If I manually set the "ID Check $" via the portal the prompt is displayed and the information from "IDCheckInformationInput" is pre-populated.
Thanks for the help.

A: I'm not sure why but this worked for me.
Setting both of these parameters to true did the trick...
RequireIDLookup = true,
RequireIDLookupSpecified = true


text:
Q: Prim's algorithm when range of Edge weights is known Suppose that all the edge weights in a graph are integers in the range from 1 to |V|. How fast can you make Prim's algorithm run? What if edge weights are integers in the range 1 to W for some constant W?
I think since the Prim's algorithm is based on implementation of min-heap, knowledge about the weights of edges will not help in speeding up the procedure. Is this correct?

A: With this constraint, you can implement a heap that uses O(V) / O(W) respectively space but has O(1) insert and O(1) extract-min operations. Actually you can get O(1) for all operations you require for Prim's algorithm. Since the time complexity of the heap influences the complexity of the main algorithm, you can get better than the default generic implementation.

A: I think the main idea to solve this problem is remember that W is a constant, so, if you represent your priority queue as some structure which size is bounded by W, travel the entire list at each iteration will not change the time complexity of your algorithm...
For example, if you represent your priority queue as an array T with W + 1 positions, having a linked list of vertices in each position such that T[i] is a list with all the vertices that have priority equal to i and use T[W + 1] to store vertices with priority equal to infinite, you will take
O(V) to build your priority queue (just insert all the vertices in the list T[W+1])
O(W) to extract the minimum element (just travel T searching for the first position non empty)
O(1) to decrease key (if vertex v had key equal to i and it was updated to j, just take-off v from list T[i] and insert at the first position of the list T[j]).
So, it will give you complexity O(VW + E) instead of O(V logV + E).
(Of course, it will not work if the range is from 1 to V, because V^2 + E is greater than V \logV + E).

A: For non-binary heap Prim's implementation, the pseudocode can be found with Cormen, Introduction to Algorithms, 3rd edition.
Knowing the range being 1...k, we can create an array with k size and walk through the list, adding edges to the corresponding weight. This, by nature of its storage, means the edges are sorted by weights. This would be O(n+m) time.
Relying on the pseudocode for Prim's algorithm in Cormen, we can analyze its complexity to result in O(nlog{n} + mlog{n}) = O((n+m)log{n}) time (Cormen page 636). In specific, step 7 and step 11 contributes the log{n} element that is iterated over n and m loop. The n log{n}-loop is from the EXTRACT-MIN operation, and the m log{n}-loop is from the "implicit DECREASE-KEY" operation. Both can be replaced with our edge-weight array, a loop of O(k). As such, with our modified Prim's algorithm, we would have a O(nk + mk) = O(k(n+m)) algorithm.


text:
Q: Cant parse json data from twitter api I'm trying to get a list of twitter user names based on the id's, but I can't get jquery to parse to the json data returned by the twitter api. Instead of displaying the names I get: [object Object]. I checked the result and it appears to be valid json data. I need help understanding how to use the data.
Here's the code I'm using:
    $.getJSON('https://api.twitter.com/1/users/lookup.json?user_id=16917715', function(data) {
    var items = [];
      $.each(data, function(key, val) {
        items.push('
' + val + '
');
      });
      $('
', {
        'class': 'twitter-names-list',
        html: items.join('')
      }).appendTo('#follower-names');
});

A: I'm pretty sure you need to be using JSONP instead of JSON. Generally you can't make cross domain ajax calls and that's probably what's failing here. Here's a good article on the subject
IIRC you can simply add &callback=? to your GET request. That would make your request $.getJSON('https://api.twitter.com/1/users/lookup.json?user_id=16917715&callback=?',...
jQuery will replace that ? with a dynamic function to process the data and it should work better for you

A: add &callback=? to the url to retrieve the data
$.getJSON('https://api.twitter.com/1/users/lookup.json?user_id=16917715&callback=?', function(data) {
    console.log(data);
});

A: I haven't used the API, but from looking at https://dev.twitter.com/docs/api/1/get/users/lookup, it appears that the result is an array of objects.  If I'm reading your code correctly, it appears that you are iterating the array, not the objects' properties in the array.  I would wrap your current $.each() call in
for( var x = 0; x < data.length; x++ )
{
    $.each(data[ x ], function(key, val){
    ...
    });
}


text:
Q: ¿Cómo lanzar los mensaje de validación de html a traves de javascript o jquery? Estoy haciendo el envió de un formulario a través de la función submit de jquery, el problema es que no toma en cuenta los campos requeridos y hace el submit incluso cuando estan vacios, esto no sucede cuando se tiene un boton tipo submit en el formulario.
El siguiente ejemplo no toma en cuenta el atributo required en el campo nombre:

$("#btn").on('click', function (){
  $("#main").submit();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="main" name="main" method="post" action="">
      <input id="nombre" name="nombre" type="text" required></input>
      <button id="btn" type="button">ok</button>
</form>

El siguiente ejemplo con un boton submit lanza los mensajes de validacion:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="main" name="main" method="post" action="">
      <input id="nombre" name="nombre" type="text" required></input>
      <button id="btn" type="submit">ok</button>
</form>

¿Como se pueden activar o lanzar estos mensajes de validacion a traves de jquery o javascript?

A: Puedes hacerlo por medio del evento click del boton, comprobar validación, y sí es así realizar tu función.

$("#btn").on('click', function (){
  //verificar que tu formulario esté correcto
  let bandera = $("#nombre") != "";
  //preguntar por tu validación
  if(bandera)
    $("#main").submit();
  else
    alert("No cumple los requisitos");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="nombre" type="text"></input>
<button id="btn" type="button">ok</button>


text:
Q: typeahead.js no errors but not working I am trying to implement typeahead but for some reason, it won't show up.
room.js:
var data = [];
$.get('url_to_json', function(data) {
  data = JSON.parse(data);
});

var students = new Bloodhound({
  limit: 5,
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('global_id'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: data
});

students.initialize();

$('.search_by_name').typeahead({
    highlight: true
  },
  {
    name: 'name_first',
    displayKey: 'global_id',
    source: students.ttAdapter()

  });

room.html:
<input class="form-control search-by-name" placeholder="Ex: smith1jo / 123456" id="id_search" name="search" type="text">

the url that I am accessing is just a django HttpResponse of json in this structure:
[
    {
        'global_id': 'value1',
        'name_first': 'value2',
    },
    {
        'global_id': 'value3',
        'name_first': 'value4',
    },
]

When I go to the page, the javascript console doesn't throw any errors but the type ahead feature just won't show up. I don't notice a difference.

A: You have to call your code only after the document is ready. Wrap everything in a
$(document).ready(function () {
    // your code here
});

and it should work.
Here's a working plunker


text:
Q: Marquee carousel split up in two different row instead of one (cargo collective) As I said I'm building this marquee carousel but the images, instead of one row split up in two.
.marquee {
    color: black!important;
    white-space: nowrap!important;
    overflow: hidden;
    position: relative;
}

{image 1}

{image 2}

{image 3}

{image 4}

{image 5}

{image 6}

{image 7}

{image 8}


text:
Q: What do the Core Data Generated Accessors for an NSOrderedSet look like? I have a NSManagedObject subclass (Parent) that has an ordered to-many relationship with another NSManagedObject subclass (Child). I require Parent to use KVO to watch a value on the Child(ren) held in its NSOrderedSet. This means I need to manually add and remove the Parent as an observer when a Child is added-to or removed-from the set. This means I need to implement my own accessors for the NSOrderedSet.
Where can I see what these accessors should look like?

A: No.  Observe the collection as a whole and allow the OS to handle observation for each child.  Observe the keypath to the property from the vantage point of the parent.  In other words, the parent will be observing itself via a keypath which goes though the children.
[self addObserver: self forKeyPath: @"childs.observedProperty" options: ... context: ...];


text:
Q: Easiest way to implement this SQL query? I have an excel function: =Max(0, -Min(A1-B1, C1-B1))
and A1,B1,C1 are the Value column in the table:
Date, Key, Value
assume for now the Date is irrelevant and the Key is A,B,C for A1,B1,C1
How do I implement this excel function? The way I originally did it I had two joins (to get the values all in separate columns on the same row) but this seemed like overkill and there must be a smarter way?

A: You could probably reduce it to one join, since you only need B for the A part:
select  case
        when min(Value - isnull(yt2.Value,0)) > 0 then 0
        else -min(Value - isnull(yt2.Value,0))
        end
from    YourTable yt1
join    YourTable yt2
on      yt1.Key = 'A' and yt2.key = 'B'
        or
        yt1.Key = 'B' and yt2.key = 'C'

A: Your question is suggesting a separate value for each row.  If so, then this is the query:
select t.*
       (case when -leastval < 0 then 0
             else -lesatval
        end) as TheValue
    end
from (select t.*,
             (case when A1 - B1 < C1 and A1 - B2 < B1 then A1 - B1
                   when C1 < B1 then C1
                   else B1
              end) as leastval
      from table t
     ) t

Now that I read the question right, let me assume that there is one value of A, B, and C per date.  Then you would use a variation on the above, by simply denomalizing the data first:
select t.*
       (case when -leastval < 0 then 0
             else -leastval
        end) as TheValue
    end
from (select t.*,
             (case when A - B < C and A - B < B then A - B
                   when C < B then C
                   else B
              end) as leastval
      from (select date,
                   min(case when key = 'A' then value end) as A,
                   min(case when key = 'B' then value end) as B,
                   min(case when key = 'C' then value end) as C
            from table t
            group by date
           ) t
     ) t

There are other ways to formulate this.  I tried to stay reasonably close to the Excel formulation.
By the way, some other databases offer Greatest() and Least() functions which may such a formula much easier to create.


text:
Q: projection on closed and convex set I have the following question.
Assume we have a Hilbert space $X$ with some inner product $<x_{1}, x_{2} >$ defined on it. Let $X_{c}$ be the subset of $X$ which is a convex cone. Next, we define a projection $P$ of $x \in X$ on the cone $X_{c}$ as
$$
y = Px = \underset{z \in X_{c}}{argmin}<x-z, x-z>.
$$
The question: is $y$ unique?

A: There is a theorem that says that if $C$ is a closed and convex set in a Hilbert space, then there exists a metric projection $P$ onto $C$, defined by the property that for each $x\in H$ there is a unique $Px=y\in C$ such that $|\!|Px-x|\!|$ minimizes the function $|\!|z-x|\!|$ over $z\in C$. Therefore, if your convex cone is also closed, then the answer to your question is affirmative. However, if the cone is not closed, then  there is no guarantee that $Px$ even belongs to the set. For example, take a cone with vertex at the origin, and then remove the origin. The resulting cone is convex, but not closed, and there is no point in it which is closest to the origin. This shows that it does not make much sense to speak about a "projection onto $X_c$" unless you assume that $X_c$ is closed, and then - as indicated above - it is well known that there is a (unique) metric projection onto it. The additional cone structure does not contribute much here.


text:
Q: How to group by one matching element in a subdocument - Mongodb Suppose I have the following collection.
[
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        },
        {
          "@pid": "61",
          "text": "Mango"
        },
        {
          "@pid": "92",
          "text": "cherry"
        },
        {
          "@pid": "27",
          "text": "grape"
        },
        {
          "@pid": "34",
          "text": "dragonfruit"
        }
      ]
    },
    "type": "A"
  },
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        },
        {
          "@pid": "27",
          "text": "grape"
        },
        {
          "@pid": "34",
          "text": "dragonfruit"
        }
      ]
    },
    "type": "B"
  },
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        }
      ]
    },
    "type": "A"
  }
]

I want to get the type in which apple or mango is sold, group by item name. For the above collection, the output would be :
{
    "_id": "Apple",
    "items" : [
        "A",
        "B",
        "A"
    ]
},
{
    "_id": "Mango",
    "items" : [
        "A"
    ]
}

I tried the following query but it return nothing :
db.collection.aggregate([

     {
         $match : {
             'items.item.text' : {$regex : 'Apple|Mango'}
         }

     },
     {
        $project : {
            type : "$type"
        }
     },
     {
         $group : {
             _id : '$items.item',
                types : {$push : '$type'}

         }
     }

 ])

I think that even if this works, it's going to group by the entire 'items.item'. Where am I going wrong?
P.S. : I don't have the liberty to change the format of the document
Thanks a lot in advance.

A: You were on the right direction. You need to use $unwind operator and you don't need $project stage in your aggregation. The below query will be helpful:
db.collection.aggregate([
  {
    $unwind: "$items.item"
  },
  {
    $match: {
      "items.item.text": {
        $regex: "Apple|Mango"
      }
    }
  },
  {
    $group: {
      _id: "$items.item.text",
      type: {
        $push: "$type"
      }
    }
  }
])

MongoPlayGroundLink


text:
Q: How to convert an array to PGLint (ie:^integer) in delphi? I have this openGL function declared in delphi :
PGLint = ^GLint;
GLint = Integer;
glTexParameteriv(target, pname: GLenum; params: PGLint);

in the sample i found on the web this function must be call like this :
int crop_rect[4] = {x, y, width, height};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop_rect);

However i don't know how to translate the crop_rect in delphi ? especially how to pass it to glTexParameteriv ?

A: Like this:
var
  crop_rect: array [0..3] of GLint ;
....
crop_rect[0] := x;
crop_rect[1] := y;
crop_rect[2] := width;
crop_rect[3] := height;
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, @crop_rect[0]);


text:
Q: Hashtag filtering with Ruby on Rails New Rails programmer here.  There is probably a pretty simple solution to this, but I just can't figure it out.  Here's the deal: lets say I have many posts on a single page. Each post has a content field, and some of those content fields contain #hashtags within the content.
I want to develop an algorithm that scans the content of every single post (say, every 2 seconds) and displays a list of every hashtag.  I'm thinking AJAX will be necessary, because the posts feature AJAX edit-in-place.  Thus, if a post is changed and a new hashtag is created, the hashtag list should be updated automatically to reflect this.  Also, each hashtag on the hashtag list should be clickable, sending a search query and in turn displaying the posts that contain the selected hashtag.
This end result is similar to tagging and a tag cloud, but should be dynamic and integrated (as opposed to having a tag field for each post).  I don't want to attach any tags to the posts as a database column.  I just want the application to scan the content of every single post and display a clickable hashtag list.
All suggestions are greatly appreciated.

A: Personally, I would use jQuery to implement the AJAX functionality you need.  Javascript will be used to check the server for new hashtags, and the actual hashtag searching will be done on the server.  In your Post model, you could have something like this to do the actual searching:
class Post < ActiveRecord::Base
  # class methods
  class << self
    def hashtags
      tags = []

      # cycle through all posts that contain a hashtag, and add them to list
      Post.all(:conditions => 'body like "%#"').each do |post|
        tags += post.hashtags
      end

      # remove duplicates and sort alphabetically
      tags = tags.uniq.sort
    end
  end

  # instance methods
  def hashtags
    @hashtags ||= body.scan(/#\w+/)
  end
end

There are two methods here with the same name, but one is called on the class (Post.hashtags) to get all hashtags across all posts, and the second one is called on a single instance (post.hashtags) to get just the hashtags from that post.
There are several other pieces to the puzzle - your controller code, your views, and your javascript.  This question is a tall order for a volunteer site.  You're asking for several different things to be done for you.
My advice is to start building this as I've described, and ask for help on the pieces that you have trouble with along the way.  We're more than happy to help, but you're asking for an entire javascript-driven MVC stack.  Try to limit your questions to something that can be answered in 5-10 minutes, and you're likely to get a lot more feedback and help.
Good luck!


text:
Q: Calendar add method not working as expected I want set a (Gregorian) Calendar time to start-of-day April 1, 2016. I do this by setting month, day and year, and then setting all the time fields to their minimum values, giving me:

04/01/2016 12:00:00:000

If I subtract one millisecond I expect to get the last millisecond on the previous day, but instead I get the last millisecond on the same day:

04/01/2016 11:59:59:999

(Note: I get similar results if I subtract one second, minute or hour.)
What am I missing? Sample code follows, thanks.
    package com.scg.domain;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AdHoc
{
    private static final int[]  UNUSED_CAL_FIELDS   =
    {
        Calendar.HOUR,
        Calendar.MINUTE,
        Calendar.SECOND,
        Calendar.MILLISECOND
    };

    public static void main(String[] args)
    {
        Calendar    cal = getGoodDate( Calendar.APRIL, 1,2016 );
        System.out.println( cal.getCalendarType() );
        adjustTime( "present", cal, 0 );
        adjustTime( "past", cal, -1 );
        adjustTime( "future", cal, 1 );
    }

    private static void adjustTime( String comment, Calendar cal, int incr )
    {
        Calendar    newCal  = Calendar.getInstance();
        newCal.setTime( cal.getTime() );
        newCal.add( Calendar.MILLISECOND, incr );

        SimpleDateFormat    fmt =
            new SimpleDateFormat( "MM/dd/YYYY HH:mm:ss:SSS" );
        System.out.println( comment + ": " + fmt.format( newCal.getTime() ) );
    }

    private static Calendar getGoodDate( int month, int day, int year )
    {
        Calendar    cal = Calendar.getInstance();

        cal.set( Calendar.YEAR, year );
        cal.set( Calendar.MONTH, month );
        cal.set( Calendar.DAY_OF_MONTH, day );

        for ( int field : UNUSED_CAL_FIELDS )
            cal.set( field, cal.getMinimum( field ) );

        return cal;
    }
}

A: You've used Calendar.HOUR, which controls only the 1-12 hour, not the 0-23 hour.  Because of this, even though getMinimum returns 0, it's interpreted as 12:00 in whichever of AM or PM cal already is in, which must be PM from getInstance() (returns "now").  You really have 12:00 noon (PM).  When you subtract a millisecond, it's still the same day.
To set it to midnight, try Calendar.HOUR_OF_DAY, which controls the 0-23 hour.
With this change, I get the output:
gregory
present: 04/01/2016 00:00:00:000
past: 03/31/2016 23:59:59:999
future: 04/01/2016 00:00:00:001


text:
Q: How do I retrieve the name of a variable in JavaScript Ok so let's say I have an assortment of varables:
tab = document.createOjbect('table');
str = 'asdf';
ary = [123, 456, 789];
obj = {a:123, b:456, c:789};

A Piece of code to 'stringify' them:
function Stringify(){
    var con = this.constructor.name;
    if(con == 'String')             return this;
    if(con == 'Arrray')             return this.toString();
    if(con == 'Object')             return JSON.stringify(this);
    if(con == 'HTMLTableElement')   return this.outerHTML;
}

An array containing the variables:
var aVar = [tab, str, ary, obj];

And I loop the array to 'stringify' its content:
for(var i in aVar){
    console.log(
        Stringify.call( aVar[i] );
    );
}

I get the expected list of stringed objects:

asdf
123,456,789
{"a":123,"b":456,"c":789}

But what if I wanted to include the name of the variables in the logs?:
tab:

str: asdf
ary: 123,456,789
obj: {"a":123,"b":456,"c":789}

How would I even go about that?:
for(var i in aVar){
    var id = // get the name of the variable at aVar[i]
    console.log(
        id + ': ',
        Stringify.call( aVar[i] );
    );
}

A: It is not possible, and does not really make sense. You have to understand that functions manipulate values, not variables.
When executing this:
var aVar = [tab, str, ary, obj];

What is put in the array is values, not variables, although it syntactically looks so. The values know nothing about the variables that reference them.
Think about it: a value could be referenced by several variables. What sense would it make to get the access the name of (one of the) variable that has referenced it at some earlier point?
I'm afraid that the only solutions for your use case are to either carry the 'variable name' along your execution flow, or to hardcode your logic for each of the variables.


text:
Q: Show that $\equiv$ is a congruence on $M\times S$ I'm sorry if a similar question has been posted before, but I was unable to find one based on my searches. This is an extra practice problem for a number theory class. I've been trying to prove this out, and I'm getting stuck on the transitivity step. This is also a check on myself to make sure that I understand what I need to demonstrate in order to show a congruence.
Here is the full question. I include the last sentence for extra context:

For a submonoid $S$ of a commutative monoid $(M,*)$, define a relation $\equiv$ on the monoid $M\times S$ by $(a,s)\equiv(b,t)$ if there is a $u\in S$ such that $a*t*u=b*s*u$. Show that $\equiv$ is a congruence on $M\times S$. $M$ is a commutative monoid $M$ and $S$ is an arbitrary submonoid of $M$.

Here's what I've written so far. Since I'm dealing with monoids, I don't think I need the part that starts "And finally" (that only applies to groups). Please let me know if I'm mistaken:

We want to see that $\equiv$ is a congruence. That means we need to demonstrate that $\equiv$ is an equivalence relation. Then we want to see that for any $(a,s),(a',s'),(b,t),(b',t') \in M \times S$, if $(a,s) \sim (a',s')$ and $(b,t) \sim (b',t')$, then $(a,s)*(b,t) \sim (a',s')*(b',t')$. And finally, we want to see that for any $(a,s),(a',s') \in M \times S$, if $(a,s) \sim (a',s')$, then $(a,s)^{-1} \sim (a',s')^{-1}$. Note that $a*t*u=b*s*u$ implies that $u \in S$ is at least right cancellable. And since $S$ is a submonoid of a commutative monoid $M$, $u$ is left cancellable, thus cancellable in general.
First, we'll demonstrate that $\equiv$ is an equivalence relation.
Reflexivity
Suppose that $a*s*u=a*s*u$. Then it follows immediately that $(a,s) \equiv (a,s)$.
Symmetry
Suppose that $a*t*u=b*s*u$. Then $(a,s),(b,t) \in M \times S$, and $(a,s) \equiv (b,t)$. Since $=$ is an equality, we have $(b,t) \equiv (a,s)$.
Transitivity
Suppose that $a*t*u_1=b*s*u_1$ and $b*v*u_2=c*t*u_2$ where $u_1,u_2 \in S$.

At this point, I'm stuck trying to show how $(a,s) \equiv (c,v)$. I've tried writing this out multiplicatively, and I thought I would have to use the fact that $u$ is cancellable, but I don't know how to proceed without violating rules.
For instance, I've written on scratch paper:
$\frac{a}{t}*\frac{1}{u_1}=\frac{b}{s}*\frac{1}{u_1}$ and $\frac{b}{v}*\frac{1}{u_2}=\frac{c}{t}*\frac{1}{u_2}$. I know that I want to be able to say $\frac{a}{v}*\frac{1}{u_3}=\frac{c}{s}*\frac{1}{u_3}$, but I'm not sure how to get there. I've also written this additively but that led to a dead end as well.
Thanks ahead of time for any help / hints / clues.

A: Let $atu_1=bsu_1$ and $bvu_2=ctu_2$ for some $a,b\in M$, $s,t,u_1,u_2\in S$.
Multiplying the first equation by $u_2v$, and noting that multiplication is associative and commutative in this setting, we get
$$(av)(u_1u_2t)=atu_1u_2v=bsu_1u_2v=(bvu_2)u_1s=(ctu_2)u_1s=(cs)(u_1u_2t).$$
Observe that $u_1u_2t\in S$ since $S$ is a submonoid.


text:
Q: drawing a div on top of the rest without using absolute positioning I have the following code

            a
            aa ab

            b
            ba bb

Login

        <form method="post" id="login_form">

login form

        </form>

        <form method="post" id="create_account_form">

create account form

        </form>

content here

The header is about 60px tall and 960px wide, centered in the browser window and sticking to the top of the viewport. When the user clicks on "Login" the #login_container reveals itself. However, I want to position it aligned right with the header row, not aligned to the right of the viewport. I can do that by not using 'position: absolute' when styling #login_container, however, then the login form gets cut-off because the containing #header div is not tall enough. In other words, I want the #login_container aligned with the right edge of #header, but laid on top of #content, if any.

A: You could either set
#header {
 position: relative;
 height: 60px;
}
#login_container {
 position: absolute;
 right: 0;
 top: 60px; /* equal to #header height, if it's not fixed, you should retrieve it dynamically via jQuery */
}

and then dynamically retrieve #content's size and apply it to #login_container.
Otherwise, and maybe even better, you could wrap the whole code in a #container div, set its width to whatever width you wish the site to have, set it centered, then move #login_container from inside #header to immediately after it and with absolute position. You will have a cleaner css code and less meddling to do with jQuery (just setting login_container's height).. so it should be like this (if I'm not missing anything):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento senza titolo</title>

                a
                aa ab

                b
                ba bb

Login

        <form method="post" id="login_form">

login form

        </form>

        <form method="post" id="create_account_form">

create account form

        </form>

    content here

Give it a try and let me know if you still got problems!


text:
Q: jquery find closest element with a known sibling In the following html code ..I have the drop down boxes selected by a value..Now i want to populate the input box next to it..
I use the following code to do it..But how to populate the corresponding text boxes..
var ty =$(".edata");
$(ty).children().find(".kt").html('').append('//Appending values to drop down');
for(var item in key_val_pair)
{
    $(ty).children().find(".kt").removeAttr('selected')
    $(ty).children().find(".kt option:eq("+item+")").prop('selected',true);
    $(ty).children().find(".kt option:eq("+item+")").closest('.e_val').val(key_val_pair[item])
}

EDIT:
 Lets say key_val_pair="{\"1\":\"123\",\"4\":\"456\"}"

HTML

        <select class="kt">
            <option value="1">k1</option>
            <option value="2" >k2</option>
        </select>
        <input type="text" placeholder="val" class="e_val"/>

        <select class="kt">
            <option value="3">k3</option>
            <option value="4" >k4</option>
        </select>
        <input type="text" placeholder="val" class="e_val"/>

A: This is considering you wish to populate the nearest Inputbox with the option picked from the dropdown:

Fiddle: http://jsfiddle.net/3Dtzb/2/

A: $(ty).children().find(".kt").next('input').val('you value');

A: Your problem is with this line:
$(ty).children().find(".kt option:eq("+item+")").closest('.e_val').val(key_val_pair[item])
closest() finds ancestors only, so you are telling it to find an ancestor with class 'e_val' of the option. You really want
$(ty).children().find(".kt option:eq("+item+")").parent().siblings('.e_val').val(key_val_pair[item])
to go up to the  (the parent), then to its associated sibling with class 'e_val'.


text:
Q: Driver.java:55: error: 'else' without 'if' So basically I'm just trying to get this bit of code to work. It used to run when I had the "else" below the two "if" statements. However, when I move it above it gives me the following error:
Driver.java:55: error: 'else' without 'if'

I'd really appreciate some help solving this issue so it'll run again.
     {
        synchronized(someObject)
        {
           someObject.wait();
           System.out.println(ID + " has been notified.");

           Customer customer = null;

           if(Dispatcher.customerRequiresPickUp() && (customer = Dispatcher.queue.poll()) != null && (rideCount >= workFinished))

             System.out.println("Customer has been picked up by driver #" + ID);

             try
              {
                Thread.sleep(rn.nextInt(5000) + 1000);
                System.out.println("Driver #" + ID + " has dropped off " + customer.getName() + " at " + customer.getEndLocation() + ".");
              }
              catch(InterruptedException e)
              {
              }

           else
              System.out.println("Driver #" + ID + " will continue to wait for a customer.");

           if(rideCount >= workFinished)
             onDuty(false);
        }
     }

A: if(Dispatcher.customerRequiresPickUp() && (customer = Dispatcher.queue.poll()) != null && (rideCount >= workFinished))
{

         System.out.println("Customer has been picked up by driver #" + ID);

         try
          {
            Thread.sleep(rn.nextInt(5000) + 1000);
            System.out.println("Driver #" + ID + " has dropped off " + customer.getName() + " at " + customer.getEndLocation() + ".");
          }
          catch(InterruptedException e)
          {
          }
}
else
{
  System.out.println("Driver #" + ID + " will continue to wait for a customer.");
}

You need curly brackets {} if an the body of an if statement is more than one line. Like so ^.


text:
Q: Django - add model field validator in __init__ I need to add a field validator through an abstract class.
The code I'm working with supposes that every class inheriting from this abstract class has a field name, but this field itself isn't defined in the abstract class unfortunately.
So I tried the following, but I'm not sure what is the good way of finding the field in self._meta.fields, since this is a list..??
class AbsClass(models.Model):
    class Meta:
        abstract = True
    def __init__(self, *args, **kw):
        super(AbsClass, self).__init__(*args, **kw)
        name_field = [f for f in self._meta.fields if f.name == 'name'][0]  # Is there another way?
        name_field.validators.append(my_validator)

A: You need Options.get_field:
...
name_field = self._meta.get_field('name')
name_field.validators.append(my_validator)
...

Your approach, however, doesn't seem like a good idea: you model's field instances are shared between all instances of your model (their references are stored in a class attribute, not in instance attributes). This means that every time you instantiate an object of your model, you'll be adding another copy of my_validator to the field's validators, because you're adding it to the same field instance.
You could implement a metaclass for your abstract base class and add the validator at compile time instead of tampering with field instances at runtime, something along the lines of this (not tested):
from django.utils.six import with_metaclass
from django.db.models.base import ModelBase

# inherit from Django's model metaclass
class AbsClassMeta(ModelBase):

    def __new__(cls, name, bases, attrs):
        if 'name' in attrs:
            attrs['name'].validators.append(my_validator)
        elif name != 'AbsClass':
            # is it an error to not have a "name" field in your subclasses?
            # handle situation appropriately
        return super(AbsClassMeta, cls).__new__(cls, name, bases, attrs)

class AbsClass(with_metaclass(AbsClassMeta, models.Model)):
    ...

Note that your AbsClass class itself will also be created using this metaclass. If you decide to throw an exception in AbsClassMeta.__new__ if the class doesn't have a name field, you need to take this into account, since your AbsClass class doesn't have a name field.

A: In Django 2.x
instead of
name_field = self._meta.get_field('name')
name_field.validators.append(my_validator)

you can do:
name_field = self.fields['name']
name_field.validators.append(my_validator)


text:
Q: Participle as verbal adjective I came across the following:

*

*As he had been deceived by his friends he lost all hope.

*He was deceived by his friends and so he lost all hope.

*Deceived by his friends, he lost all hope.

*He lost all hope because he was deceived by his friends.

It was said that only sentence 3 has a participle in it. But all 4 has the word deceived,
Why is "Deceived by his friends, he lost all hope' is said to have participle?

A: Each sentence has a participle: deceived

In linguistics, a participle is a word that shares some characteristics (parts) of both verbs and adjectives.1 It can be used in compound verb tenses or voices (periphrasis), or as a modifier. A phrase composed of a participle and other words is a participle phrase.

saith Wikipedia. But only one has a participial adjective: #3.

A: In sentences 1,2 and 4 'deceived' is used as a verb in different tenses (past perfect in #1 and simple past in #2 and #4). It is used in passive voice so maybe that is why it may appear as a participial adjective. It is used as a participial adjective in #3. As such, it is the Head of Adjectivial Phrase (Deceived by his friends) and describes the Subject(he). Hope this helps.

A: Deceived is still considered a past participle when used adjectivally.


text:
Q: Android Webview not showing full Table My html string contain this code.

Name	 MUAHAMMAD TAHIR SAEED S/O MUHAMMAD SAEED

Address	 111/C AL-REHMAN GARDEN LAHORE

Due Date	 01 DEC 21

Bill Amount
	 5137

Bill Amount After Due Date	 5460

I am using webview to show result of this html code.
webpage.setWebViewClient(new WebViewClient());
        webpage.getSettings().setJavaScriptEnabled(true);
        webpage.loadData(html,"text/html","UTF-8");

This is working correctly in emulator. But in device this webview shows only three rows. why?


text:
Q: How do I make `\item` labels to be computed modulo 4 (to see it on a small example) How do I make \item labels to be computed modulo 4 (to see it on a small example) .
Then I change it to modulo 1000 in my final project.
\documentclass{article}

\usepackage[no-math]{fontspec}

\newfontfamily\ngg{Segoe UI Historic}[Ligatures=TeX]

\usepackage{enumitem}
\begin{document}
\begin{enumerate}[ label=\large\ngg\symbol{\numexpr "13000+\value{enumi}}]

\item this label should be {\ngg\symbol{"13001}} and is such
\item this label should be {\ngg\symbol{"13002}} and is such
\item this label should be {\ngg\symbol{"13003}} and is such
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13004}}
\item this label should be {\ngg\symbol{"13002}} but is {\ngg\symbol{"13005}}
\item this label should be {\ngg\symbol{"13003}} but is {\ngg\symbol{"13006}}
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13007}}
\item etc. 13000+i modulo 4
\end{enumerate}
\end{document}

I apologize for a small typo (in my intended modulo 4 operation) but the idea
should be clear.

A: Firstly, by your example, what you want is modulo 3, not 4. Here is an example making use of enumitem's \AddEnumerateCounter.
\documentclass{article}

\usepackage[no-math]{fontspec}

\newfontfamily\ngg{Segoe UI Historic}[Ligatures=TeX]

\usepackage{enumitem}
\makeatletter
\def\historicCnt#1{\expandafter\@historicCnt\csname c@#1\endcsname}
\def\@historicCnt#1{%
  \ifcase#10\or1\or2\or3%
  \else
    \expandafter\@historicCnt\expandafter{\numexpr#1-3\relax}%
  \fi
}

\AddEnumerateCounter{\historicCnt}{\@historicCnt}{XX}
\makeatother

\begin{document}
\begin{enumerate}[label=\large\ngg\symbol{\numexpr "13000+\historicCnt*\relax}]

\item this label should be {\ngg\symbol{"13001}} and is such
\item this label should be {\ngg\symbol{"13002}} and is such
\item this label should be {\ngg\symbol{"13003}} and is such
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13004}}
\item this label should be {\ngg\symbol{"13002}} but is {\ngg\symbol{"13005}}
\item this label should be {\ngg\symbol{"13003}} but is {\ngg\symbol{"13006}}
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13007}}
\item etc. 13000+i modulo 4
\end{enumerate}
\end{document}

Update
A new latex3 flavored function \iten_mod:nn is defined, it accepts two integers #1 and #2, and returns #1 mod #2 if (#1 mod #2) > 0, otherwise #2. You can use it to accomplish "mod 1000" or similar tasks.
\documentclass{article}
\usepackage{enumitem}
\usepackage[no-math]{fontspec}

\newfontfamily\ngg{Segoe UI Historic}[Ligatures=TeX]

\makeatletter
\ExplSyntaxOn

% register \historicCnt as a new counter representation
\AddEnumerateCounter{\historicCnt}{\@historicCnt}{XX}

% define \historicCnt
\def\historicCnt#1{
  \expandafter\@historicCnt\csname c@#1\endcsname
}

\def\@historicCnt#1{
  \item_mod:nn {#1}{3}
}

% return (#1 mod #2) if (#1 mod #2) > 0 else #2
\cs_new:Nn \item_mod:nn
  {
    1 + \int_mod:nn {#1-1}{#2}
  }

\makeatother
\ExplSyntaxOff

\begin{document}
\begin{enumerate}[label=\large\ngg\symbol{\numexpr "13000+\historicCnt*\relax}]

\item this label should be {\ngg\symbol{"13001}} and is such
\item this label should be {\ngg\symbol{"13002}} and is such
\item this label should be {\ngg\symbol{"13003}} and is such
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13004}}
\item this label should be {\ngg\symbol{"13002}} but is {\ngg\symbol{"13005}}
\item this label should be {\ngg\symbol{"13003}} but is {\ngg\symbol{"13006}}
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13007}}
\item etc. 13000+i modulo 3
\end{enumerate}

\end{document}

A: Here an example that can grow. But I didn't check if your font has 1000 consecutive glyphs starting from 13000, so it is quite possible that you will get missings glyphs somewhere in the middle:
\documentclass{article}

\usepackage[no-math]{fontspec}

\newfontfamily\ngg{Segoe UI Historic}[Ligatures=TeX]

\usepackage{enumitem}
\ExplSyntaxOn\makeatletter
\cs_new_protected:Npn \@moduloitem #1
  {
   \ngg
    \char
     \int_eval:n
      {
        \int_mod:nn{\int_use:c{#1}}{\modulolength}
        +
        \exp_args:No\int_from_hex:n{\modulostart}
      }
  }
\newcommand\moduloitem[1]{\@moduloitem{c@#1}}
\newcommand\modulostart{13000}   %adapt
\newcommand\modulolength{3}      %adapt
\AddEnumerateCounter{\moduloitem}{\@moduloitem}{AA}
\ExplSyntaxOff\makeatother
\begin{document}
\begin{enumerate}[ label=\moduloitem*]

\item this label should be {\ngg\symbol{"13001}} and is such
\item this label should be {\ngg\symbol{"13002}} and is such
\item this label should be {\ngg\symbol{"13003}} and is such
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13004}}
\item this label should be {\ngg\symbol{"13002}} but is {\ngg\symbol{"13005}}
\item this label should be {\ngg\symbol{"13003}} but is {\ngg\symbol{"13006}}
\item this label should be {\ngg\symbol{"13001}} but is {\ngg\symbol{"13007}}
\item etc. 13000+i modulo 4
\end{enumerate}
\end{document}

A: Hook properly in enumitem. I used modulo 3, which is what you actually have in your example.
\documentclass{article}

\usepackage[no-math]{fontspec}

\newfontfamily\ngg{SegoeUIHistoric.ttf}[Ligatures=TeX,Scale=1.2]

\usepackage{enumitem,xparse}

\ExplSyntaxOn
\NewDocumentCommand{\nggcounter}{m}
 {
  \group_begin:
  \ngg
  \symbol
   {
    \int_eval:n { "13001 + \int_mod:nn { \value{#1} - 1 } { 3 } } % change here the modulus
   }
  \group_end:
 }
\ExplSyntaxOff

\makeatletter
\newcommand{\@nggcounter}[1]{#1}
\AddEnumerateCounter{\nggcounter}{\@nggcounter}{{\ngg\symbol{"13001}}}
\makeatother

\begin{document}

\begin{enumerate}[label=\nggcounter*]

\item this label should be {\ngg\symbol{"13001}}
\item this label should be {\ngg\symbol{"13002}}
\item this label should be {\ngg\symbol{"13003}}
\item this label should be {\ngg\symbol{"13001}}
\item this label should be {\ngg\symbol{"13002}}
\item this label should be {\ngg\symbol{"13003}}
\item this label should be {\ngg\symbol{"13001}}
\item etc. 13000+i modulo 3

\end{enumerate}

\end{document}


text:
Q: Is this another way of instantiation in C#? I am new to C# and was attempting to use LiveCharts in a WPF project.  Unfortunately, I got lost on the first example and I can't find any other references to the approach.  To be honest, I'm not even sure I'm searching with the correct terms.
Is the second statement the same as the first?
And when would you use one over the other?
The method I am familiar with:
SeriesCollection seriesCollection = new SeriesCollection();

The code I am struggling to understand:
void MyMethod()
{
    SeriesCollection = new SeriesCollection { };
}
public SeriesCollection SeriesCollection { get; set; }

A: The first method declared a class variable and assigns a new object to it.
The second method assigns a new object to a declared property in the class. There is a shorter form of this type which would look like this:
public SeriesCollection SeriesCollection { get; set; } = new SeriesCollection();

There is a difference between a member variable and a property, otherwise it's essentially the same thing.

A: There are three syntaxes for initialising objects.
There's the constructor call syntax:
var a = new A();
var b = new A(123);

There's the object initialisation syntax:
The code
var a = new A { Foo = 1, Bar = 2 };

Is shorthand for:
var a = new A();
a.Foo = 1;
a.Bar = 2;

For the most part it is carried out exactly like that (so the empty constructor is called first, then the properties are set) with the exception of anonymous types (where a hidden constructor is what is actually hit).
You can even combine the two:
var a = new A(123){ Foo = 1 };

You are allowed to leave out the () if you use the {} but don't have too.
The third way is the collection instantiation syntax:
var l = new List<int>{1, 2, 3};

Which is equivalent to:
var l = new List<int>();
l.Add(1);
l.Add(2);
l.Add(3);

You can do this on any type that both implements IEnumerable and has an appropriate public Add() method.
Again, this can be combined with the constructor () but you can leave out the () if they are empty.
In the case of a type that had both settable properties and also implemented IEnumerable and had at least one public Add() method, then an empty {} is ambiguous as to whether it's the object initialiser or a collection initialiser, but since an object initialiser that sets no properties and a collection initialiser that adds no elements have the same result, it's an ambiguity that doesn't matter, and is allowed.
As a matter of style, I'd generally recommend against the empty {} in favour of the empty (), but if it's a type you are more often initialising with {} then the empty {} can seem more in keeping with the rest of your code.


text:
Q: Using Https Protocol for downloading data from Flickr Since June 2014,  all API keys just work via HTTPS only.Flickr deprecate non-SSL access to the API. There is another Post, but It's for 6 years ago which is before this event.
I know how to download data from Flickr, and I know it should work, but the problem is the library doesn't support Https.
I am trying to count the number of Images that have been shared by a user. I used getPeopleInterface().getPublicPhotos(userId,100,1) method.
but the problem is, it returns back Error 403 for URL!
I checked the Url in browser, and the Error is "SSL is required."
So I changed http to https in the URL and it worked. I do not know how I can change it in my code.
public class GetUsersPhotos {
       public static void main(String[] args) throws Exception{

            String key = "";
            String secret = "";
            String userId = "78069284@N00";

            Transport t = new REST();
            Flickr f = new Flickr(key, secret, t);

            PhotoList list = f.getPeopleInterface().getPublicPhotos(userId,100,1);
            System.out.println(list);
        }

}

A: I solved my problem. The Flickrapi 1.2,doesn't support Https Protocol. What I did I downloaded Flickr4Java.jar which I checked and support Https, and then add the latest log4j jar file. then, it works.


text:
Q: Click and Mousedown Jquery 1.9.1 I am using jquery 1.9.1 and I have a parent element with two child elements. When I add a handler to the parent element using mousedown() and a handlers to the children using click() only the parent fires. When I add handlers for all three using mousedown() they all fire like I expect them to.
What about the first case prevents a click event from being dispatched.
here is a vanilla javascript example of it not working
http://jsfiddle.net/Nxn56/8/

A: Try something like this:
$(#parent).on('mousedown', function(e){
    e.stopPropagation();
    alert("Mouse Down on Parent");
});
$(#child).on('click', function(e){
    e.stopPropagation();
    alert("Click On Child");
});


text:
Q: Bayesian linear regression - Defining hyperparameters I am currently working on a linear regression task from a textbook and I have some questions. In the following you will find the task as well as some thoughts of mine to possible results.
Short description: A quadratic regression analysis shall be made for temperature data from France. The explained variable is given by:

The conjugate prior is:

a) In the first task I shall determine the prior hyperparameters to suitable values:

I can think about the prior mean as a guess of the average temperature in France (lets assume 20°C). But I can not make a sense out of the other parameters. How do I define the prior precision as well as the degrees of freedom and what are they telling me? I know that $\sigma^2$ can be derived from the Inv-$\chi^2$ distribution but how do I estimate $s_0^2$?


text:
Q: Rest API - Download times out without any errors I am downloading ContentVersions through Salesforce using Rest API. I have submitted several file requests and downloaded.
After downloading, an observation was that the ContentSize field in ContentVersions does not correlate with the downloaded file size.
For example,
I had a file that has ContentSize of "1,329,401,752" but when submitted or downloaded through Curl request, the file size on disk/actual size is "1,170,964,557 bytes". How is this possible? This was not synonymous with smaller files < 700 Mb where the content size does match. Has anyone had an issue with downloading files using rest api for larger files?
Edit:
Found out that there is a Rest API timeout in Salesforce for retrieving the responses. Salesforce shuts down the response after the timeout and there are no header responses. However, the http might throw chunkedencoding exception or truncated chunk exception. The default timeout is 10 minutes. Have to call Salesforce support to extend the timeout for Rest APIs. It seems that there is no way to configure the timeouts through Rest APIs or even through Salesforce web interface.


text:
Q: How to lossless optimize images with plugins for grunt-contrib-imagemin? I am trying to lossless optimize JPEG / PNG images with imagemin, but I have a problem when using extensions, they "deoptimize", meaning the result image is bigger than the original. How can I prevent this?
This is my Gruntfile.js
...
grunt.initConfig({
    imagemin: {
        jpeg: {
            options: {
                //by default it uses imageminJpegtran
                progressive: true,//default false, progressive JPEG is better compression https://superuser.com/questions/463477/progressive-jpeg-quality-compare-to-normal-jpeg
                arithmetic: false,//true breaks image

                //don't know how to use it loseless without making the images even bigger
                // use: [
                //  imageminMozjpeg({
                //      quality: 95, //Compression quality, in range 0 (worst) to 100 (perfect).
                //      dcScanOpt: 2,//2 Optimize between one scan for all components and one scan for 1st component plus one scan for remaining components
                //      arithmetic: false// false, or it breaks the image
                //  }),
                // ],
            },
            files: [{
                expand: true,
                cwd: '/www',
                src: ['**/*.{jpg,jpeg,JPG,JPEG}'],
                dest: '/www',
                filter: 'isFile'
            }]
        }
    }
});
...

A: You have the answer in the title of your question – "grunt-contrib-imagemin". If you google it you will find this page on GitHub for Grunt.js as official Grunt GitHub site. On this page it is all described very detailed.
For example:
For imagemin OptiPNG plugin:

optimizationLevel (It is for PNG (for OptiPNG plugin) and NOT FOR JPG!)
  Type: number
  Default: 3
  Select optimization level between 0 and 7.
The optimization level 0 enables a set of optimization operations that require minimal effort. There will be no changes to image attributes like bit depth or color type, and no recompression of existing IDAT datastreams. The optimization level 1 enables a single IDAT compression trial. The trial chosen is what OptiPNG thinks it's probably the most effective. The optimization levels 2 and higher enable multiple IDAT compression trials; the higher the level, the more trials.
Level and trials:

*

*1 trial

*8 trials

*16 trials

*24 trials

*48 trials

*120 trials

*240 trials

Do not try to use optimizationLevel for JPG! For JPG and PNG you will find different optimisation options. All the types of this optimization levels options are full described on the plugins sites (see the plugins listing below).
On this site you have a lot of plugins for different image types optimisation. In your case they are JPG and PNG (you have there also for WebP, Gif and SVG):
Plugins for JPG optimization:

*

*jpegtran plugin for imagemin

*mozjpeg plugin for imagemin

*jpegoptim plugin for Imagemin
Plugins for PNG optimization:

*

*pngquant plugin for imagemin

*pngout plugin for imagemin

*optipng plugin for imagemin

*pngcrush plugin for imagemin

*AdvPNG plugin for imagemin
All PNG plugins have different optimization levels options. For example for AdvPNG plugin you have an optimizationLevel as option and you can select an optimization level between 0 and 4:

0 Don't compress
1 Compress fast (zlib)
2 Compress normal (7z)
3 Compress extra (7z)
4 Compress extreme (zopfli)

JPG optimization
And for JPG optimization I would like to recommend the mozjpeg and jpegoptim plugins because they have a lot of options for configuration – see the links for this plugins above.
Example of usage from plugins
const imagemin = require('imagemin');
const jpegoptim = require('imagemin-jpegoptim');
//const mozjpeg = require('imagemin-mozjpeg');
const pngquant = require('imagemin-pngquant');

(async () => {
    const files = await imagemin(['images/*.{jpg,png}'], 'build/images', {
        plugins: [
            //jpegoptim plugin for JPG
            jpegoptim({
                progressive: true, //Lossless conversion to progressive.
                max: 80 //try to set with and without this option
                //see other options on plugin site (link above) and take / add which you need
            }),
            /* As comment because on plugin page is nothing about lossless conversion
            // mozjpeg plugin for JPG
            mozjpeg({
                quality: 80
                //see other options on plugin site (link above) and take / add which you need
            }),*/
            //pngquant plugin for PNG
            pngquant({
                quality: [0.7, 0.8]
                //see other options on plugin site (link above) and take / add which you need
            })
        ]
    });

    console.log(files);
    //=> [{data: <Buffer 89 50 4e …>, path: 'build/images/foo.jpg'}, …]
})();

Source
For PNG lossless conversion try also to use the AdvPNG plugin without any options. optimizationLevel option for AdvPNG plugin is by default setted to 3 (from 0 to 4).
Advanced reading
It is very important to read the article:

*

*A guide to PNG optimization

A: You can use the optimizationLevel option. This value ranges from 0 to 7, with 3 as the default.
For instances:
imagemin: {
   dist: {
      options: {
        optimizationLevel: 5
      },
      files: [{
         expand: true,
         cwd: 'src/images',
         src: ['**/*.{png,jpg,gif}'],
         dest: 'dist/'
      }]
   }
}

In this example the images optimized are those with the extension png, jpg, or gif, and located in the "src/images" folder and all its subfolders. The result of the optimization will be stored in the "dist" folder.
Adapted from here.


text:
Q: Can't run two RFID readers off the same 5V rail I have a circuit consisting of an Arduino Mega2560 connected to a 134.2kHz RFID reader from Priority1Design. The RFID reader works fine by itself, however as soon as other components are connected to the 5V rail it stops reading data.
I've done some measurements and the current going to the reader does not ever exceed 35mA and the voltage sits around 5V. When another component is connected to 5V and GND (say, another one of the same RFID readers without Tx and Rx connected), the voltage over the original RFID reader drops by about 50mV and the current remains the same (the Mega can provide more than enough current for both of the RFID readers).
I've performed some experiments where I try reading with both readers connected, then I unplug the second one and the first one will start reading again. I've also tried connecting decoupling capacitors between the 5V and GND pins of each of the readers (as close to the reader as possible), but nothing changed.
Here's a schematic of the effective circuit:

simulate this circuit – Schematic created using CircuitLab
When SW1 is open, RFID1 reads properly. When SW1 is closed, it cannot read. I've also noticed that when I probe Tx or Rx with an oscilloscope, it cannot read anything either.
If anyone has any suggestions as to how to fix this, it would be greatly appreciated.


text:
Q: icon already includes gloss effects not working ios 5 i am setting my project info-plist file icon already includes gloss effects key to set yes.but,does not work in iOS5 sdk and i am try to build and clean my project folder but,does not work i have tried lot of ways but, doesn't work on ios5 sdk and Xcode 4.2.3.i am setting my project info-list like below screen shot:

Thanks in Advance!

A: As you already got your answer, for users of Xcode 4.2 (Snow leopard) Dinesh's solution won't work. Here you can right-click on the info.plist file, and open as source code.
Look for this, and replace <false/> with <true/>  under <key>UIPrerenderedIcon</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>iconNormal.png</string>
            <string>iconRetina.png</string>
        </array>
        <key>UIPrerenderedIcon</key>
        <true/>
    </dict>
</dict>

A: Most of iOS 5 icon Bugs on the xcode latest version below post my anser will work for me perfectly, i am added prerender checkbox tick project target summary!
follow link must will be help ful!
Icon already includes gloss effects
Welcome!

A: Just drag and drop the icon image in to place, here is the sample screenshot


text:
Q: Vue JavaScript create variable from an other variable value I can't find how to create a variable from another variable value.
I get this variable from AJAX call (using vue-resources):
langs: {1:'fr', 2:'en', 3:'ar'},

But, I don't know how many properties langs will have.
How can I get this variable dynamically:
newVar: {
  has_lang: '1',
  values: [{ is: 'fr', val:''}, { is: 'en', val:''}, { is: 'ar', val:''}]
},

So in newVar, the fr, en, and ar properties have been generated automatically using the values in langs.
I am planning to use the values array to bind to the values of my md-input inputs using v-model:
<md-input-container v-for="value in newVar.values">
  <label>@{{ attribute.attribute }} @{{ value.is }}</label>
  <md-input v-model="value.val"></md-input>
</md-input-container>

Is doing this manipulation the best practice? Because I can't find a solution which uses v-model for inputs that are generated from a v-for loop.

A: Use a watcher to set the newVar property whenever the langs property changes. You'll need to also do this during the mounted lifecycle event if you are passing in the langs variable as a prop or defining it within data().
In your case, I'd add a method to call at both points:
data() {
  return {
    langs: {1:'fr', 2:'en', 3:'ar'},
    newVar: {},
  };
},
methods: {
  updateValues() {
    let newVar = {
      has_lang: (this.langs !== {}) ? '1' : '0',
      values: [],
    };

    for (let lang in this.langs) {
      newVar.values.push({ is: this.langs[lang], val: '' });
    }

    this.newVar = newVar;
  }
},
watch: {
  langs() {
    this.updateValues();
  }
},
mounted() {
  this.updateValues();
}

Here's a CodePen.


text:
Q: How to cast a class to an interface using generics in c#? I've this interface:
public interface IRepository<T>
{
    List<T> List();
    T Get(int Id);
    bool Add(T entity);
    bool Update(T entity);
}

And I've this class:
public class Customer<T> : IRepository<Entities.Customer>
{
   public Entities.Customer Get(int Id)
   {
      var c = new Entities.Customer();
      return c;
   }

   //continue...
}

How can I cast a generic class to a generic interface like so:
//Other method
public IRepositorio<T> DoStuff<T>(int Id)
{
   var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T)); // ok
   var b = (IRepository<T>)Activator.CreateInstance(typeof(T)); // Exception: unable to cast

   return object; // an object
}

And I call from this MCV controller:
  public ActionResult Home()
  {
     var repo = new Repository();
     repo.DoStuff<Customer<Entities.Custormer>>(10);

     return View();
  }

My conception is ok? This is possible without dynamic?

A: Based on the code supplied, I've tried the following which compiles OK
public class Entities {
    public class Customer {
    }
}

public interface IRepository<T> {
    T Get(int Id);
}

public class Customer<T> : IRepository<Entities.Customer> {
    public Entities.Customer Get(int Id) {
        var cliente = new Entities.Customer();
        return cliente;
    }
}

public class foo {

    public static IRepository<T> DoStuff<T>(int Id) {
        var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T));
        var b = (IRepository<T>)Activator.CreateInstance(typeof(T));

        return b; // an object
    }

}

However, I'm not sure what T is meant to be.  When I run and call
foo.DoStuff<Entities.Customer>(0);

then I get a runtime error on the var a line, because the class Entities.Customer does not implement the interface IRepository<T>.  If I call
foo.DoStuff<Customer<Entities.Customer>>(0);

then I get the runtime error on the 'var b' line, because the class Customer<Entities.Customer> implements IRepository<Entities.Customer> and not IRepository<Customer<Entities.Customer>>
Both exceptions are correct, so hopefully the author of the question can work out where the problem lies from this answer.

A: Activator.CreateInstance(typeof(T)); - this creates for you new instance of T, which is Entities.Customer in your example, but it looks like you want to create instance of Customer<Entities.Customer>.


text:
Q: probability that two randomly selected numbers are equal I have two sets, say $S_1 = \{1, ..., n\}$ and $S_2 = \{0, 1, ..., n - 3\}$
How do I find the probability that randomly selected numbers $n \in S_1$ and $m \in S_2$ are equal?

A: Well, your elementary event implies selecting of a number from $S_1$ and another (maybe equal, maybe not) number from $S_2$. There are $n\cdot(n-2)$ such events, and $n-3$ of them lead to the desired outcome (i.e., that the numbers are equal). Hence the probability in question is $n-3\over n(n-2)$.

A: There is $n$ elements in $S_1$ so the probability of picking any element would be $\frac{1}{n}$. In $S_2$ there is $n-2$ elements so the probability would be $\frac{1}{n-2}$.
$$P=\frac{1}{n^2-2n}$$


text:
Q: Atomic layer deposition applications? What unexplored areas (known unknowns) are there in atomic layer deposition (ALD)? What unexplored applications of ALD are there? It seems like people use it a lot for coatings of either insulators or sometimes transparent conducting contacts. What else could you do with it?

A: "Other applications with similar demanding requirements outside of the semiconductor industry are low electron leakage dielectrics for magnetic read/write heads... and diffusion barrier coatings with low gas permeability..." (http://chem.colorado.edu/georgegroup/images/stories/300.pdf )

A: I can't answer for the unknown part of your question but it is also used for semiconductors and photopholtaic panels.


text:
Q: Convert LocalDateTime to Date with 0 offset I'm trying to figure out how to convert a LocalDateTime to a Date object with a 0 offset.
The current code I'm using converts LocalDateTime to Date is:
Date.from(localDateTime.toInstant(ZoneOffset.UTC))
LocalDateTime:
2016-12-07T16:29:12.218
After being converted to Date:
2016-12-07T10:29:12.218-0600
Yes, I see there is a zone offset being passed into toInstant but i'm not sure how to do what i'm asking for.
UPDATE:
I just received more information on my problem saying to set the date with precision and a zone of UTC to make the offset 0.

A: Looks like you are trying to convert LocalDateTime to Date at your system zone. So, try this instead
Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())