text:
Q: How do I download a raw file from my IBM Cloud Git Repos and Issue Tracking repository? I'm trying to download a raw file from one of my IBM Cloud Git Repos and Issue Tracking repositories.  I had a script that was able to fetch raw file contents using the following curl command:
curl -H "Private-Token: $PERSONAL_ACCESS_TOKEN" https://git.ng.bluemix.net/:owner/:repo/raw/:branch/:filename

but it recently started failing with a 302 response that is redirecting to a UI login page.
Is there a supported way to download raw file contents from an IBM Cloud Git Repos and Issue Tracking repository?

A: The curl request above is attempting to use a personal access token to authenticate to a UI endpoint.  There was a security fix in GitLab 11.3.11 that limited the scope of personal access tokens to API calls only.  That would explain why personal access tokens are no longer working on that request.
The supported method of downloading raw file contents would be to call the repository files API.
For example, to fetch myFolder/myFile.txt from the master branch of myRepo, owned by myUser, you can make a curl call like this:
curl -H "Private-Token: $PERSONAL_ACCESS_TOKEN" https://git.ng.bluemix.net/api/v4/projects/myUser%2FmyRepo/repository/files/myFolder%2FmyFile.txt/raw?ref=master


text:
Q: Check if mouse is inside the game window I'm using XNA to visualize a 3D scene in a window (= not full-screen). The user can click and drag the mouse to move the camera:
Public Sub New()
    ...
    Me.IsMouseVisible = True
    Me.Window.AllowUserResizing = True
    ...
End Sub

Protected Overrides Sub Update(ByVal gameTime As Microsoft.Xna.Framework.GameTime)
    Dim m = Mouse.GetState()

    ' Change camera position based on m
    ...
End Sub

This works. The problem is that this even works when the mouse is not inside the game window, which looks a bit strange (I move a mail in Outlook and the 3D scene in the other window starts turning).
I didn't find a Mouse.IsInsideGameWindow() property. Is there anything else that I can (easily) do to avoid this?

A: bool IsMouseInsideWindow()
{
    MouseState ms = Mouse.GetState();
    Point pos = new Point(ms.X, ms.Y);
    return GraphicsDevice.Viewport.Bounds.Contains(pos);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS @keyframe animation flickers on hover Looking for help! I'm having a flickering issue with the keyframe animation I made for the hover state. I'm using Squarespace and adding custom code to the site. Designer by trade so forgive my code, I'm stuck.
View site here: https://dingbat.co/new-fonts
Flicker Issue on Hover

img {
  max-width:100%;
}

img:hover{
  opacity: 1 !important;
  animation: bruxism 1s infinite;
  animation-timing-function: steps(100);
}
@keyframes bruxism{
    0%   { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
    8%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'); }
   16%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png');}
   24%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'); }
   32%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'); }
   40%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'); }
   48%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'); }
   50%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'); }
   58%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'); }
   66%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'); }
   74%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'); }
   82%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png'); }
   90%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'); }
   98%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
  100%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
}

body {
  background:#000;
}

A: If you are intrested you can approximate this using only CSS with text-stroke. You simply need to update with the correct font-family:

body {
  background:#000
}

.logo {
   font-family:monospace;
   text-transform:uppercase;
   font-size:60px;
   color:#fff;
   animation: bruxism 1s infinite steps(6);
}

@keyframes bruxism{
   0% {
     -webkit-text-stroke:1px #fff;
             text-stroke:1px #fff;
  }
  20% {
     -webkit-text-stroke:2px #fff;
             text-stroke:2px #fff;
  }
  40% {
     -webkit-text-stroke:3px #fff;
             text-stroke:3px #fff;
  }
  60% {
     -webkit-text-stroke:4px #fff;
             text-stroke:4px #fff;
  }
  80% {
     -webkit-text-stroke:5px #fff;
             text-stroke:5px #fff;
  }
  100% {
     -webkit-text-stroke:6px #fff;
             text-stroke:6px #fff;
  }
}

bruxism

Or make sure to load all your images initially to make them ready on hover and avoid the flicker:
I considered an empty pseudo element where I apply all the images as background to force the browser to fetch them

html:before {
  content:"";  background:url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'), url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png');
}

img {
  max-width:100%;
}
img:hover{
  opacity: 1 !important;
  animation: bruxism 1s infinite;
  animation-timing-function: steps(100);
}
@keyframes bruxism{
    0%   { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
    8%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'); }
   16%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png');}
   24%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'); }
   32%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'); }
   40%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'); }
   48%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'); }
   50%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4440f56e45feecd847/1589152580316/Brux1.png'); }
   58%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b47b2acbe6aa4f0715f/1589152583216/Brux2.png'); }
   66%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4a0f826758a3cff34f/1589152586700/Brux3.png'); }
   74%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b4d2ffa577e027396e2/1589152589870/Brux4.png'); }
   82%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b51c673416ea88b386c/1589152593259/Brux5.png'); }
   90%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b54655c7270e62be6c0/1589152597813/Brux6.png'); }
   98%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
  100%  { content: url('https://static1.squarespace.com/static/54dfad58e4b0d9caed78a9a9/t/5eb88b57d4d3cc5898fb517d/1589152599764/Brux7.png'); }
}

body {
  background:#000;
}


text:
Q: Unable to run a POST action in play framework 2.2 I have a similar problem to this person and I am unsure why.
my post action is called from a form submission and the controller code
  def processFreeDoc = UserAwareAction {
    implicit request => {
      userEmailForm.bindFromRequest.fold(
        formWithErrors => {
          Logger.error("Error processing the form %s "format formWithErrors.errors)
          Redirect(routes.Application.index)
        },
        data => {
          val sessionProduct = getSessionUnProcessedProduct(data.sessionId, data.documentName)
          if(sessionProduct != null){
            Logger.info("Found")
            sessionProduct.updateProcessing(data.emailAddress, data.sessionId)
            Redirect(routes.Application.index)
          }
          else
            Logger.info("Nothing found")
            Redirect(routes.Application.checkoutFree(data.sessionId))

        }
      )

    }
  }

is skipped entirely. There are no errors in the IDE(IDEA) console and the breakpoint at the entry of the method is not reached so none of the log messages are seen.
EDIT :
The relevant route in the routes file - POST /processFreeDoc                   controllers.Application.processFreeDoc


text:
Q: how to update git client to overcome the latest vulnerability? Recently GitHub recommended us to update the git client on our machines.
news on vulnerability
So I type in console
git --version     //getting 2.0.1
which git     //getting /usr/local/git/bin/git

Then I upload one from here(2.2.1, for instance):
The Git core team site
I unzip it and then I cant figure it out where to put unzipped files because files under /usr/local/git are so different,
what do I need to do to install it?
Update: for everyone curious about my question, this particular link have the answers

A: Since you appear to be using Linux (or maybe Max OSX) you'll need to use one of the package managers. The Download page for Git on Linux has more information.
For Mac OS you'll need to use Homebrew or MacPorts.
Otherwise you'll have to download the source code, make and make install the newest version of Git if the Linux and Mac package managers don't have the newest release listed.
Installing Git


text:
Q: CoreData Related data in a tableviewcell I am working on a project with related entities in CoreData.  I want to have a tableview with cells that show attributes of records from a related entity, but am struggling to find a good way to do this.
Here's the basics:
My custom TableViewCell has five things:
UILabel *eventTime
UILabel *person1Name
UIImageView *person1Image //storing a string
UILabel *person2Name
UIImageView *person2Image //storing a string

Event entity has a time, person1Name, and person2Name attributes and a to-many relationship to my Person entity.
Person entity has string attributes for name and image and a to-many relationship to my Events entity.
Events will always have two related person records.
Persons will be affiliated with many events.
In my cellForRowAtIndexPath, how do I configure the cell so that the related person attributes show for each event?
I was playing with this:
EventsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EventCell" forIndexPath:indexPath];
Event *event = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSSet *persons = event.eventPersons;  //eventPersons is the NSSet in the NSManagedObject subclass…

// Configure the cell...

for (Player* p in persons) {
    if (p.firstName == event.person1Name) {
        cell.player1NameLabel.text = p.firstName;
        cell.player1ImageView.image = [UIImage imageWithContentsOfFile:p.playerImage];
    } else if (p.firstName == event.person2Name) {
        cell.player2NameLabel.text = p.firstName;
        cell.player2ImageView.image = [UIImage imageWithContentsOfFile:p.playerImage];
    }
}

But I may have multiple people with the same first name, so this fails to work properly in all cases.  I don't want to store a bunch of duplicate information in the Event entity for comparing records and would prefer a more elegant way to grab the attributes of the two related person records in each cell.
Thanks.

A: You already have duplicate information in the storage of the names. But your problem is that they aren't unique.
So, change them to be unique (I.e. Use a different identifier than the name) or use a different method of recording first and second (I.e. Use an ordered relationship).


text:
Q: serialize post from form inside colorbox I am trying to serialize form data from a form that is inside color-box. I get the form to submit but the form data isn't there.
Here is what I am using to try to get the form data.
 $("#submitForm").live("click",function(){
  var data = $(this).closest("form").serialize();
   $.ajax({
        type: "POST",
        url: "update_cc.php",
        data: "data="+data,
        success:function(data){
            $().colorbox({html: data, open:true});
        }
      });
    return false;
  });

Has anybody used colorbox with a form inside of it?

A: Have you checked to make sure that 'data' is what you expect it to be, because your call to colorbox looks fine to me.  It would help to see an actual link.

A: You shouldn't be doing this:
data: "data="+data,

It should just be
data: data,

serialize() will already give you the form controls in the form of name=value pairs separated by &.


text:
Q: convert string into class name in rails I have a variable handler whose value can be flight_gds, flight_commission etc.
There are classes in my application which has names like FlightGds, FlightCommission etc. under module FlightManager.
I want to execute the function of class based on the value of the handler.
The function name is same in all classes, only the class name is different which is dependent on
the handler.
For example:
If handler name is 'flight_gds', then the function is FlightManager::FlightGds.calculate()
I am trying something like this:
FlightManager::handler.camelize.calculate()

But I am getting undefined method handler error.
Is there any way to do this or I should go with if/else loop?

A: You should use constantize to get a class based on it's name in string:
"FlightManager::#{handler.camelize}".constantize.calculate())


text:
Q: HTMLbody to keep cell format I have a script sending out HTML formatted emails to the list of recipients:

Hi there,

Please provide the weekly status report by Monday, CoB:

  <?= project ?>

 Should you have any questions or experience difficulties, reach out to me.

Best regards,

PMO Team

The     reference in the code takes data from respective column ( htmlBody.project = row[3]) :
function sendEmailForm() {
  var htmlBody = HtmlService.createTemplateFromFile('mail_template');

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("T_TEST");
 var startRow = 2; // First row of data to process
  var numRows = 70; // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 11);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[i];
    {
    var emailAddress = row[0]; // First column
     if (emailAddress.match('@')  === null){
       continue;  // skip this iteration of the loop and go to the next one
    };
    var ccEmailAddress = row[1]
   // var body = row[3]; // Second column
    var subject = row[2];
   htmlBody.project = row[3];
    //htmlBody.survey = row[10];
   var message = htmlBody.evaluate().getContent();
    //var body = email_html;
    var aliases = GmailApp.getAliases()
    Logger.log(aliases); //returns the list of aliases you own
    Logger.log(aliases[1])
    GmailApp.sendEmail(emailAddress, subject, message, {htmlBody : message, cc: ccEmailAddress,'from': aliases[1]});
  }
  }
}

However, data in those cells are organized in paragraphs, e.g.:
Project 1
Project 2
Project 3
What I actually get in the emails is: Project 1 Project 2 Project 3
Is there any way to keep cell format in the emails? Thanks in advance for any help

A: In that case, as a simple modification, how about the following modification?
Modified script:
Please modify sendEmailForm() as follows.
From:
htmlBody.project = row[3];

To:
htmlBody.project = row[3].replace(/\n/g, "
");

And also, please modify the HTML as follows.
From:
<?= project ?>

To:
<?!= project ?>

*

*By the above modification, Project 1\nProject 2\nProject 3 in a cell is converted to Project 1
Project 2
Project 3 and this HTML is put using <?!= project ?>.

Reference:

*

*Force-printing scriptlets


text:
Q: overriding with difference access specification c++ I came across a question while taking iKM test. There was a base class with two abstract methods with private access specifier. There was a derived class which was overriding these abstract methods but with protected/public access specifier.
I never came across such thing where overridden methods in derived class had different access specification.  Is this allowed ? If yes, does it comply to "IS A" relation between base and derived (i.e. safely substitutable).
Could you point me to some references which can provide more details on such usages of classes ?
Thank you.

A: It is allowed, in both directions (ie, from private to public AND from public to private).
On the other hand, I would argue it does not break the IS-A relationship. I base my argument on 2 facts:

*

*using a Base& (or Base*) handle, you have exactly the same interface as before

*you could perfectly (if you wish) introduce a forward method that is public and calling the private method directly anyway: same effect with more typing

A: Yes, this is legal, accessibility is checked statically (not dynamically):
class A {
public:
    virtual void foo() = 0;
private:
    virtual void bar() = 0;
};

class B : public A {
private:
    virtual void foo() {} // public in base, private in derived
public:
    virtual void bar() {} // private in base, public in derived
};

void f(A& a, B& b)
{
    a.foo(); // ok
    b.foo(); // error: B::foo is private
    a.bar(); // error: A::bar is private
    b.bar(); // ok (B::bar is public, even though A::bar is private)
}

int main()
{
    B b;
    f(b, b);
}

Now, why would you want to do that? It only matters if you use the derived class B directly (2nd param of f()) as opposed to through the base A interface (1st param of f()).
If you always use the abstract A interface (as I would recommend in general), it still complies to the "IS-A" relashionship.

A: As many of the guys pointed out it is legal.
However, "IS-A" part is not that simple. When it comes to "dynamic polymorphism" "IS-A" relation holds, I.e. everything you can do with Super you can also do with Derived instance.
However, in C++ we also have something that is often referred as static polymorphism (templates, most of the time). Consider the following example:
class A {
public:
    virtual int m() {
        return 1;
    }
};

class B : public A {
private:
    virtual int m() {
        return 2;
    }
};

template<typename T>
int fun(T* obj) {
    return obj->m();
}

Now, when you try to use "dynamic polymorphism" everything seems to be ok:
A* a = new A();
B* b = new B();

// dynamic polymorphism
std::cout << a->m(); // ok
std::cout << dynamic_cast<A*>(b)->m(); // ok - B instance conforms A interface
// std::cout << b->m(); fails to compile due to overriden visibility - expected since technically does not violate IS-A relationship

... but when you use "static polymorphism" you can say that "IS-A" relation no longer holds:
A* a = new A();
B* b = new B();

// static polymorphism
std::cout << fun(a); // ok
//std::cout << fun(b); // fails to compile - B instance does not conform A interface at compile time

So, in the end, changing visibility for method is "rather legal" but that's one of the ugly things in C++ that may lead you to pitfall.

A: Yes, this is allowed as long as the signature is the same. And in my opinion,  yes, you're right, overriding visibility (for example, public -> private) breaks IS-A. I believe Scott Myers Effective C++ series has a discussion on this one.


text:
Q: Directive attribute binding with Bootstrap tooltip I am having an issue where the ternary operator for the glyphicon class switching works just fine but doesn't seem to work on my custom tooltip directive. It just stays with the default Add Project and won't switch to Update Project. It obviously has something to do with my custom directive. Do I need to force a $digest cycle or add a $watch? I'm relatively new to Angular and would greatly appreciate some assistance on this one.
HTML:
<span class="glyphicon glyphicon-{{ currentproject ? 'arrow-up' : 'plus'}}"
      ng-click="PostProject(currentproject)"
      tooltip="{{ currentproject ? 'Update' : 'Add'}} Project">
</span>

Custom Directive:
app.directive('tooltip', function () {
    return {
        restrict: 'A',
        scope: {
            tooltip: '@'
        },
        link: function ($scope, element, attrs, ctrl) {
            $(element).tooltip({
                title: $scope.tooltip
            });
        }
    };
});

A: Yes, you should add a $watch to the tooltip. Angular can't magically call $().tooltip() if the value of the expression changes.
    link: function ($scope, element, attrs, ctrl) {
      $scope.$watch('tooltip', function(newValue) {
          updateTooltip(newValue);
          // this does'nt update the existing bs tooltip:
          // see http://stackoverflow.com/a/9875490/498298
          // $(element).tooltip({ title: newValue });
      });
    }

http://codepen.io/hansmaad/pen/QEWwdw?editors=1010

A: With all credit and help going to @hansmaad and based on this, here is the final solution:
$scope.$watch('tooltip', function (newValue, oldValue) {
    $(element)
        .tooltip({
            title: newValue
        })
        .attr('data-original-title', newValue);
})


text:
Q: Mesos slave container with Oracle Linux 7 base image fails to start I created a mesos slave docker image with Oracle Linux 7.2 as the base image. The dockerfile builds correctly but when I try to run the image, it gives the following error:
I0414 17:57:30.659329     1 logging.cpp:188] INFO level logging started!
I0414 17:57:30.666347     1 main.cpp:223] Build: 2016-03-17 17:47:25 by root
I0414 17:57:30.666445     1 main.cpp:225] Version: 0.28.0
I0414 17:57:30.666483     1 main.cpp:228] Git tag: 0.28.0
I0414 17:57:30.666543     1 main.cpp:232] Git SHA: 961edbd82e691a619a4c171a7aadc9c32957fa73
I0414 17:57:30.726467     1 systemd.cpp:236] systemd version `219` detected
I0414 17:57:30.726622     1 main.cpp:240] Inializing systemd state
Failed to initialize systemd: Failed to locate systemd runtime directory: /run/systemd/system

Here is the dockerfile:
FROM oraclelinux:7.2

RUN rpm -Uvh http://repos.mesosphere.io/el/7/noarch/RPMS/mesosphere-el-repo-7-1.noarch.rpm
RUN yum -y update
RUN yum -y install mesos

ENTRYPOINT ["mesos-slave"]

The OS of the host machine is Oracle Linux 7.2 as well. I was able to run an image build with Ubuntu 14.04 as well as the existing image created by Mesosphere (https://hub.docker.com/r/mesosphere/mesos-slave/) successfully.
Any idea why this is happening? Thanks in advance.

A: Try this in your Dockerfile:
ENV MESOS_SYSTEMD_ENABLE_SUPPORT false

A: docker can't start systemd in runtime. this is core reason.


text:
Q: .NET video play library which allows to change the playback rate? I am integrating a video player to an existing .NET WinForms application.
I first tried to use "Windows Media Player Control" which is included in Windows SDK,
but I could not change the playback rate.
The following is the code I wrote to change the rate.
if (axWindowsMediaPlayer1.settings.get_isAvailable("Rate"))
{
    axWindowsMediaPlayer1.settings.rate = 3.0;
}

The condition in the if statement always returns "false" no matter what video file I use. Does anyone have any idea why I cannot change the rate? It really needs to be available to change the playback rate, so WMP control seems to be a bad choice if it's impossible to do so.
Or, is there any alternative solution which allows me to change the rate? Preferably a .NET based library which does not involve any unmanaged code.
Thanks!

A: I ended up using DirectShow.NET (http://directshownet.sourceforge.net/) which is an open-source library. It contains a lot of samples, and it has a sample with playback rate control.

A: IF a commercial library is an option take a look at http://www.visioforge.com/media-player-sdk-net.html
Another commercial option would be Leadtools MultIMedia SDK - see http://www.leadtools.com/sdk/multimedia.htm#+cp_playback

A: Is the if statement really necessary?
I could set the rate fine without it..
axWindowsMediaPlayer1.settings.rate = 3.0;


text:
Q: Simplifiying/modularizing my code in javascript I know that I should follow the DRY principle in coding. However, I am not that into javascript so I want to ask how to make the code below more readable and maintanable.
$('#frontfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = frontvImageIsLoaded;
    });
    $('#rearfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = rearvImageIsLoaded;
    });
    $('#rightfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = rightvImageIsLoaded;
    });
    $('#leftfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = leftvImageIsLoaded;
    });
    //called after an image file has been chosen
    function frontvImageIsLoaded(e) {
        $("#frontimagepreview").attr('src', e.target.result);
        $("#frontpreview-msg").css('color', 'green');
    };
    function rearvImageIsLoaded(e) {
        $("#rearimagepreview").attr('src', e.target.result);
        $("#rearpreview-msg").css('color', 'green');
    };
    function rightvImageIsLoaded(e) {
        $("#rightimagepreview").attr('src', e.target.result);
        $("#rightpreview-msg").css('color', 'green');
    };
    function leftvImageIsLoaded(e) {
        $("#leftimagepreview").attr('src', e.target.result);
        $("#leftpreview-msg").css('color', 'green');
    };

This is the code for Main.Mod.image_change()
 var image_change = function handleFileImageChange(obj){
            //holds the image preview object

            var file = obj.files[0];
            var imagefile = file.type;
            var match= ["image/jpeg","image/png","image/jpg"];

            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
              alert("Incorrect image file. You still be able to upload this form but the system " +
               "will be using the default image.");
              $("#preview-msg").css('color', 'red');
              return false;
            }else{
                var reader = new FileReader();
                //reader.onload = imageIsLoaded;
                reader.readAsDataURL(obj.files[0]);

              return reader;
            }
        };

The code above, will handle file input change event then change img src base on the file input.
I know the code i wrote really sucks since I have to repeat my code several times. How can I implement it in a more efficient way?
Thanks.

A: *

*use , to combine selectors:
$('#frontfile_v,#rearfile_v').change(function(){
    // ...
})

The "change" event will be bound to every object matched by the selector. This way you don't need to duplicate the binding.

*Merge the "image loaded" functions into one function by passing parameters:
var idsMap = {
   leftfile_v : {preview : '#frontimagepreview', msg : '#frontpreview-msg'},
   // etc...
};

$('#leftfile_v,#rearfile_v').change(function(){
    var ids = idsMap[$(this).attr('id')];
    reader = Main.Mod.image_change(this);
    reader.onload = function(e) {
        imageIsLoaded(e, ids.preview, ids.msg);
    };
});

function imageIsLoaded(e, preview, msg) {
    $(preview).attr('src', e.target.result);
    $(msg).css('color', 'green');
};

A: Yet another variant. As say @Malki: use comma in selector
$('#frontfile_v, #rearfile_v,#rightfile_v,#leftfile_v').change(function(){
    var id = this.id.replace(/file_v$/,'');
    reader = Main.Mod.image_change(this);
    if(reader){ //for case when `image_change` return not "false"
        // use mode generic function
        reader.onload = function(e){
            $("#"+id+"imagepreview").attr('src', e.target.result);
            $("#"+id+"preview-msg").css('color', 'green');
        };
    }
});

As for handleFileImageChange you need use Array.indexOf function
var image_change = function handleFileImageChange(obj){
    //holds the image preview object

    var file = obj.files[0];
    var imagefile = file.type;
    var match= ["image/jpeg","image/png","image/jpg"];

    if(match.indexOf(imagefile) == -1){
        alert("Incorrect image file. You still be able to upload this form but the system will be using the default image.");
        $("#preview-msg").css('color', 'red');
        return false;
    }else{
        var reader = new FileReader();
        //reader.onload = imageIsLoaded;
        reader.readAsDataURL(file); //you not need use "obj.files[0]" because you already save it in "var file"

        return reader;
    }
};


text:
Q: Merge two records to calculate the time diff I would like to calculate the time difference between two transactions based on intime and outtime.
Please help me to get the desired output.
This is my query:
SELECT
    ssno,
    firstname, lastname,
    deptname,
    inreader, in_desc, intime,
    outreader, out_desc, outtime,
    CONVERT (VARCHAR(5), DATEADD(MINUTE, DATEDIFF(MINUTE, intime, outtime), 0), 114) AS DIFF,
    timeatt
FROM
    (SELECT
         eid,
         ssno,
         firstname, lastname,
         deptname,
         timeatt,
         MIN(CASE
                WHEN timeatt = 1 THEN intime
                ELSE NULL
             END) INTIME,
         MIN(CASE
                WHEN timeatt = 1 THEN INREADER
                ELSE NULL
             END) inreader,
         MIN(CASE
                WHEN timeatt = 1 THEN 'SWIPE IN'
                ELSE NULL
             END) AS IN_DESC,
         MAX(CASE
                WHEN timeatt = 2 THEN outtime
                ELSE NULL
             END) OUTTIME,
         MAX(CASE
                WHEN timeatt = 2 THEN 'SWIPE OUT'
                ELSE NULL
             END) AS OUT_DESC,
         MAX(CASE
                WHEN timeatt = 2 THEN OUTREADER
                ELSE NULL
             END) outreader,
         DATEDIFF(MINUTE, outtime, intime) DIFF
     FROM
         (SELECT
              E.empid EID,
              EM.firstname, EM.lastname,
              EM.ssno,
              D.NAME DEPTNAME,
              R.readerdesc AS INREADER,
              R.readerdesc AS OUTREADER,
              -- CAST (E.EVENT_TIME_UTC AS DATE) TIME3,
              (CASE
                  WHEN timeatt = 1
                     THEN MIN(DATEADD(hh, 03, (E.event_time_utc)))
                     ELSE NULL
                  END) INTIME,
              (CASE
                  WHEN timeatt = 2
                     THEN MAX(DATEADD(hh, 03, (E.event_time_utc)))
                     ELSE NULL
                END) OUTTIME,
               R.timeatt
           FROM
               ((events E
           INNER JOIN
               emp EM ON (E.empid = EM.id))
           FULL JOIN
               reader R ON E.devid = R.readerid
                        AND E.machine = R.panelid)
       FULL JOIN
           udfemp UE ON (EM.id = UE.id)
       FULL JOIN
           dept D ON (UE.dept = D.id)
       WHERE
           E.eventid = '0'
           AND E.empid = 31669
           AND CAST(E.event_time_utc AS DATE) = '2019-08-28'
       GROUP BY
           CAST(E.event_time_utc AS DATE),
           E.empid, EM.firstname, EM.lastname,
           EM.ssno, D.NAME, R.readerdesc, R.timeatt) AS T1
    GROUP BY
        eid,
        firstname, lastname,
        ssno,
        deptname,
        DATEDIFF(MINUTE, outtime, intime), timeatt) AS T2
--WHERE OUTTIME IS NOT NULL
GROUP BY
    eid,
    firstname, lastname, ssno,
    deptname,
    DATEDIFF(MINUTE, outtime, intime),
    intime, outtime, in_desc, out_desc, inreader, outreader,
    timeatt
ORDER BY
    intime DESC;

The required output to be merged in one single record, as said this is to calculate the time difference for a day.

Thanks
Santhosh

A: This may be help you by removing datetime column from group by clause.
Please check below query and let us know.
SELECT ssno, firstname, lastname, deptname, inreader, in_desc, intime, outreader, out_desc, outtime, CONVERT (VARCHAR(5), DATEADD(MINUTE, DATEDIFF(MINUTE, intime, outtime), 0), 114) AS DIFF, timeatt FROM (SELECT eid, ssno, firstname, lastname, deptname, timeatt, MIN(CASE WHEN timeatt = 1 THEN intime ELSE NULL END) INTIME, MIN(CASE WHEN timeatt = 1 THEN INREADER ELSE NULL END) inreader, MIN(CASE WHEN timeatt = 1 THEN 'SWIPE IN' ELSE NULL END) AS IN_DESC, MAX(CASE WHEN timeatt = 2 THEN outtime ELSE NULL END) OUTTIME, MAX(CASE WHEN timeatt = 2 THEN 'SWIPE OUT' ELSE NULL END) AS OUT_DESC, MAX(CASE WHEN timeatt = 2 THEN OUTREADER ELSE NULL END) outreader, DATEDIFF(MINUTE, outtime, intime) DIFF FROM (SELECT E.empid EID, EM.firstname, EM.lastname, EM.ssno, D.NAME DEPTNAME, R.readerdesc AS INREADER, R.readerdesc AS OUTREADER, -- CAST (E.EVENT_TIME_UTC AS DATE) TIME3, (CASE WHEN timeatt = 1 THEN MIN(DATEADD(hh, 03, (E.event_time_utc))) ELSE NULL END) INTIME, (CASE WHEN timeatt = 2 THEN MAX(DATEADD(hh, 03, (E.event_time_utc))) ELSE NULL END) OUTTIME, R.timeatt FROM ((events E INNER JOIN emp EM ON (E.empid = EM.id)) FULL JOIN reader R ON E.devid = R.readerid AND E.machine = R.panelid) FULL JOIN udfemp UE ON (EM.id = UE.id) FULL JOIN dept D ON (UE.dept = D.id) WHERE E.eventid = '0' AND E.empid = 31669 AND CAST(E.event_time_utc AS DATE) = '2019-08-28' GROUP BY --CAST(E.event_time_utc AS DATE), -- This may be not needed.
     E.empid, EM.firstname, EM.lastname, EM.ssno, D.NAME, R.readerdesc, R.timeatt) AS T1 GROUP BY eid, firstname, lastname, ssno, deptname, --DATEDIFF(MINUTE, outtime, intime),-- This may be not needed.
     timeatt) AS T2 --WHERE OUTTIME IS NOT NULL GROUP BY eid, firstname, lastname, ssno, deptname, ---DATEDIFF(MINUTE, outtime, intime),-- This may be not needed.
     intime, outtime, in_desc, out_desc, inreader, outreader, timeatt ORDER BY intime DESC;


text:
Q: Proving the Intermediate Value Theorem using Darboux Theorem I am studying for a final and have been solving extra problems in Spivak's Calculus. However, I am not sure how to write out the proof for a star problem in Chapter 14: Fundamental Theorem of Calculus.
It reads:

Use the Fundamental Theorem of Calculus and Darboux's Theorem to give
  a proof of the Intermediate Value Theorem.

I think I have the idea, but I can't seem to formulate it into a rigorous formal proof. Basically, what I have in mind is letting $F$ be a function such that $F'=f$, and applying Darboux's thoerem on $F$. Then by FTC, we have the IVT??

A: Let $a\lt b$, $f:[a,b]\to \mathbb{R}$, continuous. Let $[x_1, x_2]\subset (a,b)$, let $c$ between $f(x_1)$ and $f(x_2)$, wlog $f(x_1)\lt c\lt f(x_2)$. By the FTC, this says that
$$F'(x_1)\lt c\lt F'(x_2),$$
where $F:[a,b]\to\mathbb{R}:x\mapsto \int_a^x f(t) dt$. By Darboux's Theorem $F'$ must satisfy the intermediate values property, then there exist $u\in (x_1,x_2)$ such that $F'(u)=c$, i.e. $f(u)=c$.


text:
Q: Bash script to set an environment variable if unset I wrote a bash script to set the environment variable VAR if it is currently not set:
example.sh
#!/bin/bash

if [ -z $VAR ]; then
    export VAR=abc
fi

Now I type this in the command line: ./example.sh && echo $VAR. I expect abc, but the result is blank. Why?

A: Use source example.sh or . example.sh


text:
Q: ImportError: cannot import name GLM I installed pymc3 from pip and was going through getting started
http://pymc-devs.github.io/pymc3/notebooks/getting_started.html
Towards the end they use GLM -
from pymc3.glm import GLM

Which returns error "ImportError: cannot import name GLM"
I am able to import other modules of pymc3.glm. For eg this works-
from pymc3.glm import families

A: install the module with pip3

sudo pip3 install git+https://github.com/pymc-devs/pymc3

use python 3
then it should be fine

A: Try updating your pip once through :
pip install --upgrade pip
or
python -m pip install --upgrade pip
Even if doesn't solve the problem, there might be some problem with the module's version for 3+. In this case, try to go back to a stable 2.7 version.


text:
Q: Draw bezier curve above image of UIImageView How to draw beziercurve above the image of the UIImageView. I am subclassing UIImageView and drawing circles using UIBezierCurve on the corners of image view. But as soon as i place the image in UIImageView the inside part of circles are overlapped by the image. So is there any solution which lets me draw the UIBezier path on the UIimage of uiimageview ?

A: You can try subclassing simple UIView and drawing an image yourself using drawInRect: method of UIImage instance. It should look something like this:
- (void)drawRect:(CGRect)dirtyRect {
    // note you can get image from anywhere
    UIImage *image = [UIImage imageNamed:@"MyImage"];

    [image drawInRect:self.bounds];

    // now that image is drawn, everything
    // past this point will be drawn on top of it
    ...
}


text:
Q: How to get the width of a html element inside an element with overflow scroll I have the following html:
<!DOCTYPE html>

    <title></title>

..

..

..

..

If I try the following:
>screen.width
1440
>document.getElementById("me").getBoundingClientRect();
bottom: 56, height: 48, left: 8, right: 1415, top: 8, width: 1407

I would expect the width to be at least 2000 (4X500) plus padding and such.
Instead it gives me the screen width. I will fill the "me" element with a variable amount of elements that will have to scroll horizontally and need the width of the element.
Since the content is variable I cannot set it to a fixed with and instead want to use 100% of the screen width for the container and calculate the width of the content (needed for a custom scroll bar.)
Thank you for taking the time to read this question.
[update]
As for Alvaro's excelent answer; here is an example of the code I plan to use (sorry for the jQuery):
<!DOCTYPE html>

    <title></title>

..

..

..

..

..

..

..

..

    <input type="button" id="ADD" value="ADD" />
    <input type="button" id="REMOVE" value="REMOVE" />

A: If you add:
#me {float:left;}

javascript may give you the right width of your element insteed of the window's width.
I tested it with this jquery:
var meWidth = $('#me').outerWidth(true );
$('.test').css({
    'width': meWidth + 'px'
});

Adding the width obtain to a div I called .test
JSFIDDLE
Note: outerWidth(true ) calculate width + padding + border + margin. In your example: 2132px.


text:
Q: Set default encoding to utf-8 using htaccess I'm using oscommerce under xampp and I'm trying to set default encoding to utf-8, because some characters are messed up. My database is utf8-turkish-ci. Here's my htaccess code:
<filesMatch "\.(htm|html|css|js)$">
AddDefaultCharset UTF-8
DefaultLanguage tr-TR
</filesMatch>

Here's a screenshot:

How can I fix these characters?
Edit: I checked my database and saw that it's utf8-unicode-ci


text:
Q: Converting css to less I am trying to convert some css to less, but on compile i got some errors?
Here is what i have in css, how to convert this to less
#preloader {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #2AABE2;
    background: rgba(42, 171, 226, 0.5);
    display: none;
    -khtml-opacity: 0.80;
    opacity: 0.80;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha"(Opacity=60);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=60);
    filter:alpha(opacity=60);
    z-index: 20000;
    text-align: center;
}
.preloader-text {
    color: white;
    font-size:16px !important;
    margin: auto auto 10px;
}
.preloader-holder {
    background-position: center center;
    background-repeat: no-repeat;
    height: 200px;
    left: 50%;
    margin: -100px 0 0 -200px;
    position: absolute;
    top: 50%;
    width: 400px;
}

A: Simply use escape character ~:
#preloader {
    ....
    -ms-filter:~'progid:DXImageTransform.Microsoft.Alpha"(Opacity=60)';
    filter: ~'progid:DXImageTransform.Microsoft.Alpha(opacity=60)';
    ....
}

remember to use single quotes to contain entire string, because value already containd double ones.

A: Try prefixing the string with ~
-ms-filter: ~"progid:DXImageTransform.Microsoft.Alpha(opacity=60)";

or
-ms-filter: e("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");

Check out string functions on less docs


text:
Q: VBA to add multiple hyperlinks to one Powerpoint text box I'm using a VBA loop in Powerpoint to import data from Excel and write each new string that has been imported as a new bullet in the text box on the slide. This works fine. Then a hyperlink that is also imported should be added to each bullet. This works except that only the last bullet keeps its hyperlink. I suspect that the hyperlink is added not specifically to the bullet but to the text box and therefore is overwritten with each new bullet leaving only the bottom bullet with a hyperlink. Any idea how I can get all bullets' hyperlinks to remain?
Many thanks!

new_slide.Shapes(2).TextFrame.TextRange.text = new_slide.Shapes(2).TextFrame.TextRange.text & vbNewLine & new_text

With new_slide.Shapes(2).TextFrame.TextRange.Find(new_text).ActionSettings(ppMouseClick)
    .Action = ppActionHyperlink
    .Hyperlink.Address = excel_link
End With

A: {modified version}
It works if we add the text first, then step through each line, adding the hyperlink a line at a time. You'll need to either step through your XL import twice, once for the text, once for the hyperlinks:
Sub RoundTwo()
    Dim oSh As Shape
    Dim x As Long

    Set oSh = ActiveWindow.Selection.ShapeRange(1)

    For x = 1 To 3
        With oSh.TextFrame.TextRange
            .Text = .Text & vbNewLine & "Some new text"
        End With
    Next

    For x = 1 To 3
        Call AddLinkToLine(oSh, x)
    Next

End Sub

Sub AddLinkToLine(oSh As Shape, lLine As Long)
    With oSh.TextFrame.TextRange.Paragraphs(lLine)
        With .ActionSettings(ppMouseClick)
            .Action = ppActionHyperlink
            .Hyperlink.Address = "http://www.pptfaq.com"
        End With
    End With
End Sub


text:
Q: How integrate RapidMiner in a PHP web application? I've got an implementation in RapidMiner that classifies questions according to Bloom's taxonomy. I need to consume the data produced by a web application developed in PHP and show the results in the interface of the web application.
So I'm wondering if it is possible that the application in PHP communicates with RapidMiner to process the data and show the results provided by RapidMiner in the interface.
I know RapidMiner is implemented in Java, and there is the option of using Java bridge to comunicate PHP and JAVA, but I'm not sure if that is a solution to this.

A: Why not try to communicate with xml, for example, PHP app sends a list of questions via xml to rm, it then processes it and returns an xml feed. I think this'll likely be the easiest solution.. As far as performance, I can't say one way or the other if it's the best solution


text:
Q: How to fix `react-d3-tree` in place? For some reason the default behaviour in this package is to allow users to move the trees around as they please.
How do you disable grabability?
I'd also accept an answer which suggests a different tree-graph package that looks nice and doesn't allow users to drag it around the screen.
The package is hosted at:
https://github.com/bkrem/react-d3-tree
And here is an example in CodeSandBox:
https://codesandbox.io/s/yq86mj80zx?file=/src/index.js


text:
Q: Turn on Multiple Layers in one click Is there a way to turn on multiple layers at once? I have around 100 shapefiles which are turned off by default on entry. Turning the folder on/off makes no difference and you can't select multiple layers using Ctl then turn them all on and off.

A: There is even an easier way in the layer panel: select "Manage map themes" (the eye-symbol) and click on "show all layers" (see screenshot). Other options: hide all layers, show or hide selected layers, Hide Deselected Layers. You can even pre-define visibility presets, so-called Map Themes, so that you can change with one click between different configurations of layer visibility.
See here for the documentation: https://docs.qgis.org/3.10/en/docs/user_manual/introduction/general_tools.html#configuring-map-themes


text:
Q: SQL: list of points to rectangle I have two tables:
regions <id>
points <region_id, x, y>

Assuming there are exactly 4 points per region, and these points describe a rectangle -- is there an SQL query that will bring me this view:
rectangular_regions <region_id, x1, y1, x2, y2>

?

A: SELECT region_id, MIN(x) AS x1, MIN(y) AS y1, MAX(x) AS x2, MAX(y) AS y2
FROM points
GROUP BY region_id.


text:
Q: EC2 Instance is setting Access-Control-Allow-Origin: * for all responses So I want a same-origin policy which only allows my API to be called from the same-origin in browser, I don't want CORs.
After hours testing whether nginx or my node web app was setting Access-Control-Allow-Origin:* , it turns out that AWS EC2 is setting CORs headers without my permission. I can override this using Nginx to remove response headers and replace (if necessary)...
However I do not believe this is how it should be done, why is AWS putting extra strain on my web server without giving me the option to customise their default "allow all origins"?
This is such an unnecessary problem AWS is creating for me and was wondering if anyone else is experiencing the same and how we should go about it?
What I've tried:

*

*In local development without AWS, neither nginx nor my node app add any access control headers (without my permission) - there is no mention of it. I even disabled CORS on my node app to make sure!

*Turning on cors in my node app to see if I can override the response that is being set by AWS EC2 downstream.
This results in two separate Access-Control-Allow-Origin headers, the AWS one taking precedence over mine.

*Using Nginx to respond to Options, so AWS knows that I have considered CORs requests and that I want to reject them... However my nginx response to Options is once again overrided by AWS downstream on the response! Additionally I would add CORs options to my responses using NGinx but they are still overrided by AWS.
when I say AWS overrides my response I mean that, my response is included but so is AWS response.
[example AWS with Nginx response][1]
[1]: https://i.stack.imgur.com/9xnlr.png

Maybe AWS are saying something, that all API's should be accessible from all origins? just doesn't make sense to me!
Btw here is what amazon have to say about cors, that it is "standardised" https://docs.aws.amazon.com/AWSEC2/latest/APIReference/cors-support.html
I don't understand the difference between an EC2 instance running MY API, vs and EC2 API? my main concern is changing the AWS cors headers, which I cant find any help on!

A: So after playing around more and realising that the Access-Control-Allow-Origin:* is being returned only by all GET requests, and all successful POST requests (from my own domain - no CORs, as i have it disabled), I thought something has to be up (all my get requests are allowed cross domain).
This post explains it beautifully by Amazon themselves, pretty annoyed they have taken the liberty to take my web security into their own hands, but atleast we know what side they are on now!
https://docs.aws.amazon.com/AWSEC2/latest/APIReference/cors-support.html
"For all simple requests such as GET & POST(simple post), the Access-Control-Allow-Origin * is returned" by AMAZON.
"Therefore, Amazon EC2 allows any cross-domain origin, and never allows browser credentials, such as cookies." because " Access-Control-Allow-Credentials is never returned" - so cookies should not be at risk of cross-site attacks from this setup I hope. However this setup also encourages spam botting from any domain, which will make amazon more money - which is the only plausible reason for why they have decided to enabled CORs for all simple requests.. @jeff.
If you prefer images, and so we can quote amazon on this!
Simple Requests Response from EC2
Finally, Amazon EC2 even have the courtesy to accept OPTIONS requests on our behalf, for more dangerous requests - to which they send a response of:

*

*Access-Control-Allow-Origin: * "This is always returned with a * value."

*Access-Control-Allow-Credentials is NOT returned. Setting browser for default false which will not send any cookies with the now permitted cross origin requests.

*Access-Control-Expose-Headers is NOT returned. EC2 doesn't permit your browser to read response headers?

*Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE - "this depends on whether you use our Query API or REST" have no idea what that means but a cross site preflight for my REST API returned GET, OPTIONS, POST - thankfully.

*Access-Control-Allow-Headers "Amazon EC2 accepts any headers in preflight requests."

The general sense is that Amazon wants us to outsource basic CORs security to the EC2 instance? Would love to test out the pre-flight they provide better but it seems they do most of the boilerplate and let you decide if you want to accept any complex/notsimple CORs requests - as detailed here https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
Took me a while and a bit of shock, but glad we got here!


text:
Q: Split XML based on a child and iterate over a dynamic tag in my Mule flow i will be invoking a stored procedure which is going to out me XML response something like this
<RESULT xmlns="some_stored_proc:Response">
   <ROOT_TAG>
      <RESULTSET_1>
         <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>1</hasError>
        </ROW>
        <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>1</hasError>
        </ROW>
    </RESULTSET_1>
<RESULTSET_2>
         <ROW>
            0.3
            0.2
            <C>1.1</C>
            <hasError>0</hasError>
        </ROW>
        <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>0</hasError>
        </ROW>
    </RESULTSET_2>
<RESULTSET_3>
         <ROW>
            1.1
            2.4
            <C>1.8</C>
            <hasError>0</hasError>
        </ROW>
        <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>0</hasError>
        </ROW>
    </RESULTSET_3>
</ROOT_TAG>
</RESULT>

now in my dataweave what i want to do is go through this XML and any  which has  set to 1 bring them under a root tag called ISSUES
<ISSUES>
     <ROW>
        0.1
        0.4
        <C>1.0</C>
        <hasError>1</hasError>
    </ROW>
    <ROW>
        0.1
        0.4
        <C>1.0</C>
        <hasError>1</hasError>
    </ROW>
</ISSUES>

and the rest of the ROW's goes under DOCUMENT like this
    <DOCUMENT>
         <ROW>
            0.3
            0.2
            <C>1.1</C>
            <hasError>0</hasError>
        </ROW>
        <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>0</hasError>
        </ROW>
         <ROW>
            1.1
            2.4
            <C>1.8</C>
            <hasError>0</hasError>
        </ROW>
        <ROW>
            0.1
            0.4
            <C>1.0</C>
            <hasError>0</hasError>
        </ROW>
    </DOCUMENT>

i keep hitting one exception or the other.
NOTE: There can be any number of <RESULTSET_n> tags based on the input size and a group size which goes as an input to the database stored proc. So this tag is going to be kind of dynamic.

A: So basically what I did is use the groupBy function to split your document into valid and invalids the I transform each part into the expected data structure
%dw 2.0
output application/xml
import * from dw::core::Objects
---
{
    RESULT: {(
payload.RESULT.ROOT_TAG
    groupBy ((value, key) -> (key as String match /RESULTSET_([0-9]+)/)[1] == "1")
    pluck ((value, key, index) ->
        key as String match {
            case "true" ->
                { ISSUES: {(valueSet(value))}}
            case "false" ->
                { DOCUMENT: {(valueSet(value))}}
        }
    )

    )}
}


text:
Q: Linker errors after adding Flurry library I created a new app from scratch to test with Flurry.
After following their documentation, downloading the SDK and adding it to the app I'm getting the following error messages:
I've linked the all the frameworks they require:
I have architectures set to standard with armv7 and arm64 and running lipo -info on the libFlurry_7.6.0.a and libFlurryAds_7.6.0.a files shows that they both support architectures: i386, armv7, x86_64, and arm64.
I'm trying to build to the iOS simulator.

A: Have you added the libraries in your project root?
If yes skip to step 2. If no add it:
Step 1

Step 2: Go to Target > Build Settings > Search Paths > Library Search Paths > add: $(inherited) and $(SRCROOT) and $(PROJECT_DIR)

You don't need the 3 search paths, but just to make sure it will look for into your project. I hope this can help you.


text:
Q: Using an IF function to refer to separate sheet [EXCEL] I am looking for a way use an IF function that refers to a column that is referring to a sheet.
EX:

NOTE: yellow box is what I want to have happen using the function
The ID column is populated from a separate sheet in my workbook
Formula:
=Sheet2!$A$3:$A$48
=Sheet3!$A$3:$A$48
I want the Flag column to refer to the ID column from the other worksheet. In pseudocode:
"If ID field references the Sheet2 Range, return value 1, ELSE, return 0".

A: Building on @BigBen's comment try this:
=IF(ISNUMBER(SEARCH("Sheet2",FORMULATEXT(A2))),1,0)

replace A2 with cell reference that matches the location of ID # 123456 in your spreadsheet, and then drag the formula down.


text:
Q: Selectively Disable cells of row in DataBound DataGridView I need to be able to turn off some cells in a row based on a boolean flag.  If the flag is true I everything should be enabled and visible like normal.  If the flag is false however I need to have several cells in the row made invisible and readonly.

A: You can handle the CellPainting event, check the status of your flag there and then paint the cell to be shown/hidden.
This link on MSDN may help you in this:
http://msdn.microsoft.com/en-us/library/hta8z9sz.aspx

A: Here is my example. Add an event handler for CellPainting, then determine if the item is disabled or not. If it is disabled, then just paint the background and make the cell read-only.
I've got a custom class BoardStatusView bound to the data grid, which has a boolean function that determines if the cell should have a check box or not (Upgradeable())
    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            BoardStatusView bs = dataGridView1.Rows[e.RowIndex].DataBoundItem as BoardStatusView;
            bool disabled = !bs.Upgradeable();
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = disabled;
            if (disabled && e.ColumnIndex == 0)
            {
                e.PaintBackground(e.ClipBounds, false);
                e.Handled = true;
            }
        }
    }


text:
Q: Calculation Performance (slow Plotting) I have a functions, which is an Integral. It is exaclty this function
Zf[x_] := 2*I*NIntegrate[Exp[-y^2.0 + 2.0*I*y*x], {y, 0, Infinity}];

Later I need to plot a graph of this function like this
Print["init time=", DateString[]]
Timing[Plot[Im[Zf[x]], {x, -2, 2}]]
Print["finish time=", DateString[]]

and it takes around 9 seconds.
but as final result I need to plot some more complicated functions, depends on this Zf like this.
f1[x_, p1_] := I*Im[Zf[x]] + p1*I*(1 + Zf[x]);
f2[x_, p1_, p2_] :=
  p1*(f1[x] + (2 + Zf[x])/ Conjugate[Zf[x]]) -
   I*p2*(f1[x] - (2 - Zf[x])/ Conjugate[Zf[x]]);

Here p1 and p2 some parameters. and later I plot it again like this
Print["init time=", DateString[]]
Timing[Plot[Im[f1[x, 2]], {x, -2, 2}]]
Print["finish time=", DateString[]]

Print["init time=", DateString[]]
Timing[Plot[Im[f2[x, 1.35, 1.45]], {x, -2, 2}]]
Print["finish time=", DateString[]]

and plotting of f1 takes around 30 seconds, plotting of f2 takes 90 seconds.
If I replace NIntegrate to normal Integrate, it becomes much slower (I even cannot plot first graph in 10 minutes).
The problem is much bigger because finally I need dozens of graphs with comparation of all that functions and different parameters. Also I would like to change parameters quickly and compare the results.
Print["init time=", DateString[]]
Timing[Plot[{Im[Zf[x]], Im[f1[x, 2]], Im[f2[x, 1.35, 1.45]],
   Im[f1[x, 3]], Im[f2[x, 2.35, 2.45]]}, {x, -2, 2}]]
Print["finish time=", DateString[]]

It takes 240 seconds.
Here is only 2 parameters. In real life it is much more complicated. I have around 10 parameters and functions more complicated than f1 and f2. It really takes hours.
Can I do something to improve performance of this kind of calculations?

A: I believe this is fast enough
p[x_] = Integrate[Exp[-y^2 + 2*I*y*x], {y, 0, Infinity}]
Zf[x_] := 2 I p[x]
f1[x_, p1_] := I*Im[Zf[x]] + p1*I*(1 + Zf[x]);
f2[x_, p1_, p2_] := p1*(f1[x] + (2 + Zf[x])/Conjugate[Zf[x]]) -
                        I*p2*(f1[x] - (2 - Zf[x])/Conjugate[Zf[x]]);

Plot[Im[f1[x, 2]], {x, -2, 2}]
Plot[Im[f2[x, 1.35, 1.45]], {x, -2, 2}]


text:
Q: Help with Wordpress Query I'm sort of a noob when it comes to Wordpess; I've only recently started building themes and I've run into a wall. I'm trying to feature 3 different articles at the top of my site using wpquery and for some reason it's only displaying one. I'll include my code below and if anyone can help my figure out what's wrong I would be very grateful!
Code included in pastebin: http://pastebin.com/1DB7vent

     <?php
     $args = array( 'tag' => 'featured', 'posts_per_page' => '3' );
     $recent_posts = wp_get_recent_posts( $args );
     ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="nofollow">
           <?php the_post_thumbnail('featured', array( 'title'  => '' )); ?>

           <a href="<?php the_permalink(); ?>" rel="bookmark">
               <?php the_title(); ?>

     <?php wp_reset_query(); ?>

I want the "li" to repeat 2 more times for a total of three. I'm trying to get a setup similar to this:

            "Featured Article 1 Title"

   <REPEAT 'LI' ABOVE TWICE MORE BELOW>

A: Take a look in current theme's directory at loop.php. You need to loop through your query results and display them. The general structure is like so:
<?php while ( have_posts() ) : the_post(); ?>

       <?php //show your post  ?>

<?php endwhile; // End the loop. Whew. ?>


text:
Q: Why didn't I get 'Nice Answer'? I did not get a 'Nice Answer' for this post, is it disabled on meta, is it a bug, or is there something else I'm missing?

A: Because it wasn't good?...
...I think you did - You have 3x Nice answers and looking at your profile, you have 3 answers with over 10 up votes.
Just remember to wait patiently.

A: If you already have a Nice Answer for a question that has been downvoted or deleted and doesn't fit the criteria of Nice Answer anymore, you won't get a new one.


text:
Q: USB Serial for Android - problems sending/receiving data with Arduino Uno R3 I'm trying to send a command such as "c" or "s" to the Arduino from my Android applicaton. The device is recognized, but I'm unsure if I'm sending/receiving the data correctly. I'm using the USBSerialforAndroid library.
When I tap my buttons to start and stop the measurements, the toast notifications pop up to signify that they are going through, but when data is "received" I'm getting back either "7.00" or "0.00", which I know are wrong. I feel like it may be within my Arduino code, or how I'm sending bytes from the app.
Here is the relevant Android code:
startMeasurement.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
      if (selectedSensorType.equals("grade")) {
         //do nothing
      } else if (selectedSensorType.equals("height")) {
          startCode = "c";

          heightStart = serialUser(startCode); //get heightFloor from Arduino
      } else if (selectedSensorType.equals("distance")) {
          startCode ="s";

          distanceStart = 0;
      }
  }
});

saveMeasurement.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
      if (selectedSensorType.equals("grade")) {
         check.setText(String.format("%.2f", outputGrade));
      } else if (selectedSensorType.equals("height")) {
         endCode = "c";
         heightEnd = serialUser(endCode); //get heightCurb from Arduino

         double measuredHeight = heightEnd - heightStart;
         check.setText(String.format("%.2f", measuredHeight));
      } else if (selectedSensorType.equals("distance")) {
         endCode = "e";
         distanceEnd = serialUser(endCode); //get distanceEnc from Arduino

         double measuredDistance = distanceEnd - distanceStart;
         check.setText(String.format("%.2f", measuredDistance));
      }
   }
});

Here is my serialUser() method:
private double serialUser(String command) {
        double output = 0;
        if (mSerialDevice != null) {
            byte[] commandArray = command.getBytes();
            byte[] returnArray = new byte[8];

            try {
                mSerialDevice.setBaudRate(115200);
                mSerialDevice.write(commandArray, 1000);
                output = mSerialDevice.read(returnArray, 2500);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return output;
    }

And here is my Arduino code:
void setup()
{
  Serial.begin(115200);
  Dist.begin(2,3);
}

const double Pi = 3.14159265359; // 3.141593, set to 1 for testing purposes
double encoderPosition  = -999;

void loop()
{
  double newPosition = abs(myEnc.read()); // gets raw data, 1440 ticks = 1 rev
  double revs = newPosition/(double)960; // calculates number of revs
  double diameter = 15; // specify wheel diameter
  double distanceEnc = diameter*Pi*revs; // calculates distance
  double heightDiff;
  int timesum = 0;

  distanceEnc = round(distanceEnc*1000.0l)/1000.0l; // round distance to 3 decimal places

  if (newPosition != encoderPosition) { // write new position to serial
    encoderPosition = newPosition;
    //Serial.println(distanceEnc,3);
    //Serial.println(revs,3);
  }

  while (Serial.available()) { // if a character is sent to the device, the encoder reading resets to zero

    byte incomingCommand = Serial.read();
    if (incomingCommand == 's'){
      myEnc.write(0);
      revs = 0;
    }
    if (incomingCommand == 'e'){
      Serial.println(distanceEnc,3);
    }
    if (incomingCommand == 'f'){
      time = Dist.getDistanceTime();
      heightFloor = (float) time/(148.00);
      Serial.println(heightFloor);
    }
    if(incomingCommand =='c'){
      for(int i=1; i<11; i++){
       times[i] = Dist.getDistanceTime();
       delay(100);
       timesum = timesum+times[i];}

     time = timesum/(int)10;
      heightCurb = (float) time/(148.00);
      heightDiff = heightFloor - heightCurb;
      Serial.println(heightCurb);
    }
  }
}

A: I used the example from the developer's example folder to build a working app.
https://github.com/mik3y/usb-serial-for-android/tree/master/usbSerialExamples
Check these out, and see what you can make of it.


text:
Q: Apache Commons equals/hashCode builder I'm curious to know, what people here think about using
org.apache.commons.lang.builder EqualsBuilder/HashCodeBuilder
for implementing the equals/hashCode? Would it be a better practice than writing your own? Does it play well with Hibernate? What's your opinion?

A: If you do not want to depend on a 3rd party library (maybe you are running an a device with limited resources) and you even do not want to type your own methods, you can also let the IDE do the job, e.g. in eclipse use
Source -> Generate hashCode() and equals()...

You will get 'native' code which you can configure as you like and which you have to support on changes.

Example (eclipse Juno):
import java.util.Arrays;
import java.util.List;

public class FooBar {

    public String string;
    public List<String> stringList;
    public String[] stringArray;

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((string == null) ? 0 : string.hashCode());
        result = prime * result + Arrays.hashCode(stringArray);
        result = prime * result
                + ((stringList == null) ? 0 : stringList.hashCode());
        return result;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        FooBar other = (FooBar) obj;
        if (string == null) {
            if (other.string != null)
                return false;
        } else if (!string.equals(other.string))
            return false;
        if (!Arrays.equals(stringArray, other.stringArray))
            return false;
        if (stringList == null) {
            if (other.stringList != null)
                return false;
        } else if (!stringList.equals(other.stringList))
            return false;
        return true;
    }

}

A: The EqualsBuilder and HashCodeBuilder have two main aspects that are different from manually written code:

*

*null handling

*instance creation

The EqualsBuilder and HashCodeBuilder make it easier to compare fields that could be null. With manually writen code this creates a lot of boilerplate.
The EqualsBuilder will on the other hand create an instance per equals method call. If your equals methods are call often this will create a lot of instances.
For Hibernate the equals and hashCode implementation make no difference. They are just an implementation detail. For almost all domain objects loaded with hibernate the runtime overhead  (even without escape analysis) of the Builder can be ignored. Database and communication overhead will be significant.
As skaffman mentioned the reflection version cannot be used in production code. Reflection will be to slow and the "implementation" will not be correct for all but the simplest classes. Taking all members into account is also dangerous as newly introduced members change the equals method behaviour. The reflection version can be useful in test code.

A: If you don't to write your own, there is also the possibility to use google guava (formerly google collections)

A: The commons/lang builders are great and I have been using them for years without noticeable performance overhead (with and without hibernate). But as Alain writes, the Guava way is even nicer:
Here's a sample Bean:
public class Bean{

    private String name;
    private int length;
    private List<Bean> children;

}

Here's equals() and hashCode() implemented with Commons/Lang:
@Override
public int hashCode(){
    return new HashCodeBuilder()
        .append(name)
        .append(length)
        .append(children)
        .toHashCode();
}

@Override
public boolean equals(final Object obj){
    if(obj instanceof Bean){
        final Bean other = (Bean) obj;
        return new EqualsBuilder()
            .append(name, other.name)
            .append(length, other.length)
            .append(children, other.children)
            .isEquals();
    } else{
        return false;
    }
}

and here with Java 7 or higher (inspired by Guava):
@Override
public int hashCode(){
    return Objects.hash(name, length, children);
}

@Override
public boolean equals(final Object obj){
    if(obj instanceof Bean){
        final Bean other = (Bean) obj;
        return Objects.equals(name, other.name)
            && length == other.length // special handling for primitives
            && Objects.equals(children, other.children);
    } else{
        return false;
    }
}

Note: this code originally referenced Guava, but as comments have pointed out, this functionality has since been introduced in the JDK, so Guava is no longer required.
As you can see the Guava / JDK version is shorter and avoids superfluous helper objects. In case of equals, it even allows for short-circuiting the evaluation if an earlier Object.equals() call returns false (to be fair: commons / lang has an ObjectUtils.equals(obj1, obj2) method with identical semantics which could be used instead of EqualsBuilder to allow short-circuiting as above).
So: yes, the commons lang builders are very preferable over manually constructed equals() and hashCode() methods (or those awful monsters Eclipse will generate for you), but the Java 7+ / Guava versions are even better.
And a note about Hibernate:
be careful about using lazy collections in your equals(), hashCode() and toString() implementations. That will fail miserably if you don't have an open Session.

Note (about equals()):
a) in both versions of equals() above, you might want to use one or both of these shortcuts also:
@Override
public boolean equals(final Object obj){
    if(obj == this) return true;  // test for reference equality
    if(obj == null) return false; // test for null
    // continue as above

b) depending on your interpretation of the equals() contract, you might also change the line(s)
    if(obj instanceof Bean){

to
    // make sure you run a null check before this
    if(obj.getClass() == getClass()){

If you use the second version, you probably also want to call super(equals()) inside your equals() method. Opinions differ here, the topic is discussed in this question:

right way to incorporate superclass into a Guava Objects.hashcode() implementation?

(although it's about hashCode(), the same applies to equals())

Note (inspired by Comment from kayahr)
Objects.hashCode(..) (just as the underlying Arrays.hashCode(...)) might perform badly if you have many primitive fields. In such cases, EqualsBuilder may actually be the better solution.

A: Folks, wake up! Since Java 7 there are helper methods for equals and hashCode in the standard library. Their usage is fully equivalent to usage of Guava methods.

A: If you are just dealing with the entity bean where id is a primary key, you can simplify.
   @Override
   public boolean equals(Object other)
   {
      if (this == other) { return true; }
      if ((other == null) || (other.getClass() != this.getClass())) { return false; }

      EntityBean castOther = (EntityBean) other;
      return new EqualsBuilder().append(this.getId(), castOther.getId()).isEquals();
   }

A: In my opinion it doesn't play well with Hibernate, especially the examples from the answer comparing length, name and children for some entity. Hibernate advises to use business key to be used in equals() and hashCode(), and they have their reasons. If you use auto equals() and hashCode() generator on your business key, it's ok, just the performance problems need to be considered as mentioned previously. But people usually uses all properties what is IMO very wrong. For example I'm currently working on project where entities are written using Pojomatic with @AutoProperty, what I consider a really bad pattern.
Their two main scenarios to use hashCode() and equals() are:

*

*when you put instances of persistent classes in a Set (the
recommended way to represent many-valued associations) and

*when you use reattachment of detached instances

So let's assume our entity looks like this:
class Entity {
  protected Long id;
  protected String someProp;
  public Entity(Long id, String someProp);
}

Entity entity1 = new Entity(1, "a");
Entity entity2 = new Entity(1, "b");

Both are the same entity for Hibernate, which have been fetched from some session at some point (their id and class/table are equal). But when we implement auto equals() a hashCode() on all props, what do we have?

*

*When you put the entity2 to the persistent set where the entity1 already exists, this will be put twice and will result in exception during commit.

*If you want to attach the detached entity2 to the session, where entity1 already exists they (probably, I haven't tested this especially) won't be merged properly.

So, for 99% project I make, we use the following implementation of equals() and hashCode() written once in base entity class, which is consistent with the Hibernate concepts:
@Override
public boolean equals(Object obj) {
    if (StringUtils.isEmpty(id))
        return super.equals(obj);

    return getClass().isInstance(obj) && id.equals(((IDomain) obj).getId());
}

@Override
public int hashCode() {
    return StringUtils.isEmpty(id)
        ? super.hashCode()
        : String.format("%s/%s", getClass().getSimpleName(), getId()).hashCode();
}

For the transient entity I do the same what Hibernate will do on persistence step, ie. I use the instance match. For the persistent objects I compare the unique key, which is the table/id (I never use composite keys).

A: Just in case, others will find it useful, I've come up with this Helper class for hash code computation that avoids extra object creation overhead mentioned above (in fact, the overhead of Objects.hash() method is even bigger when you have inheritance as it will create an new array on each level!).
Usage example:
public int hashCode() {
    return HashCode.hash(HashCode.hash(timestampMillis), name, dateOfBirth); // timestampMillis is long
}

public int hashCode() {
    return HashCode.hash(super.hashCode(), occupation, children);
}

The HashCode helper:
public class HashCode {

    public static int hash(Object o1, Object o2) {
        return add(Objects.hashCode(o1), o2);
    }

    public static int hash(Object o1, Object o2, Object o3) {
        return hash(Objects.hashCode(o1), o2, o3);
    }

    ...

    public static int hash(Object o1, Object o2, ..., Object o10) {
        return hash(Objects.hashCode(o1), o2, o3, ..., o10);
    }

    public static int hash(int initial, Object o1, Object o2) {
        return add(add(initial, o1), o2);
    }

    ...

    public static int hash(int initial, Object o1, Object o2, ... Object o10) {
        return add(... add(add(add(initial, o1), o2), o3) ..., o10);
    }

    public static int hash(long value) {
        return (int) (value ^ (value >>> 32));
    }

    public static int hash(int initial, long value) {
        return add(initial, hash(value));
    }

    private static int add(int accumulator, Object o) {
        return 31 * accumulator + Objects.hashCode(o);
    }
}

I've figured that 10 is the maximum reasonable number of properties in a domain model, if you have more you should think of refactoring and introducing more class instead of maintaining a heap of Strings and primitives.
The drawbacks are: it's not useful if you have mainly primitives and/or arrays that you need to hash deeply. (Normally this is the case when you have to deal with flat (transfer) objects that is out of your control).


text:
Q: How to listen to a TCP stream on my FastAPI server I am working on a project building an API that is able to send the live location of vehicles to a frontend.
I get this location data by subscribing to a ZMQ stream by running a while loop. This is all working and if I just run my stream as a script I can print all kinds of information to the terminal (I'll store those in a database later on).
I also have the FastAPI server up and running
Now what I'd like to do is:

*

*At startup start the server so I can make API calls

*Start the while loop and start receiving data from the ZMQ stream

What happens instead:

*

*It seems either / or.

*I can import a function with the while loop but this blocks the server from starting up

*Or I can run the server with no means to start the stream

Here is my code:
# General FastAPI Imports
from fastapi import Depends, FastAPI, Request
from data_collection.livestream import enable_data_stream
from client_service import client_api

app = FastAPI()

app.include_router(client_api.router, prefix="/API/V1")
@app.get('/')
def read_root(request: Request):
    return {"Hello": "World"}

The Stream:

from gzip import GzipFile
from io import BytesIO
import zmq
import xml.etree.ElementTree as ET

context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.connect("tcp://SERVER")
subscriber.setsockopt(zmq.SUBSCRIBE)

while True:
    multipart = subscriber.recv_multipart()
    address = multipart[0]
    try:
        contents = GzipFile('', 'r', 0, BytesIO(multipart[1])).read()
        root = ET.fromstring(contents)
        print("Updates Received:")
        # Gets the timestamp
        print('time', root[3].text)
        print('X Coord: ', root[4][0][12].text)
        print('Y Coord: ', root[4][0][13].text)

I tried looking into the multiprocess and threading implementations for python but I'm unsure how those tie in with starting the FastAPI process (as that's enabled from Uvicorn)

A: In the example below, the server and worker are started in separate processes because the While loop won't resolve. It seems that you were on the right track. In my example, I have these functions in one file, but there are no restrictions on someone breaking them out into their own files:
import uvicorn
import multiprocessing
import time
import zmq
import xml.etree.ElementTree as ET
from gzip import GzipFile
from io import BytesIO
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

def server():
    uvicorn.run(app, host="localhost", port=8000)

def worker():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.connect("tcp://SERVER")
    subscriber.setsockopt(zmq.SUBSCRIBE)

    while True:
        multipart = subscriber.recv_multipart()
        address = multipart[0]

        try:
            contents = GzipFile('', 'r', 0, BytesIO(multipart[1])).read()
            root = ET.fromstring(contents)
            print("Updates Received:")
            # Gets the timestamp
            print('time', root[3].text)
            print('X Coord: ', root[4][0][12].text)
            print('Y Coord: ', root[4][0][13].text)

        except Exception as e:
            print(e)
            print("Error: %s" % multipart[1])
            break

if __name__ == '__main__':
    # Runs server and worker in separate processes
    p1 = multiprocessing.Process(target=server)
    p1.start()

    time.sleep(1)  # Wait for server to start

    p2 = multiprocessing.Process(target=worker)
    p2.start()

    p1.join()
    p2.join()


text:
Q: Reverse polarity protection with two-cell series Li-ion I plan on using a P-channel MOSFET for reverse polarity protection. The MOSFET I chose is the SISS27DN-T1-GE3 - it has a 30 V VDS, ~5.5 mΩ RDS, and +/-20 V VGS.
Since this MOSFET has a higher VDS and VGS voltage than expected from two Li-ions, I believe I can forgo the zener diode and resistor to clamp voltage to the gate.
Any gotchas I didn't think of? I do have a charging/balancing circuit for the 2 batteries  - will this negatively affect the circuit?


text:
Q: Tabpage not resizing on minimize/ maximimize Hi I have a windows form in my application with a tab control inside it. I have noticed that when I restore the application from the taskbar after minimizing it, the tabpage shrinks to half it's normal size and all controls inside move downwards. I have the tabpage docked to fill inside a TablePanelLayout. The tabs stay in place though. This does not happen upon resizing the form. Please help.
This is the relevant code from the designer.cs file
        //
        // tabControl1
        //
        this.tabControl1.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
        this.tabControl1.Controls.Add(this.tabPage1);
        this.tabControl1.Controls.Add(this.tabPage2);
        this.tabControl1.Controls.Add(this.tabPage3);
        this.tabControl1.Controls.Add(this.lookupTab);
        this.tabControl1.Controls.Add(this.tabPage4);
        this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tabControl1.ItemSize = new System.Drawing.Size(71, 35);
        this.tabControl1.Location = new System.Drawing.Point(3, 110);
        this.tabControl1.Multiline = true;
        this.tabControl1.Name = "tabControl1";
        this.tabControl1.SelectedIndex = 0;
        this.tabControl1.Size = new System.Drawing.Size(1453, 601);
        this.tabControl1.TabIndex = 0;
        this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
        //
        // tabPage1
        //
        this.tabPage1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        this.tabPage1.Controls.Add(this.panel2);
        this.tabPage1.Location = new System.Drawing.Point(4, 39);
        this.tabPage1.Name = "tabPage1";
        this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage1.RightToLeft = System.Windows.Forms.RightToLeft.No;
        this.tabPage1.Size = new System.Drawing.Size(1445, 558);
        this.tabPage1.TabIndex = 0;
        this.tabPage1.Text = "Settings";
        this.tabPage1.UseVisualStyleBackColor = true;
        //
        // tabPage2
        //
        this.tabPage2.Controls.Add(this.label5);
        this.tabPage2.Controls.Add(this.label4);
        this.tabPage2.Controls.Add(this.label2);
        this.tabPage2.Location = new System.Drawing.Point(4, 39);
        this.tabPage2.Name = "tabPage2";
        this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
        this.tabPage2.Size = new System.Drawing.Size(1445, 558);
        this.tabPage2.TabIndex = 1;
        this.tabPage2.Text = "Calibration";
        this.tabPage2.UseVisualStyleBackColor = true;

A: I found what was wrong. Posting it here in case someone else has the same problem.
I set this.tabControl1.Multiline = true; to false and the problem disappeared.


text:
Q: ValidationError with Django REST API and generic_relations for generic foreign key writable access I'm using Django REST API and generic_relations module with it to create a kind of variant to Django Comments which is not driven by templates but via REST API functions.
The Model class in named Annotation and is like:
class Annotation(BaseCommentAbstractModel):

    paragraph_id = models.PositiveIntegerField(null=False)

    body = models.TextField()
    '''
    Annotations can be written only by logged in users. It is to prevent hit and run comments by people under anonymity.
    '''
    user = models.ForeignKey(DjangoUser, null=False, verbose_name=_('user'), related_name = "annotations")

Now, there is another model, for content, which can be pretty much anything, so lets say, it is a simple Posting Application:
class BlogContent(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    body = models.TextField()
    ...
    annotation = GenericRelation(Annotation, content_type_field='content_type', object_id_field='object_pk')

The serializers for the same look like:
from generic_relations.relations import GenericRelatedField

class BlogContentSerializer(serializers.ModelSerializer):
    author_id = serializers.Field(source='author_id.username')
    annotation = serializers.RelatedField(many=True)

    class Meta:
        model = BlogContent
        fields = ('title','created','author_id',
              'data','published_flag', 'url_path','slug','annotation')

class AnnotationSerializer(serializers.ModelSerializer):
    user = serializers.Field(source='user.username')
    content_object = GenericRelatedField({
        BlogContent: serializers.HyperlinkedRelatedField(view_name='annotation:blogcontent-detail'),
        }, read_only=False)

    class Meta:
        model = Annotation
        fields = ('paragraph_id', 'body', 'user', 'content_object')

class UserSerializer(serializers.ModelSerializer):
    blogcontent= serializers.PrimaryKeyRelatedField(many=True)
    annotations = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = User
        fields = ('username', 'id', 'blogcontent', 'annotations')

Now, the problem is in the line:
    content_object = GenericRelatedField({
            BlogContent: serializers.HyperlinkedRelatedField(view_name='annotation:blogcontent-detail'),
            }, read_only=False)
If the generic relations are to be used as read only, by setting the read_only=True, then the REST API browsability is fine, but the moment I switch it to False, the server throws back a ValidationError
ValidationError at /en/annotation/
[u'Invalid model - model not available.']

Perusing the logs and the code, it seems that in rest_framework.renderers.py at get_raw_data_form(self, view, method, request) Does not find an object in the call obj = getattr(view, 'object', None).
This in turn, while evaluating field_to_native function as serializer = self.determine_deserializer_for_data(value) in generic_relations,  causes to pass nothing in as value and hence, the code breaks.
Has anybody else too encountered such error and/or could help me fix it? Please help!
The traceback is as follows:
/home/craft/pirateenv/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
            response = response.render() ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/django/template/response.py in render
        self.content = self.rendered_content ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/response.py in rendered_content
    ret = renderer.render(self.data, media_type, context) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/renderers.py in render
    context = self.get_context(data, accepted_media_type, renderer_context) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/renderers.py in get_context
    raw_data_post_form = self.get_raw_data_form(view, 'POST', request) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/renderers.py in get_raw_data_form
            content = renderer.render(serializer.data, accepted, context) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/serializers.py in data
            self._data = self.to_native(obj) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/rest_framework/serializers.py in to_native
        value = field.field_to_native(obj, field_name) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/generic_relations/relations.py in field_to_native
    serializer = self.determine_deserializer_for_data(value) ...
▶ Local vars
/home/craft/pirateenv/lib/python2.7/site-packages/generic_relations/relations.py in determine_deserializer_for_data
        raise ValidationError(self.error_messages['no_model_match']) ...
▶ Local vars

A: This issue on the repository also mentions the same error but in a different context, the solution offered, nevertheless works for me too, until the time the author releases a fix.
The solution is to add an  if value: clause after calling the super method.


text:
Q: How to prove the formula has no finite model, thus it has no finit domain I am not sure how to even start solving this problem. I tried to solve it using the semantic tree, but with no success.
It's an exercise from the book Mathematical Logic for Computer Science by Mordechai Ben-Ari, page 154, exercise 7.10.
Prove that the following formula has no finite models:
∀x∃yp(x,y)∧∀x¬p(x,x)∧∀x∀y∀z(p(x,y)∧p(y,z)→p(x,z)).

A: Note that $p$ is transitive and irreflexive. Hence, it is also asymmetric, and thus a strict partial order. This means that all objects can be ordered accordingly. Moreover, given any finite number of objects, that means that there is a 'smallest' element, i.e. an element $x$ such that for no $y$: $p(x,y)$.  However, that contradicts the $\forall x \exists y p(x,y)$. So, the domain cannot be finite.


text:
Q: Нужно скачать все файлы с внешней страницы и собрать в архив Нужно написать сценарий, который будет переходить по внешней указанной ссылке и с той страницы, на которую перейдёт скачает все файлы определённого формата, например mp3, на сервер, на сервере соберёт из в архив, который можно будет скачать.
Как это реализовать? Куда копать?

A: Я бы рассмотрел запуск wget из вашего скрипта.
wget -r -A .mp3 URL


text:
Q: Module not found: Can't resolve 'firebase/analytics' in React Js I have install newer version of firebase by  npm install -g firebase in few days ago .
Today I am making react app where I need firebase . So That is why I am trying import some firebase functions stuff in my react app by
 import { initializeApp } from "firebase/app"; But, When I import this import { initializeApp } from "firebase/app"; got this error massage
Module not found: Can't resolve 'firebase/analytics'
I how to fixed this problem ???

place note : I have already firebase globally !!!


text:
Q: How to format Visual Studio Code's underscore I am new to the programming community as I just started my work just recently.
The problem that I'm having is that my underscore looks like this "__" and not like this "_ _". I wanted to see the space between the underscores. I was fiddling with VS code settings while googling for about 3 hours, and I have yet to arrive at an answer to fix my problem.
Thank you

A: There's a configuration on VS code called "letterSpacing".
Just go to preferences and search.
If you increase the letter spacing, then the underscores will look like what you want.


text:
Q: Win10: Time since woke from sleep I want to know how many hours I have been working tonight.
So at a cmd prompt, I do this:
systeminfo|find "Time:"

That shows me the boot time.
But I booted my system yesterday morning. The computer was asleep last night, and all day today until a few hrs ago when I woke it from sleep.
So how do I find the time it woke from sleep?

A: The Windows event log can be queried from the command-line.
This command will show the most recent power event:
wevtutil qe System /rd:true /f:Text /c:1 /q:"<QueryList><Query Id='0' Path='System'><Select Path='System'>*[System[Provider[@Name='Microsoft-Windows-Kernel-Power']]]</Select></Query></QueryList>"

Sample output:
Event[0]:
  Log Name: System
  Source: Microsoft-Windows-Kernel-Power
  Date: 2020-07-30T10:19:27.250
  Event ID: 130
  Task: N/A
  Level: Information
  Opcode: Info
  Keyword: N/A
  User: N/A
  User Name: N/A
  Computer: DESKTOP-ABCDEFG
  Description:
Firmware S3 times. SuspendStart: 766335719, SuspendEnd: 766335719

The Date field gives the local time of the event, which will be the time of the last power event.
  Date: 2020-07-30T10:19:27.250

This means the PC resumed from sleep at 10:19:27 local time on July 30, 2020.
wevtutil is documented here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/wevtutil
The /rd:true flag specifies to return the most recent events.
The /c flag specifies to return only one event. More events can be returned from the log easily. For instance, to see the three most recent power events, change /c:1 to /c:3. This can be useful to see the time the system went to sleep, for example.
The /q query expression is an XPath query. It can be derived from the Windows Event Viewer application by clicking on the XML tab:

Note that in my example, I changed the double quotes to single quotes to avoid problems with the CMD shell.

A: How do I find the time it woke from sleep?
You need to look in the system event log, using Event Viewer.
Look for:
Event ID: 1
Source: Microsoft-Windows-Power-Troubleshooter

To do this:

*

*If you are using Windows 7, click on the start menu button, enter cmd, right-click cmd.exe and select Run as Administrator.

*If you are using Windows 8.x, use Windows-X to display a command menu, and select Command Prompt (Admin) from the available list.

*Type eventvwr.msc to launch the Windows Event Viewer.

*Select Windows Logs > System from the menu in the sidebar.

*Once the log is displayed, select Filter Current Log from the Actions menu.

*A new window opens up that you use to customize what is displayed in the selected event log.

*Locate Event sources there and select Power-Troubleshooter from the context menu. The list is sorted alphabetically, and you should not
  have any issues finding the filter item in the menu.

*All entries are listed by level, date and time, and Event ID.

*Open the entries closed in date and time to the waking of the PC and check for the Wake Source listing there. It may reveal what woke
  the computer.

Source How to find out why your PC wakes up, and how to stop it - gHacks Tech News
Example output:

A: Using PowerShell:
Get-WinEvent -MaxEvents 1 -FilterHashTable @{ProviderName='Microsoft-Windows-Power-Troubleshooter';LogName='System';ID='1'}

will output something like:
   ProviderName: Microsoft-Windows-Power-Troubleshooter

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2023/01/26 09:07:14              1 Information      The system has returned from a low power state....


text:
Q: Include information from a previous webpage on a contact form I'm trying to figure out how I can include information from a previous webpage on a contact form, the site is running Wordpress. Here is my scenario:

*

*I have an image gallery and a button on each image, below the image caption.

*This button links to a webpage with a contact form where a user fills in a few choices about the image.

*This form is then emailed to the website owner.

How can I include the image caption from step 1 in the contact form?

A: Add something like ?image=1 to the urls on the image. Then you can use $_GET['image'] on the next page to get the image ID.
WordPress has add_query_arg() to help you with that.

A: HTML / HTTP is stateless. In your case, use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure. Sessions store variables on the server where as the cookies get stored in the client side.
Session
//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

Cookies
//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

You can also use get GET/POST variables. For example, you can store the image caption variable on page 1, append it to the appropriate URL and then retrieve it on page 2.


text:
Q: Get the value of the first row of a UIPicker First of all, apologize because I have seen some posts about this, but I can not understand them.
My problem is this:
I have a UIPickerView that gets the values from an NSArray. Everything working perfect except when I get the value of the first row of the picker.
I have read that the method - (void) pickerView: (UIPickerView *) pickerView didSelectRow: (NSInteger) row inComponent: (NSInteger) component only runs when users scroll up or down in the picker.
So how I can get in a NSString the first value of picker?
This is my method:
 - (Void) pickerView: (UIPickerView *) pickerView didSelectRow: (NSInteger) row     inComponent: (NSInteger) component
{

 NSLog (@ "are in line% i", row);

 NSLog (@ "You've selected,% @", [array objectAtIndex: row]);

}

I have an array called "array" that he contains the data;
Thanks so much!

A: A lot people have faced similar problem (what if person selects default value in UIPickerView) and you might want to checkout following post in order to fix your particular problem:
https://stackoverflow.com/a/789633/200272


text:
Q: With Rails and Devise, how do I set the cookie properties if I'm using ActiveRecord store? In myapp/config/initializers/session_store.rb, I have the following:
Myapp::Application.config.session_store :cookie_store, :key => '_myapp_session', :domain => :all

The :key option sets the name to use for the cookie, and :domain => :all says that the cookie can be shared across subdomains.
Now I want to move to using ActiveRecord to store the session. If I do this:
Myapp::Application.config.session_store :active_record_store

... although the session is stored in the database, there is still, of course, a cookie. But I no longer have control over its name or scope.
How can I use ActiveRecord store for the session and still specify the cookie name and domain?

A: Figured it out
It's very simple, actually:
Myapp::Application.config.session_store :active_record_store, :key => '_myapp_session', :domain => :all