Q:

mciSendstring ¿system.nullreferenceexception?

Tengo una clase con este código:
class Mp3Player
{
    [DllImport("winmm.dll")]
    private static extern long mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

    public string returnData;
    private string command;

    public void Open(string file)
    {
        Close();
        command = "open \"" + file + "\" type MPEGVideo alias MyMp3";
        mciSendString(command, null, 0, 0);
    }

    public void Close()
    {
        command = "close MyMp3";
        mciSendString(command, null, 0, 0);
    }

    public void Play()
    {
        command = "play MyMp3";
        mciSendString(command, null, 0, 0);
    }

    public void Stop()
    {
        command = "stop MyMp3";
        mciSendString(command, null, 0, 0);
        Close();
    }

    public bool IsPlaying()
    {
        command = "status MyMp3 mode";
        mciSendString(command, returnData, 128, 0);

        string estado = "playing";
        if (returnData.Contains(estado))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

Es para reproducir un archivo mp3 con la dll "winmm.dll", he visto varios ejemplos de código
y he tomado solo lo que a mi me interesa que son los métodos más básicos.
Todos los métodos me funcionan excepto el "IsPlaying()" que me da error ¿porque?
al parecer devuelve null, pero he leído como 50 veces la documentación y supuestamente está bien.
He probado de todo y no logro que me devuelva el estado.

A:

Por lo que estoy leyendo aquí, el segundo parámetro del método mciSendString debe ser un buffer donde se recibirá la información.

Pointer to a buffer that receives return information. If no return information is needed, this parameter can be NULL.

En tu caso, estás llamando al método con tu variable returnData, pero returnData es null, nunca la inicializas. Al pasarle un null como segundo parámetro, la función mciSendString lo ignora.
Es decir, una vez llamado el método, tu variable returnData sigue siendo null.
Por ello, la línea returnData.Contains(estado) lanza la NullPointerException.
Se solucionaría simplemente inicializando returnData con un string vacío.
class Mp3Player
{
    [DllImport("winmm.dll")]
    private static extern long mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

    public string returnData = string.Empty;
    private string command;

    // ...

    public bool IsPlaying()
    {
        command = "status MyMp3 mode";
        mciSendString(command, returnData, 128, 0);

        string estado = "playing";

        return returnData.Contains(estado);
    }
}

Espero que sirva.


Q:

Why doesn't a compareTo BigInteger while loop exit?

I have this method that is stuck in a while loop, I print the boolean value of the condition in the method itself and it does eventually get to be false but it will not exit the cycle.
    public static boolean isPalindrome(BigInteger num) {
         BigInteger invertedNum = BigInteger.valueOf(0);
         BigInteger auxNum = num;

         while (auxNum.compareTo(BigInteger.valueOf(0)) != 0) {
             invertedNum = invertedNum.multiply(BigInteger.valueOf(10)).add(auxNum.divide(BigInteger.valueOf(10)));
             auxNum = auxNum.divide(BigInteger.valueOf(10));
             System.out.println(auxNum.compareTo(BigInteger.valueOf(0)) != 0);
    }

    return invertedNum == num;
}

A:

I ran your code and it works fine; the while loops exits.
Your code does have 2 bugs in it:

in the .add(auxNum.divide) call I assume you want mod instead.
you can't compare bigints with ==. You must use .equals (in the while loop you use .compareTo which works fine, but .equals is more readable, in that it correctly expresses what you're trying to accomplish. You're comparing with == at the very end, in the return statement.

Applying those 2 fixes, your code correctly returns true for palindromic (in decimal) numbers, and false otherwise.


Q:

SVG animation start position

i have a small SVG animation that i have been playing around with and i was wondering if there is a simple solution for the following issue.
Is there a way of changing the start point of where the circle starts? As it always seems to start on the right hand 3 o'clock position and goes around clockwise. Ideally i want it to start where and when the line finishes animating. Example: http://jsfiddle.net/matta70/7jvd6fsx/1/
 .line {
    stroke-dasharray: 650;
    stroke-dashoffset: 650;
    animation: offset 3s linear forwards;
 }
 .circle {
    stroke-dasharray: 230;
    stroke-dashoffset: 230;
    animation: offset 3s linear forwards;

 }

 /*========================
 *      KEYFRAMES
 */

 @keyframes offset {
    100% {
        stroke-dashoffset: 0;

    }
 }

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="577px"
     height="74px" viewBox="0 0 577 74" enable-background="new 0 0 577 74" xml:space="preserve">
    <g id="Layer_1">
        <line class="line" fill="none" stroke="#000000" stroke-width="2" x1="0" y1="37" x2="504" y2="37"/>
        <circle class="circle" fill="none" stroke="#000000" stroke-width="2" cx="540" cy="37" r="36"/>
        <circle fill="none" stroke="#000000" stroke-width="2" cx="540" cy="37" r="18"/>
    </g>
</svg>

A:

You need to use
transform="rotate(<angle>)"

here a working code
<style>
 .line {
     stroke-dasharray: 650;
     stroke-dashoffset: 650;
     animation: offset 3s linear forwards;
 }
 .circle {
     stroke-dasharray: 230;
     stroke-dashoffset: 230;
     animation: offset 1s linear forwards 2.3s;
 }
 /*========================
     *      KEYFRAMES
     */
 @keyframes offset {
     100% {
         stroke-dashoffset: 0;
     }
 }
</style>
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="577px" height="74px" viewBox="0 0 577 74" enable-background="new 0 0 577 74" xml:space="preserve">
<g id="Layer_1">
    <line class="line" fill="none" stroke="#000000" stroke-width="2" x1="0" y1="37" x2="504" y2="37" />
    <circle class="circle" transform="rotate(180 540 37)"  fill="none" stroke="#000000" stroke-width="2" cx="540" cy="37" r="36" />
    <circle fill="none" stroke="#000000" stroke-width="2" cx="540" cy="37" r="18" />
</g>

You can find a well explained tutorial here
Here there is a Jsfiddle copied from somewhere, time ago. (hove image)
Hope this help


Q:

how to change width of drop down menu responsive bootstrap

I use the responsive navbar from bootstrap. I want to change the width that changes to the drop down menu the default of this width is 768px but I want to change it with respect to my width. How should I do that I think I should do that with jquery using $(windows).resize() event.
Here is a sample of bootstrap navbar:

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Brand

Link

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left" role="search">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

          Dropdown

Action

Another action

Something else here

Separated link

A:

I think there are two ways of doing this by using customization. Perhaps the fastest way to customize your bootstrap.css file is to use the Customizer at http://getbootstrap.com/customize/.
At there you can change value for @grid-float-breakpoint. I tested with value 480px (original value was @screen-sm, which is same as 768px) After that click “Compile and Download” button at the end of the Customizer page. This will change the break point when the navbar collapses. At the bootstrap.css file for instance the following value is changed from
@media (min-width: 768px) {
  .navbar-collapse {
    width: auto;
    border-top: 0;
    box-shadow: none;
  }

to this one below. The previous @media setting is from the default bootstrap.css download without customization.
@media (min-width: 480px) {
  .navbar-collapse {
    width: auto;
    border-top: 0;
    -webkit-box-shadow: none;
            box-shadow: none;
  }

The second way of changing these settings is using LESS and compile the same value from source code. If you decide to make your own compilation, you can discover variable @grid-float-breakpoint at variables.less file at less directory of your bootstrap source installation (Bootstrap_dir/less/variables.less). More info at Compiling CSS and JavaScript and at Bootstrap 3 Less Workflow Tutorial


Q:

Check if picture is the same

Is it possible to check if two picture are identical with php?
(I want to check if a picture of an event from facebook is the dafault, or not)
Thanks, John

A:

I'd use a hashing algorithm and compare the two hashes:
if ( sha1_file ( $file1 ) === sha1_file ( $file2 ) ) {
  // They're identical
} else {
  // They're not
}

This uses sha1_file, but you could use any hashing algorithm.. MD5 for instance


Q:

F# Create function at runtime

I know it is related to this SO question and this one, but I want to know, if (and how) it is possible to create new F# functions at runtime.
By this I mean something like using the REPL without showing it. Is there any other option than CodeDOM and Reflection or Quotations?
If it is not possible in F#, is it possible in any other .Net Language?

A:

Sure you can, that's what the DLR (Dynamic Language Runtime) is for. It's used by IronPython, IronRuby, and other dynamic languages which work exactly as you describe. The DLR is just a library, so you can use it from within F# if you want.
Another option is to implement similar functionality using F#'s higher-order functions -- this would be very flexible, but ultimately somewhat slower because the .NET CLR won't be able to do much (if anything) in the way of optimization.


Q:

Streamlined probability measure for tossing infinitely many coins

The standard probability measure over countably many independent coin tosses (i.e., the probability that you get a prescribed prefix of length $v$ is $2^{-v}$) is usually obtained via results in measure theory (at least, that's what I have seen).  Is there a streamlined presentation out there that uses the least possible amount of results from measure theory (ideally, none) to show that this is indeed a valid probability measure?

A:

This version is due to Emile Borel ...
Sequence of heads & tails encoded as 0s and 1s, then sequence is taken to represent a number in $[0,1]$ in its binary expansion.  The measure is Lebesgue measure.
So you still need to know that Lebesgue measure exists.


Q:

Following  links on mouse down instead of on mouse click

I am using the following code to make the browser follow a link on mouse down instead of on mouse up (like a normal click).
$('#links a').each(function(){
  $(this).mousedown(function(){
    window.location.href=$(this).attr('href');
  });
});

First of all, is this good practice? GMail does this and it gives the effect that the page is loading faster than it actually is.
Also, is there a better way of doing this? I haven't tested this in all browsers yet, so I'm not sure if it works in older browsers.

A:

The mousedown function is not supported by Internet Explorer version 5.5 or earlier.        jQuery normalizes the browser-specific behavior of the event capture into the mousedown function.
As to good practice or not, I don't see a tangible performance benefit from handling mouse click events in this way.  So, unless you have a specific reason for doing so, I would stay with standard conventions.


Q:

Rails. Save pass parameter from action to action

For example, user visiting home with invitation link localhost:3000/home?invitation=invitation_token and I want to keep in params while user is browsing site till he visit registration page.
I know there is possibility to add params to link_to method but there is to many where I need to put this and it's not possible to predict user behavior.
But what I'm looking it's custom method what I will place in before_action what will check if there is params[:invitation] and pass it to next, unpredictable, method.
PS. I know that I can save to cookies, but this is not quite what I'm looking for.

A:

You should save it in a session variable such as session[:invitation_token], otherwise you'll have to pass the param in every link. You can then use the variable directly such as:
before_action :check_token

def check_token
  redirect_to registration_url unless session[:invitation_token]
end


Q:

z3py: how to ask which constructor my adt instance has?

Suppose I have a datatype, for example:
List = Datatype('List')
List.declare('cons', ('car', IntSort()), ('cdr', List))
List.declare('nil')
List = List.create()

And I have an instance, by:
s.check()
instance = s.model()[var]

How can i ask which constructor my instance has?
I know I could do something like this:
for i in range(List.num_constructors()):
    if List.recognizer(i)(instance):
        break
return List.constructor(i)

But this is not a very practical way when the number of constructors is large.
How can i ask this?

A:

Python interface defines recognizers is_cons, is_nil for you, which you can then use for simplifying your code. Something like:
from z3 import *

List = Datatype('List')
List.declare('cons', ('car', IntSort()), ('cdr', List))
List.declare('nil')
List = List.create()

# constructors
cons = List.cons
car  = List.car
cdr  = List.cdr
nil  = List.nil

# recognizers
def is_cons (x): return simplify(List.is_cons(x))
def is_nil  (x): return simplify(List.is_nil(x))

def valToConstructor(l):
    if is_cons(l):
        return "Found cons"
    elif is_nil(l):
        return "Found nil"
    else:
        raise Exception('Unexpected list value: {}'.format(l))

# example:
ex1 = nil
ex2 = cons (0, cons (1, ex1))

print valToConstructor(ex1)
print valToConstructor(ex2)

When run, this produces:
Found nil
Found cons

Note that you cannot skip the exception case in valToConstructor since this function might be called with a symbolic value as well; and the recognizers would not fire for those values. But if you always call it with values you get out of a model, it should work just fine.
Directly accessing the constructor
You can also use the decl function for the underlying AST:
>>> ex1.decl()
nil
>>> ex2.decl()
cons

But you have to be careful when the object you're passing is a symbolic value; as in that case decl returns its name:
>>> ex3 = Const('ex3_name', List)
>>> ex3.decl()
ex3_name

But perhaps this is precisely what you're looking for.


Q:

In a canvas, is it better to have a single context or multiples?

i'm currently developing a js app.
I'm not a js expert so i'm asking for tips.
My question is:
Is it good practice (performance-wise as well) to draw in a canvas with an array of context or it is better to have a single context with all the drawing inside?
Case 1:
for (i = 0; i < 8; i++) {
    contextAr[i] = canvasAr.getContext('2d');
    contextAr[i].beginPath();
    contextAr[i].arc(canvasAr.width / 2, canvasAr.height / 2, ...
}

Case 2:
contextAr.beginPath();
contextAr.arc(...);
contextAr.moveTo(...);
contextAr.LineTo(...);

A simple example could be a circle divided in 4 quarters. Should i treat the draw with a single context or should i treat each pieces separately.
I think i'm not fully grasping the meaning of context though.
Is contextAr[i] = canvasAr.getContext('2d'); a redundant call?
I would not be surprise if contextAr[i] had identical elements.
Thank you.

A:

It's rather pointless obtaining a 2D context several times from the same canvas element as the same context object will be returned.
From the standard (my emphasis) -

Return the same object as was returned the last time the method was
  invoked with this same first argument.

So the common and best practice is to obtain a single reference to a context per canvas element and use that successively.


Q:

Bootstrap Collapse Not Working with JQuery

This is driving me insane.
I have this:

                Records Added

And I am trying to fire the collapse with this (in various ways):
$('#collapseDiv').collapse("toggle")
All I get is:

Uncaught TypeError: $(...).collapse is not a function(…)

Any ideas?
```
```

A:

Make sure Jquery is included above Bootstrap, it works fine

$('#collapseDiv').collapse("toggle");
.white-link{color:#fff;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

      Records Added

A:

I was having the same problem.... So in JQuery I did something like this:
$('#collapseDiv').removeClass('show');

As mentioned in official doc...

.collapse hides content
.collapsing is applied during transitions
collapse.show shows content

so that is why I removed 'show' class and it worked for me... only drawback is that it hides immediately (without any animation)


Q:

Company mode (Emacs plugin) back-end could not be initialized?

Every time I initiate company-mode with M-x company-mode this message shows up:
Company back-end 'company-semantic' could not be initialized
Company back-end 'company-ropemacs' could not be initialized
Company back-end 'company-pysmell' could not be initialized

The completion works but I wonder whats the meaning of that message and how to fix it.
EDIT: I moved company-semantic.el company-ropemacs.el company-pysmell.el to ~.emacs.d\plugins\company-0.4.3\unused-backends but I'm still getting that error.

A:

Instead of changing your company-mode install directory. Just define company-backends in your .emacs file. E.g.
(setq company-backends '(company-elisp
                         company-ropemacs
                         company-gtags
                         company-dabbrev-code
                         company-keywords
                         company-files
                         company-dabbrev))

Excluding the backends you do not want to support from the list.

A:

semantic, ropemacs and pysmell are all emacs extensions. Do you have them installed?
If you don't intend to use them, a quick workaround would be to remove or move that files that define those back-ends, which would prevent company mode from trying to load them.
cd /location/of/company
mkdir unused-backends
mv company-semantic.* company-ropemacs.* company-pysmell.* unused-backends/
As long as you do not add unused-backends to your load-path, this will fix the problem.
If you want to use those backends (semantic is a parser for better context-appropriate emacs actions based on language, pysmell and ropemacs are both for usage with python), then installing them should fix this problem.


Q:

Express is rewriting the body on a curl call

I am new to node js & express. I was able to get my first Node JS form today and it is working as expected. So I wanted to recreate the same on Express, but for some reason I am programmatically failing at it. I am able to track the headers and the body down, but for some reason I am failing to understand why would Express rewrite the way body is being handled.
I am adding in my findings. Below is the code, this was generated via express command line tool. This is the app.js file, the method upload is looking for some data. I am not handling any file uploads at the moment, I am only looking for some text to come across.
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

/**custom stuff**/

app.post('/upload',function(req, res){
        console.log(req.header('Content-Type'));
        console.log(req.header('Host'));
        console.log(req.header('User-Agent'));

        console.log(req.body);
        res.send("Hello the response is "+req.body.username);
});

/** end**/

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Now I make a curl call to the function.
curl -d '{"username":"myname"}' -H 'Content-Type: application/x-www-form-urlencoded' http://localhost:3000/upload

And these are the headers and the body.(headers end at line 3, body is on line 4)
application/x-www-form-urlencoded
localhost:3000
curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
{ '{"username":"myname"}': '' }
POST /upload 200 7ms - 36b

Now, I used Advanced Rest Client App for Google Chrome and below are the headers and the body.
application/x-www-form-urlencoded
localhost:3000
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
{ username: 'myname from adv rest client app' }
POST /upload 200 5ms - 58b

So, the one thing that is confusing me is why would the body for the request made by the rest client app be well formed and intact while the body from my request is distorted. Can anyone help me out with this here.
Thank you

A:

The issue may be in the data/header combination of the curl command, as there seems to be a mismatch between the data format used (JSON):
-d '{"username":"myname"}'

And the format specified (URL-encoded):
-H 'Content-Type: application/x-www-form-urlencoded'

For URL-encoded data, try:
-d 'username=myname'

Also, since you're working with file uploads, you'll likely want to specify multipart/form-data or use the -F/--form option which sets it:
curl -F 'username=myname' http://localhost:3000/upload


Q:

How can I implement blocking using Django-relationships?

I've been using django-relationships to allow users to follow each other. If Bob follows Joe. Bob will be able to see all of Joe's photos. However if Bob blocks John, John will not be Bob's photos.
My problem is that I don't know how to restrict content from a blocked user. I've seen the examples but I still can't seem to find a solution.
Assume Photographer is a FK to User
Here is my FollowingPhoto resource (this resources returns all photos that belong to the people that the user is following):
FollowingPhoto(ModelResource):
     photographer = fields.ForeignKey(PhotographerResource, 'photographer', full=True)
     class Meta:
          queryset = Photo.objects.all().order_by('-postTime')
          resource_name = 'following'
          fields = ['id', 'title', 'url', 'likes','postTime','photographer', 'location_id', 'location_name']
          authentication = BasicAuthentication()
          authorization = DjangoAuthorization()
          serializer = Serializer(formats=['json'])
          include_resource_uri = False
          filtering = {
                 'postTime': ALL,
                 'photographer' : ALL_WITH_RELATIONS,

         }

     def get_object_list(self, request):
             return super(FollowingPhoto, self).get_object_list(request).filter(photographer__user__in = request.user.relationships.following())

Now as you may have noticed with my get_object_list, it returns all the content from the users I am following. How can prevent users who are blocked from showing up on this list?
The Django-relationships app generates two tables in postgresql, the table below is the relationships_relationships table:
    id       from_user    to_user_id   status_id            created
[PK] serial   integer      integer                         timestamp
    6            1            5           1         2012-10-05 20:10:29.848667+00"
    7            1            3           1         2012-10-05 20:11:23.319961+00"

And the other table is the relationships_relationshipstatus table:
    id          name          verb         from_slug        login_required   private
[PK] serial   character     character   character varying      boolean       boolean
    1         Following      follow         friends             FALSE         FALSE
    2         Blocking        block         !                   TRUE          TRUE

Below I have added a link to Django-relationships models.py so that you may get further clarification:
models.py

A:

It looks to me like you just need a .exclude clause - something like:
def get_object_list(self, request):
     return super(FollowingPhoto, self).get_object_list(request).filter(photographer__user__in = request.user.relationships.following()).exclude(photographer__user__in=request.user.relationships.blocking())

That will prevent Bob from seeing John's photos if Bob is blocking John.  Given that Bob only sees John's photos if Bob is following John, it will do nothing unless Bob is both following and blocking John, which seems odd to me - do you maybe want Bob to not see John's photos if John is blocking Bob instead?  If so:
def get_object_list(self, request):
    return super(FollowingPhoto, self).get_object_list(request).filter(photographer__user__in = request.user.relationships.following()).exclude(photographer__user__in=request.user.relationships.blockers())


Q:

use response write to make a link

I have a urlcolumn and a title column and i want the link to be automatically made in asp
 <%response.write(rs.fields.item("titlecolumn"))%>

A:

At the minimum, you will need to quote the output value for Response.Write to work, i.e.
<%Response.Write("" + rs.fields.item("titlecolumn") + "")%>

EDIT (updated my code sample).
EDIT #2 - Make sure to clean any input going into these links.  Creating links this way makes you very vulnerable to a XSS attack (especially since the href attribute can actually execute Javascript).


Q:

Git - Break a piece of code off from Master and make it a Branch

I have a project I've been working on for quite some time, but have never released.  I have a feature I started working on (multiplayer support) and then I realized I do not want to include in version 1.0.
I recently started controlling my source-code with git. I committed my entire source code as "initial version commit" on master.
I'm using the branch-for-each-new-feature structure that is popular.
I would like to remove the multiplayer code from "master" and put it into a branch called "multiplayer".  This way I can make the rest of the changes I need for v1.0, release v1.0 without any multiplayer code, and then after v1.0 is released, I can rebase my multiplayer branch, start working on it, and have it be included in v2.0.
This is  a bit of a strange problem because the issue arose because I started using git to version control a project halfway through.  I haven't seen anything on the net proposing a way to address this.
I have a solution in mind, but it seems bad.  I will post it below as an answer, but not accept it.  Hopefully someone will be able to provide a better answer.  Thank you.

A:

git checkout master
git checkout -b multiplayer (This will create a branch, called multiplayer, for your feature  based on your master)
Few possibilities:

If you have clear commits of this feature you can revert them: git
revert _your_hash_
If you have clear commits of this feature you can remove them from
the history by rebasing, you will have to push force after : git
rebase HEAD~x -i x is the number of commits behind you want to check,
you can delete a line to remove it, -i is interactive.
You should do a cleanup commit and remove your code on the master.


Q:

Jquery cycle 2 carousel not working no console errors

It's just not activating at all. I copied the code exactly as it is in the demo page of the plugin, Is there somethign I have missed?

    << Prev
     Next >>

</div

A:

in order to auto-activate a slider or a carousel with cycle, you have to use the default class name "cycle-slideshow" otherwise you have to declare which class the plugin has to looking for:

Don't forget to use a well clean code writing. You're missing some closure in your tags.
This is fiddle to show the working code.


Q:

Get hidden form values jquery star rating

I have a question regarding the jQuery Star-Rating plugin.
I have many items to rate on one page, so I have added some hidden fields to each rating form.
The problem is I cannot get these values posted.
Here's an example:
<form method="post" id="rate" action="rate.php">
  <input name="rating" type="radio" class="auto-submit-star {split:4}" value="9.75" />
  <input name="rating" type="radio" class="auto-submit-star {split:4}" value="10.00" />
  <input type="hidden" id="post_id" value="1" />
  <input type="hidden" id="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>"/>
</form>

The plugin uses a callback like this:
<script type="text/javascript">
  $(function() {
    $('.auto-submit-star').rating({
      callback: function(value, link) {
        alert("The value selected was '" + value + "'\n\nWith this callback function I can automatically submit the form with this code:\nthis.form.submit();");
      }
    });
  });
</script>

When a star is clicked I get the prompted message, that is all good, except I can't figure out how to also get the post_id and ip values.
I have tried :
var values = $('#rate').serialize();
alert (values);

However it always returns Object Object, it looks like only the number gets send to the function.
Is there a way to also send the other 2 fields?

A:

You just have to set a name attribute for these inputs:
<form method="post" id="rate" action="rate.php">
  <input name="rating" type="radio" class="auto-submit-star {split:4}" value="9.75" />
  <input name="rating" type="radio" class="auto-submit-star {split:4}" value="10.00" />
  <input name="postId" type="hidden" id="post_id" value="1" />
  <input name="ip" type="hidden" id="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>"/>
</form>


Q:

Removing repeated characters in String

I am having strings like this "aaaabbbccccaaddddcfggghhhh" and i want to remove repeated characters get a string like this "abcadcfgh".
A simplistic implementation for this would be :
for(Character c:str.toCharArray()){
  if(c!=prevChar){
    str2.append(c);
    prevChar=c;
  }

}

return str2.toString();

Is it possible to have a better implementation may be using regex?

A:

You can do this:
"aaaabbbccccaaddddcfggghhhh".replaceAll("(.)\\1+","$1");

The regex uses backreference and capturing groups.
The normal regex is (.)\1+ but you've to escape the backslash by another backslash in java.
If you want number of repeated characters:
String test = "aaaabbbccccaaddddcfggghhhh";
System.out.println(test.length() - test.replaceAll("(.)\\1+","$1").length());

Demo


Q:

“IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory” in arquillian

java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory. is caused by the presence of a JSF API inside a dependency. I'm eager to provide dependencies in the WAR or EAR of my Java EE applications instead of using the dependency artifacts provided by the server because that increases flexibility when it comes to necessary updates (assuming that updating the server artifacts) in my experience. That makes it easy to compare a deployment on Payara 4.1.2.181 to one to the embedded version done by Arquillian. I control the classloading with <class-loader delegate="false"/> added to /WEB-INF/glassfish-web.xml.
Unfortunately, the error message is not helpful and afaik one has to go through the Maven dependencies and test exclusions in a trial-error approach. There're some "usual suspects" which are worth trying which I collected from different posts: jsf-impl.jar, javax.faces.jar, jsf-api.jar, javaee.jar.
Given a fairly simple JSF project with 1 backing bean producing "Hello world!" for a h:outputLabel the deployment works on Payara, but not with Arquillian with the functional test
@RunWith(Arquillian.class)
@RunAsClient
public class FunctionalIT {
    private final static Logger LOGGER = LoggerFactory.getLogger(FunctionalIT.class);

    @Deployment(testable = false)
    public static Archive<?> createDeployment0() throws TransformerException, XPathExpressionException, ParserConfigurationException, SAXException, IOException {
        WebArchive retValue = Maven.configureResolver().workOffline().resolve("richtercloud:arquillian-assertt-statements-web:war:1.0-SNAPSHOT")
                .withoutTransitivity().asSingle(WebArchive.class);
        ByteArrayOutputStream archiveContentOutputStream = new ByteArrayOutputStream();
        retValue.writeTo(archiveContentOutputStream, Formatters.VERBOSE);
        LOGGER.info(archiveContentOutputStream.toString());
        return retValue;
    }

    @Drone
    private WebDriver browser;
    @ArquillianResource
    private URL deploymentUrl;
    @FindBy(id = "helloWorldLabel")
    private WebElement helloWorldLabel;

    @Test
    public void testAll() {
        browser.get(deploymentUrl.toExternalForm()+"/index.xhtml");
        LOGGER.info(browser.getPageSource());
        new WebDriverWait(browser, 10).until(ExpectedConditions.visibilityOf(helloWorldLabel));
    }
}

since the Arquillian deployment fails due to (the functional test is run with the maven-failsafe-plugin)
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.
    at javax.faces.FactoryFinderInstance.getFactory(FactoryFinderInstance.java:541)
    at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:292)
    at javax.faces.webapp.FacesServlet.init(FacesServlet.java:374)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1435)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1243)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5468)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5713)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:609)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2057)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1703)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:294)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:357)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.initialize(ApplicationLifecycle.java:526)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:510)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:549)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:545)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:544)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:575)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:567)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:566)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1474)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:111)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1856)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1732)
    at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:134)
    at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:110)
    at org.jboss.arquillian.container.glassfish.embedded_3_1.GlassFishContainer.deploy(GlassFishContainer.java:193)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:151)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:118)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:239)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deploy(ContainerDeployController.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.container.impl.client.container.DeploymentExceptionHandler.verifyExpectedExceptionDuringDeploy(DeploymentExceptionHandler.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createDeploymentContext(ContainerDeploymentContextHandler.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createContainerContext(ContainerDeploymentContextHandler.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:62)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:92)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:77)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachDeployment(ContainerDeployController.java:232)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachManagedDeployment(ContainerDeployController.java:212)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deployManaged(ContainerDeployController.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:62)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:96)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:80)
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:179)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:384)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:193)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:148)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:369)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:275)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:239)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:160)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:373)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:334)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:119)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:407)

Now, I don't seem to be able to apply the solution provided in the link above since there seems to be no dependency matching or similar to the ones listed above:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] arquillian-assertt-statements
[INFO] arquillian-assertt-statements-web
[INFO] arquillian-assertt-statements-it
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building arquillian-assertt-statements 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ arquillian-assertt-statements ---
[INFO] richtercloud:arquillian-assertt-statements:pom:1.0-SNAPSHOT
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building arquillian-assertt-statements-web 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ arquillian-assertt-statements-web ---
[INFO] richtercloud:arquillian-assertt-statements-web:war:1.0-SNAPSHOT
[INFO] +- org.primefaces:primefaces:jar:6.1:compile
[INFO] \- javax:javaee-web-api:jar:7.0:provided
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building arquillian-assertt-statements-it 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ arquillian-assertt-statements-it ---
[INFO] richtercloud:arquillian-assertt-statements-it:jar:1.0-SNAPSHOT
[INFO] +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] +- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-javaee:jar:2.0.0:test
[INFO] |  \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-base:jar:2.0.0:compile
[INFO] +- org.jboss.arquillian.junit:arquillian-junit-container:jar:1.2.0.Final:test
[INFO] |  +- org.jboss.arquillian.test:arquillian-test-api:jar:1.2.0.Final:compile
[INFO] |  |  \- org.jboss.arquillian.core:arquillian-core-api:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.test:arquillian-test-spi:jar:1.2.0.Final:compile
[INFO] |  |  \- org.jboss.arquillian.core:arquillian-core-spi:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-test-api:jar:1.2.0.Final:compile
[INFO] |  |  \- org.jboss.shrinkwrap:shrinkwrap-api:jar:1.2.6:compile
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-test-spi:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.core:arquillian-core-impl-base:jar:1.2.0.Final:test
[INFO] |  +- org.jboss.arquillian.test:arquillian-test-impl-base:jar:1.2.0.Final:test
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-impl-base:jar:1.2.0.Final:test
[INFO] |  |  +- org.jboss.arquillian.config:arquillian-config-api:jar:1.2.0.Final:compile
[INFO] |  |  +- org.jboss.arquillian.config:arquillian-config-impl-base:jar:1.2.0.Final:compile
[INFO] |  |  \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-spi:jar:2.0.0:compile
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-test-impl-base:jar:1.2.0.Final:compile
[INFO] |  \- org.jboss.shrinkwrap:shrinkwrap-impl-base:jar:1.2.6:test
[INFO] |     \- org.jboss.shrinkwrap:shrinkwrap-spi:jar:1.2.6:test
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-depchain:pom:2.2.6:test
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api:jar:2.2.6:compile
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-spi:jar:2.2.6:test
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-spi-maven:jar:2.2.6:test
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api-maven-archive:jar:2.2.6:test
[INFO] |  +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven:jar:2.2.6:test
[INFO] |  |  +- org.eclipse.aether:aether-api:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.eclipse.aether:aether-impl:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.eclipse.aether:aether-spi:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.eclipse.aether:aether-util:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.eclipse.aether:aether-connector-basic:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.eclipse.aether:aether-transport-wagon:jar:1.0.0.v20140518:test
[INFO] |  |  +- org.apache.maven:maven-aether-provider:jar:3.2.5:test
[INFO] |  |  +- org.apache.maven:maven-model:jar:3.2.5:test
[INFO] |  |  +- org.apache.maven:maven-model-builder:jar:3.2.5:test
[INFO] |  |  |  \- org.codehaus.plexus:plexus-component-annotations:jar:1.5.5:test
[INFO] |  |  +- org.apache.maven:maven-repository-metadata:jar:3.2.5:test
[INFO] |  |  +- org.apache.maven:maven-settings:jar:3.2.5:test
[INFO] |  |  +- org.apache.maven:maven-settings-builder:jar:3.2.5:test
[INFO] |  |  +- org.codehaus.plexus:plexus-interpolation:jar:1.21:test
[INFO] |  |  +- org.codehaus.plexus:plexus-utils:jar:3.0.20:test
[INFO] |  |  +- org.sonatype.plexus:plexus-sec-dispatcher:jar:1.3:test
[INFO] |  |  |  \- org.sonatype.plexus:plexus-cipher:jar:1.4:test
[INFO] |  |  +- org.apache.maven.wagon:wagon-provider-api:jar:2.6:test
[INFO] |  |  +- org.apache.maven.wagon:wagon-file:jar:2.6:test
[INFO] |  |  |  \- commons-lang:commons-lang:jar:2.6:test
[INFO] |  |  \- org.apache.maven.wagon:wagon-http-lightweight:jar:2.6:test
[INFO] |  |     \- org.apache.maven.wagon:wagon-http-shared:jar:2.6:test
[INFO] |  \- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven-archive:jar:2.2.6:test
[INFO] |     +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-spi-maven-archive:jar:2.2.6:test
[INFO] |     +- org.eclipse.sisu:org.eclipse.sisu.plexus:jar:0.3.0.M1:test
[INFO] |     |  \- org.eclipse.sisu:org.eclipse.sisu.inject:jar:0.3.0.M1:test
[INFO] |     \- org.codehaus.plexus:plexus-compiler-javac:jar:2.3:test
[INFO] |        \- org.codehaus.plexus:plexus-compiler-api:jar:2.3:test
[INFO] +- org.jboss.arquillian.graphene:graphene-webdriver:pom:2.3.2:test
[INFO] |  +- org.jboss.arquillian.graphene:graphene-webdriver-api:jar:2.3.2:test
[INFO] |  +- org.jboss.arquillian.graphene:graphene-webdriver-spi:jar:2.3.2:test
[INFO] |  +- org.jboss.arquillian.graphene:graphene-webdriver-impl:jar:2.3.2:test
[INFO] |  |  +- org.jboss.arquillian.extension:arquillian-drone-impl:jar:2.5.0:test
[INFO] |  |  +- org.jboss.arquillian.extension:arquillian-drone-configuration:jar:2.5.0:test
[INFO] |  |  +- cglib:cglib-nodep:jar:3.2.5:compile
[INFO] |  |  \- org.objenesis:objenesis:jar:1.2:compile
[INFO] |  \- org.jboss.arquillian.extension:arquillian-drone-webdriver-depchain:pom:2.5.0:test
[INFO] |     +- org.jboss.arquillian.extension:arquillian-drone-spi:jar:2.5.0:test
[INFO] |     \- org.jboss.arquillian.extension:arquillian-drone-webdriver:jar:2.5.0:test
[INFO] |        +- org.arquillian.spacelift:arquillian-spacelift:jar:1.0.2:test
[INFO] |        |  \- org.arquillian.spacelift:arquillian-spacelift-api:jar:1.0.2:test
[INFO] |        +- org.jsoup:jsoup:jar:1.8.3:test
[INFO] |        \- org.awaitility:awaitility:jar:3.0.0:test
[INFO] |           \- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] +- com.codeborne:phantomjsdriver:jar:1.4.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-api:jar:3.9.1:compile
[INFO] |  \- org.seleniumhq.selenium:selenium-remote-driver:jar:3.9.1:compile
[INFO] +- org.seleniumhq.selenium:htmlunit-driver:jar:2.28:compile
[INFO] |  \- org.seleniumhq.selenium:selenium-support:jar:3.9.1:compile
[INFO] +- net.sourceforge.htmlunit:htmlunit:jar:2.24:compile
[INFO] |  +- xalan:xalan:jar:2.7.2:compile
[INFO] |  |  \- xalan:serializer:jar:2.7.2:compile
[INFO] |  +- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] |  +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] |  +- org.apache.httpcomponents:httpmime:jar:4.5.2:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.10:compile
[INFO] |  +- net.sourceforge.htmlunit:htmlunit-core-js:jar:2.23:compile
[INFO] |  +- net.sourceforge.htmlunit:neko-htmlunit:jar:2.24:compile
[INFO] |  |  \- xerces:xercesImpl:jar:2.11.0:compile
[INFO] |  |     \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |  +- net.sourceforge.cssparser:cssparser:jar:0.9.21:compile
[INFO] |  |  \- org.w3c.css:sac:jar:1.3:compile
[INFO] |  +- commons-io:commons-io:jar:2.5:compile
[INFO] |  +- commons-logging:commons-logging:jar:1.2:compile
[INFO] |  \- org.eclipse.jetty.websocket:websocket-client:jar:9.2.20.v20161216:compile
[INFO] |     +- org.eclipse.jetty:jetty-util:jar:9.2.20.v20161216:compile
[INFO] |     +- org.eclipse.jetty:jetty-io:jar:9.2.20.v20161216:compile
[INFO] |     \- org.eclipse.jetty.websocket:websocket-common:jar:9.2.20.v20161216:compile
[INFO] |        \- org.eclipse.jetty.websocket:websocket-api:jar:9.2.20.v20161216:compile
[INFO] +- org.seleniumhq.selenium:selenium-java:jar:3.9.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-chrome-driver:jar:3.9.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-edge-driver:jar:3.9.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-ie-driver:jar:3.9.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-opera-driver:jar:3.9.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-safari-driver:jar:3.9.1:compile
[INFO] |  +- net.bytebuddy:byte-buddy:jar:1.7.9:compile
[INFO] |  +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO] |  +- com.google.code.gson:gson:jar:2.8.2:compile
[INFO] |  +- com.google.guava:guava:jar:23.6-jre:compile
[INFO] |  |  +- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO] |  |  +- org.checkerframework:checker-compat-qual:jar:2.0.0:compile
[INFO] |  |  +- com.google.errorprone:error_prone_annotations:jar:2.1.3:compile
[INFO] |  |  +- com.google.j2objc:j2objc-annotations:jar:1.1:compile
[INFO] |  |  \- org.codehaus.mojo:animal-sniffer-annotations:jar:1.14:compile
[INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.4.6:compile
[INFO] |  +- com.squareup.okhttp3:okhttp:jar:3.9.1:compile
[INFO] |  \- com.squareup.okio:okio:jar:1.13.0:compile
[INFO] +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.9.1:compile
[INFO] +- com.fasterxml.jackson.core:jackson-core:jar:2.9.2:compile
[INFO] +- richtercloud:selenium-tools:jar:1.0-SNAPSHOT:compile
[INFO] |  +- junit:junit:jar:4.12:compile
[INFO] |  |  \- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] |  +- org.apache.commons:commons-compress:jar:1.11:compile
[INFO] |  +- ru.yandex.qatools.ashot:ashot:jar:1.5.3:compile
[INFO] |  |  \- com.googlecode.lambdaj:lambdaj:jar:2.3.3:compile
[INFO] |  |     \- org.hamcrest:hamcrest-all:jar:1.1:compile
[INFO] |  \- org.junit.jupiter:junit-jupiter-engine:jar:5.0.3:compile
[INFO] |     +- org.apiguardian:apiguardian-api:jar:1.0.0:compile
[INFO] |     +- org.junit.platform:junit-platform-engine:jar:1.0.3:compile
[INFO] |     |  +- org.junit.platform:junit-platform-commons:jar:1.0.3:compile
[INFO] |     |  \- org.opentest4j:opentest4j:jar:1.0.0:compile
[INFO] |     \- org.junit.jupiter:junit-jupiter-api:jar:5.0.3:compile
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api-maven:jar:2.2.6:compile
[INFO] +- org.jboss.arquillian.extension:arquillian-drone-api:jar:2.5.0:compile
[INFO] +- org.jboss.arquillian.junit:arquillian-junit-core:jar:1.2.0.Final:compile
[INFO] +- org.jboss.arquillian.container:arquillian-glassfish-embedded-3.1:jar:1.0.2:compile
[INFO] |  +- org.jboss.arquillian.container:arquillian-container-spi:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.protocol:arquillian-protocol-servlet:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.testenricher:arquillian-testenricher-cdi:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.testenricher:arquillian-testenricher-ejb:jar:1.2.0.Final:compile
[INFO] |  +- org.jboss.arquillian.testenricher:arquillian-testenricher-resource:jar:1.2.0.Final:compile
[INFO] |  \- org.jboss.arquillian.testenricher:arquillian-testenricher-initialcontext:jar:1.2.0.Final:compile
[INFO] \- fish.payara.extras:payara-embedded-all:jar:5.0.0.Alpha3:test
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] arquillian-assertt-statements ...................... SUCCESS [  0.864 s]
[INFO] arquillian-assertt-statements-web .................. SUCCESS [  0.060 s]
[INFO] arquillian-assertt-statements-it ................... SUCCESS [  0.904 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.254 s
[INFO] Finished at: 2018-03-05T11:24:55+01:00
[INFO] Final Memory: 17M/303M
[INFO] ------------------------------------------------------------------------

The same error occurs when the test is run with maven-surefire-plugin 2.21.0. The issue also happens with embedded Payara 5.182 and 4.1.2.181 which are the latest of the 5.x and 4.x branches.
An SSCCE which doesn't contain more information than the MCVE above, but facilitates experiments in a clone, can be found at https://gitlab.com/krichter/arquillian-assertt-statements and example output of a complete run at https://gitlab.com/krichter/arquillian-assertt-statements/-/jobs/75705830.

A:

This seems to be fixed by adding
<listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>

to the web-app section of web.xml. Since you might not want to pollute your production web.xml you can use the following to insert the listener programmatically (in the Arquillian @Deployment method for example):
@Deployment(testable = false)
public static Archive<?> createDeployment0() throws ParserConfigurationException,
        SAXException,
        IOException,
        XPathExpressionException,
        TransformerConfigurationException,
        TransformerException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
        //namespace awareness is necessary in order to avoid an empty
        //`xmlns` attribute to be added to the persistence-unit element in
        //the output which causes failure of the functional test due to
        //`java.io.IOException: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 108; Deployment descriptor file META-INF/persistence.xml in archive [project1-jar-1.0-SNAPSHOT.jar].  cvc-complex-type.2.4.a: Invalid content was found starting with element 'persistence-unit'. One of '{"http://xmlns.jcp.org/xml/ns/persistence":persistence-unit}' is expected.`
        //see
        //https://stackoverflow.com/questions/48362284/how-to-avoid-xmlns-to-be-added-to-a-manipulated-xml-root-element
        //for details and an explanation
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document webXmlDocument = documentBuilder.parse(new File("src/main/webapp/WEB-INF/web.xml"));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xPath = xPathfactory.newXPath();

    XPathExpression expr = xPath.compile("//*[local-name()='web-app']");
    Node webAppNode = (Node) expr.evaluate(webXmlDocument,
            XPathConstants.NODE);
    Element listenerNode = webXmlDocument.createElementNS(webAppNode.getNamespaceURI(),
            "listener");
        //use `createElementNS` instead of `createElement` in order to avoid
        //empty `xmlns` attribute on the created `listener` element which
        //is otherwise added even if the document builder is namespace aware
    Element listenerClassNode = webXmlDocument.createElementNS(webAppNode.getNamespaceURI(),
            "listener-class");
    listenerClassNode.setTextContent("com.sun.faces.config.ConfigureListener");
    listenerNode.appendChild(listenerClassNode);
    webAppNode.appendChild(listenerNode);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(webXmlDocument), new StreamResult(writer));
    String webXml = writer.toString();
    StringAsset webXmlAsset = new StringAsset(webXml);
    WebArchive archive = ShrinkWrap.create(WebArchive.class)
            .setWebXML(webXmlAsset)
            ...;
    return archive;
}

Use org.jboss.shrinkwrap.api.Node webXml = mavenArtifact.get("/WEB-INF/web.xml") and parse webXml.getAsset().openStream() with DocumentBuilder to retrieve the web.xml if you use the complete WAR archive  in a separate project for the functional tests like in the example above.
I found the solution in Payara bug report 1105 where I linked the information provided here which hopefully triggers further investigation and a fix by the Payara devs.
I added the fix on the fix branch of the SSCCE.


Q:

My website looks different on other resolutions

So, I am using position:absolute to align elements on my website and it looks different on other resolutions. my current resolution is 1920x1080. I have another screen with 1366x768 resolution and it looks terrible on it. This is my first time of making proper website. Is there any other way to align elements to avoid this thing?

EVEREST

        Features
        Services
        Contact us

 Hello World.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

         GET STARTED

this is what is looks like on 1366x768

A:

You need to do a responsive website using Media queries of a framework like Bootstrap using a grid.
Here an example of Media queries:
@media (min-width: 30em) and (orientation: landscape) { ... }

Here an example of the grid Bootstrap displaying 3 equals columns independent of the screen size:

      One of three columns

      One of three columns

      One of three columns


Q:

Change format in Android Chronometr to show millisecond

i'd like to change format in my android chronometr to show millisecond. So far I used this tip:
    mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        public void onChronometerTick(Chronometer cArg) {
            long t = SystemClock.elapsedRealtime() - cArg.getBase();
            cArg.setText(DateFormat.format("kk:mm:ss", t));
        }
    });

but i dont know the symbols for millisecond. Is there something? Thanks!

A:

try:
   mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        public void onChronometerTick(Chronometer cArg) {
            long t = SystemClock.elapsedRealtime() - cArg.getBase();
            cArg.setText(DateFormat.format("kk:mm:ss:SSS", t));
        }
    });


Q:

Secondary x-axis labels for sample size with ggplot2 on R

I am trying to replicate the following graph, which I made in Excel, with ggplot2 in R:

I am able to successfully create the lines with geom_line(), the labels with geom_text() / some manual adjustments, and the y-axis. Find my code below:
library(readxl)
library(ggplot2)

somedata <- read_excel("somedata.xlsx")
somedata[,c(3:6)] <- somedata[,c(3:6)] * 100
somedata[,6] <- somedata[,6] + 25

somegraph <- ggplot(data = somedata, aes(x = date))
somegraph +
  geom_point(aes(y = eligible_main), shape = 15, size = 4) +
  geom_line(aes(y = eligible_main)) +
  geom_line(aes(y = eligible_center), size = 2) +
  geom_line(aes(y = eligible_upper), linetype = 2) +
  geom_line(aes(y = eligible_lower), linetype = 2) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 10), labels = paste0(seq(0, 100, 10), "%")) +
  labs(title = "Title", x = "Time", y = "Percentage") + theme_classic() +
  theme(plot.title = element_text(hjust = 0.5), axis.text.x = element_text(angle = 90, hjust = 1))

For reference, here is some fake data I created in a similar format as the data I am graphing. You can paste it into R and run my code above in the console: http://s000.tinyupload.com/?file_id=43876540434394267818
But I am finding it extremely difficult to create the sample-size secondary labels on the x-axis in the same orientation. Is there a simple solution to this in ggplot2, or with another package? Also, can I add annotation lines onto my graph to point things out once finished?
Thank you very much!

A:

I have a solution that might help.  I was unable to grab the data you shared, I created my own dummy dataset as follows:
set.seed(12345)
library(lubridate)

df <- data.frame(
  dates=as.Date('2020-03-01')+days(0:9),
  y_vals=rnorm(10, 50,7),
  n=100
)

First, the basic plot:
library(scales)
library(ggrepel)
p.basic <- ggplot(df, aes(dates, y_vals)) +
        geom_line() +
        geom_point(size=2.5, shape=15) +
        geom_text_repel(
            aes(label=paste0(round(y_vals, 1), '%')),
            size=3, direction='y', force=7) +
        ylim(0,100) +
        scale_x_date(breaks=date_breaks('day'), labels=date_format('%b %d')) +
        theme_bw()

Note that my code is a bit different than your own.  Text labels are pushed away via the ggrepel package.  I'm also using some functions from scales to fix and set formatting of the date axis (note also lubridate is the package used to create the dates in the dummy dataset above).  Otherwise, pretty standard ggplot stuff there.
For the text outside the axis, the best way to do this is through a custom annotation, where you have to setup the grob.  The approach here is as follows:

Move the axis "down" to allow room for the extra text.  We do that via setting a margin on top of the axis title.
Turn off clipping via coord_cartesian(clip='off').  This is needed in order to see the annotations outside of the plot by allowing things to be drawn outside the plot area.
Loop through the values of df$n, to create a separate annotation_custom object added to the plot via a for loop.

Here's the code:
p <- p.basic +
    theme(axis.title.x = element_text(margin=margin(50,0,0,0))) +
    coord_cartesian(clip='off')

for (i in 1:length(df$n)) {
  p <- p + annotation_custom(
    textGrob(
      label=paste0('n=',df$n[i]), rot=90, gp=gpar(fontsize=9)),
      xmin=df$dates[i], xmax=df$dates[i], ymin=-25, ymax=-15
    )
}
p

Advanced Options for more Fun
Two more things to add: Annotations (like callouts for specific points + text), and the lines below the plot in between the axis label stuff.
For lines below the axis: You can add breaks= to other axes fairly easily via scale_... and the breaks= parameter; however, for a date axis, it's... complicated.  This is why we will just add lines using the same method as above for the text below the axis.  The idea here is to break the axis into sub.div segments in the code below, which is based on how many discrete values are in your x axis.  I could do this in-line a few times... but it's fun to create the variable first:
sub.div <- 1/length(df$n)

Then, I use that to create the lines by annotating individually the lines along the step sub.div*i using a for loop again:
for (i in 1:(length(df$n)-1)) {
  p <- p + annotation_custom(
    linesGrob(
      x=unit(c(sub.div*i,sub.div*i), 'npc'),
      y=unit(c(0,-0.2), 'npc')   # length of the line below axis
    )
  )
}

I realize I don't have the lines on the ends here, but you can probably see how it would be easy to add that by modifying the method above.
Annotations (with arrows, why not?): There are lots of ways to do annotations.  Some are covered here using the annotate() function.  As well as here.  You can use annotate() if you wish, but in this example, I'm just going to use geom_label for the text labels and geom_curve to make some curvy arrows.
You can manually pass individual aes() values through the call to both functions for each annotation.  For example, geom_text(aes(x=as.Date('2020-03-01'), y=55,..., but if you have a few in your dataset, it would be advisable to set the annotations based on information within the dataframe itself.  I'll do that here first, where we will label two of the points:
df$notes <- c('','','','Wow!','','','OMG!!!','','','')

You can use the value of df$notes to indicate which of the points are getting labeled, and also take advantage of the mapping of x and y values within the same dataset.
Then you just need to add the two geoms to your plot, modifying as you wish to fit your own aesthetics.
p <- p + geom_curve(
    data=df[which(df$notes!=''),],
    mapping=aes(x=dates+0.5, xend=dates, y=y_vals+20, yend=y_vals+2),
    color='red', curvature = 0.5,
    arrow=arrow(length=unit(5,'pt'))
  ) +
  geom_label(
    data=df[which(df$notes!=''),],
    aes(y=y_vals+20, label=notes),
    size=4, color='red', hjust=0
  )

Final thing: Horizontal Lines  One final thing that I noticed in your code before, but forgot to point out is that to make your horizontal lines, just use geom_hline.  It's much easier.  Also, you can do it in two calls to geom_hline pretty easily (and even in just one call if you care to pass a dataframe to the function):
p <- p + geom_hline(yintercept = 50, size=2, color='gray30') +
  geom_hline(yintercept = c(25,75), linetype=2, color='gray30')

Just note that it's advisable to add these two geom_hline calls before geom_line or geom_point in the original p.basic plot so they are behind everything else.


Q:

How to restrict editing of records to the logged-in user?

Sorry, I am still new to Django, hopefully the question isn't out of place.
When I have the following in my template:
{{ item.last_name }}

By clicking on last name the user will be redirected to the following link in order to edit it.
http://127.0.0.1:8000/contact/edit/?id=1

But then what prevents any logged in user to just inject a different id in there on the browser and edit a record that doesn't belong to him?
Update
I just had an idea when I read the comment and answer below.  Rather than using a third party app, couldn't I just create a UserProfile for each user and attach a unique company wide uuid.uuid1().  Each time a loggedin user attempts to edit something, his unique company uuid will be also passed in the link as an additional parameter.
On the edit side, it would harvest this guid and compare it against the logged in user and see if they match. If they do match, he is authorized to proceed with the editing, otherwise he will be redirected.
What do you think? Any weaknesses?

A:

When you're using Django auth, always rely on the session mechanism to identify an user instead of making some other id such as uuid1() (except, for example, when you need extra sessions in an e-commerce site under HTTPS).
For the permission part, you could check the ownership directly, mainly as described by Koliber Services. The relationships between Company, User and Contact are crucial for the logic of permission checking. There are many ways to model the relationships and thus the code would differ much. For example:
# a modeling way
User.company -> Company : an user belongs to a company
Contact.contributor -> User : a contact is contributed by an user, would be invalid is user is leaving the company
# could check accessibility by
can_view = contact.contributor.company_id == current_user.company_id

# another modeling way
User.company -> Company : an user belongs to a company
Contact.company -> Company : a contact info is owned by a company, does not share globally
# could check accessibility by
can_view = contact.company_id == current_user.company_id

When can_view is False, user should get a 403 for his unauthorized attempting and get logged.
Normally the above method is enough for content protection(not yet in Django Admin). However, when you have many different types of permission checking and even row-permission checkings, it's better to use some uniform permission API.
Take Django-guardian for example, you could simply map companies to groups and assign can_view permission for a contact for the group representing the user's company. Or, assign the can_view permission to all users in a company when a contact is created by using signal or celery task.
Furthermore, you could use /contact/1/edit/ instead of /contact/edit/?id=1. In this way the int(request.GET('id')) part is moved to urlconf like r'^contact/(?P<pk>\d+)/$', less code and much clearer.


Q:

File lock between threads and processes

I'm writing a program that writes to a single file from both different threads on the same JVM and from different JVM's/processes. Is there a way to lock a file for both threads and processes, so that no matter how many threads/processes are trying to write at the same time, only 1 can write at a time?
Currently I have something similar to the following which works for locking threads, but not for blocking processes. If I try using FileLock on top of the implementation below it appears the synchronized stops working.
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import scripts.com.adz.commons.utils.FileUtilities;

import java.io.*;

public class Foo {
    public static void main(String[] args) throws IOException {
        Bar bar = new Bar();
        bar.start();

        while (true) {
            FileUtilities.writeObjectToFile("C:\\test.html", "foo");
        }
    }
}

class Bar extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                FileUtilities.writeObjectToFile("C:\\test.html", "bar");
            } catch (IOException ignored) {}
        }
    }
}

class FileUtilitiess {
    private static final Object _lock = new Object();

    public static <T> T readObjectFromFile(File file) throws IOException, ClassNotFoundException {
        synchronized (_lock) {
            final byte[] bytes = FileUtils.readFileToByteArray(file);

            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;

            try {
                ois = new ObjectInputStream(bis = new ByteArrayInputStream(bytes));

                return (T) ois.readObject();
            } finally {
                IOUtils.closeQuietly(ois);
                IOUtils.closeQuietly(bis);
            }
        }
    }

    public static void writeObjectToFile(File file, Object object) throws IOException {
        System.out.println("Sent object: " + object.toString());
        synchronized (_lock) {
            System.out.println("Writing object: " + object.toString());

            ByteArrayOutputStream bos = null;
            ObjectOutputStream oos = null;

            try {
                oos = new ObjectOutputStream(bos = new ByteArrayOutputStream());
                oos.writeObject(object);

                FileUtils.writeByteArrayToFile(file, bos.toByteArray());

                // - Start: For testing lock.
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ignored) {}
                // - End: For testing lock.
            } finally {
                IOUtils.closeQuietly(oos);
                IOUtils.closeQuietly(bos);
            }
        }
    }
}

A:

See FileLock javadoc:

File locks are held on behalf of the entire Java virtual machine.

That means that on the OS level different threads of your application will have the same right to access the locked region.
To lock the file access from different threads you have to encapsulate your file IO code and to enforce synchronized execution.


Q:

How do I uninstall Visual Studio 2008?

I want to uninstall Visual studio 2008 from my system, but I do not see Visual studio 2008 in the list on the "Uninstall or change a program" dialog box in windows 7.  I also checked the Visual Studio 2008 folder in the Programs folder, but I could not find anything to start the uninstallation wizard. Please help.

A:

Here is a Visual Studio 2008 Uninstall Tool that might help you: http://blogs.msdn.com/b/joy/archive/2009/10/16/microsoft-visual-studio-2008-rc-rtm-uninstall-tool.aspx


Q:

Is a connected graph uniquely determined by its weighted 2-step graph?

This is an extension of a previous question: https://math.stackexchange.com/questions/876336/is-a-graph-uniquely-determined-by-its-weighted-2-step-graph/876357#876357.  In that question I asked about arbitrary graphs; in this question I restrict to connected graphs.  Here are the details:
Let $G$ be an undirected graph.  Define the 2-step graph $G^{(2)}$ of $G$ to be the weighted graph whose vertices are the same as those of $G$ but whose edges correspond to 2-step paths in $G$.  Thus the weight of an edge $(u,v)$ is the number of distinct vertices $w$ such that $(u,w)$ and $(w,v)$ are both edges in $G$.  (In particular, the weight of $(u,u)$ is the degree of $u$ for every vertex $u$.)  My question:

Are there two connected, non-isomorphic graphs $G$ and $H$ such that $G^{(2)}$ is isomorphic to $H^{(2)}$?

My intuition says that the answer should be "yes", but I'm unable to construct an example.

A:

A counterexample can be constructed as follows. Let $G$ be the graph of a hexagonal pyramid and $H$ be that of a pair of tetrahedra sharing one common vertex. Then, $G^2$ and $H^2$ are isomorphic while $G$ and $H$ themselves are not. Indeed, $G$ has a simple $6$-cycle but $H$ has not.


Q:

Exclude characters in bind model Asp.net MVC

Hi I have a field CellPhone of type int in my model.
In the view I have a javascript mask in my CellPhone field. When the client send the post of the page I receive something like that:
555-4789

But this value is not valid value for a int type. There is anyway to notify the model binder that I want to "clean" the number by removing the character '-' before binding happens?
Maybe a DataAnnotation or something else?

A:

Use custom model binder for that-

public class yourmodel
{
public int cellphone{get;set;}
}

Define custom model binder as
public class CustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
                            ModelBindingContext bindingContext)
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;

        string[] phoneArray= request.Form.Get("CellPhone").split('-');

        string phone=phoneArray[0]+phoneArray[1];

        return new yourmodel
                   {
                       cellphone= convert.ToInt32(phone)
                   };
    }
}

then in app_start register new created binder as
protected void Application_Start()
{

    ModelBinders.Binders.Add(typeof(yourmodel), new CustomBinder());
}

and in controller
[HttpPost]
public ActionResult Index([ModelBinder(typeof(CustomBinder))] yourmodel model)
{

    //..processing code
}


Q:

How did they film the final shootout scene from Felina?

The final shootout scene in the last episode of Breaking Bad is quite impressive.  Since watching it, I've wondered how it was filmed.
When stepped through frame-by-frame, the rounds appear to be leaving real bullet holes and causing real damage.  Was it just incredibly good CGI?  Did they really shoot up a room and green-screen actors into it?

A:

The trace bullet are CGI. And probably are very easy to make. Just watch this Connan segment where they add the bullets at 4m 10sec mark.

The bullets holes are usually made with small controlled explosions. So the holes are real, just not really dangerous. But also can be made with CGI.
Very basic / Low Budget example:

if you want see how a real machine gun will looks like on this case. Check this mythbuster video:


Q:

RealmSwift LinkingObjects and Decodable

I have a Realm model class that I need to be Decodable so I can serialize it from JSON and save it to database. Every PortfolioItem is associated with one Product and at some point I need to get to PortfolioItem from Product via inverse relationship. That's why I have LinkingObjects property. The problem is when I try to conform to Decodable protocol. The compiler is giving me an error Cannot automatically synthesize 'Decodable' because 'LinkingObjects<PortfolioItem>' does not conform to 'Decodable' . How to deal with this? I found very little about LinkingObjects and Decodable online and I have no idea how to approach this.
class PortfolioItem: Object {

    @objc dynamic var id: String = ""
    @objc dynamic var productId: String = ""

    @objc dynamic public var product: Product?

    convenience init(id: String, productId: String) {
        self.init()
        self.id = id
    }

}

final class Product: Object, Decodable {

    @objc dynamic var id: String = ""
    @objc dynamic var name: String = ""

    private let portfolioItems = LinkingObjects(fromType: PortfolioItem.self, property: "product")

    public var portfolioItem: PortfolioItem? {
        return portfolioItems.first
    }

    convenience init(id: String, name: String) {
        self.init()
        self.id = id
    }
}

Big thanks to Chris Shaw for helping me figure this out. I wrote a more in-depth article how to setup Decodable and LinkingObjects, look HERE.

A:

Well unless I'm missing something then the LinkingObjects properties does not need to be included in the decoding.
My assumption here is that you're receiving JSON from some online source, where the JSON for a Product consists of { id: "", name: "" }. As long as you're creating the PortfolioItem correctly with associated Product, then the resulting LinkingObjects property is the result of a dynamic query within Realm (and will thus work without any JSON source).
I'm not in a position to test compile an answer today, but you should be able to use CodingKeys to simply exclude that property, i.e. by adding this to Product:-
private enum CodingKeys: String, CodingKey {
    case id
    case name
}

Also, unrelated, but note that your convenience init function are not initialising all properties that you're passing in.


Q:

Не работает функция с замыканием

function bind(context, fn) {
    return function (... args) {
        fn.apply(context, args);
    }

}
    function logPerson() {
        console.log(`Person: ${this.name},${this.age}`)
    }

const person1 = {name: 'Михаил', age: '20'};
const person2 = {name: 'Виктор', age: '21'};

bind(person1, logPerson());
bind(person2, logPerson());

Уважаемые. Не поливайте, пожалуйста грязью. Я только учусь и пытаюсь разобраться. Изучаю замыкания. Посмотрел ролик на ютубе на эту тему по ссылке: https://www.youtube.com/watch?v=pahO5XjnfLA&t=575s и в строчке нашел ошибку. Верным оказалось: "bind(person2, logPerson)();". Объясните, пожалуйста, в чем разница при указании функции, когда вызываешь ее со скобками и без скобок? И что за пустые скобки в конце строки, после указания параметров функции bind?

A:

function bind(context, fn) {
  return function(...args) {
    fn.apply(context, args);
  }
}

function logPerson() {
  console.log(`Person: ${this.name}, ${this.age}`);
}

const person1 = {
  name: 'Михаил',
  age: '20'
};
const person2 = {
  name: 'Виктор',
  age: '21'
};

var f1 = bind(person1, logPerson);
var f2 = bind(person2, logPerson);

f1();
f2();


Q:

Interrupt a running thread to execute an action triggered by a JButton click

we are still working with the nasty robots and got another problem (after solving our package problem).
We have a robot which is running in a thread. He runs constantly forwards (move() method) and is checking if the currentDir variable has changed. If it has changed, he would call another method to get face the new direction.
Our problem is that we have to change the currentDir variable somehow. We want to do this by calling the setDir() method of our robot which is running in the thread.
This function is called after an event happened, triggered by a JButton.
But we can not manage to interrupt the thread to call this method.
Is it maybe possible to create a listener listening in the thread itself for a ActionEvent triggered by a JButton?
   public void run()
    {
          //Infinite while-loop to check for the Direction of the robot
          while(true)
          {
                 if(currentDir != getDirection()) // if currentdir is not
                 {
                       if(currentDir == Direction.NORTH)
                            goNorth();
                       else if(currentDir == Direction.EAST)
                            goEast();
                       else if(currentDir == Direction.SOUTH)
                            goSouth();

                       else
                            goWest();
                  }
                  else
                       move();
          }
    }

A:

You don't really need to set the direction from the same thread. If you set it from the UI thread in the listener, the thread should be able to just pick it up.
You might want to also make the direction variable volatile. http://www.javamex.com/tutorials/synchronization_volatile_typical_use.shtml


Q:

L shaped text box on a website

I am trying to create the following text box design on a website. I could use images for the white boxes, but the issue is that I am not sure how to create an L shaped text area where the words wrap and fit nicely into those white boxes.
Does anyone know how to achieve this, or point me to the right direction to investigate?

A:

Try CSS Exclusions.

CSS Exclusions define arbitrary areas around which inline content
  can flow. CSS Exclusions can be defined on any CSS
  block-level elements. CSS Exclusions extend the notion of content
  wrapping previously limited to floats.

They are specifically related to word-wrap.


Q:

Get-ChildItem is not showing all files in a folder

When I call Get-ChildItem in PowerShell it is only returning a few of the files that exist in the directory. This is the driver folder, so I tried using the -Force parameter in case they were hidden, but with no luck.
It's interesting though because it works perfect on my Windows 7 32 bit, but not 64 bit. Any ideas?

A:

I believe PowerShell is showing you everything however the folder you're looking at in the x86 PowerShell prompt isn't what you think.  The directory you're actually looking at is under C:\Windows\SysWow64\Drivers and not actually C:\Windows\System32\Drivers.  This is due to a Windows feature (Vista and higher) for 32-bit processes running on 64-bit OS called virtualization (specifically the File System Redirector).  When you run a 64-bit PowerShell prompt virtualization is not used so you see the real C:\Windows\System32\Drives dir.
From a 32-bit PowerShell prompt, you can see the "real" C:\windows\system32\drivers dir by using this path:

Get-ChildItem C:\Windows\SysNative\Drivers


Q:

Geometry problem by isi 2016

Let ABCD be a square two of whose adjacent vertices, say A, B are on the positive x axis and positive y axis. If C has co-ordinates (u,v) in the first quadrant, determine the area ABCD in terms of u and v.

A:

Due to similar triangles, we have:
$u = y$
$v = y + x = u + x$
And $s^2$ is the area of $ABCD$.
Therefore, $s^2 = x^2 + y^2 = (v-u)^2 + u^2 = v^2 - 2 u v + 2 u^2$


Q:

How to prevent downtime during AWS Elastic Beanstalk deployment of a new version of the app?

My understanding of Elastic Beanstalk is that when you deploy a new version of your app, that it deploys it to the Amazon EC2 instances one at a time (if you have more than one).  However, even with a minimum of two instances, my application incurs a short amount of downtime when I upload a new .war when it is deploying it, as if it is updating them both simultaneously.  Is there a way I can ensure there is no downtime and that one instance is fully updated and accepting requests before the next starts:  Here is how the events look.  Note this is with zero load on the app, so it will only get worse with production traffic.
INFO
Environment update completed successfully.

INFO
New application version was deployed to running EC2 instances.

ERROR
The application did not respond at the health check URL.

INFO
Waiting for 8 seconds while EC2 instances download the updated application version.

INFO
Deploying version SomethingMore to 2 instance(s).

A:

To achieve this goal in Elastic Beanstalk, you'll need to expand your deployment procedure to facilitate multiple Environments (see AWS Elastic Beanstalk Components):

An environment is a version that is deployed onto AWS resources. Each
  environment runs only a single version, however you can run the same
  version or different versions in many environments at the same time.
  [...] For
  more information about the environment and the resources that are
  created, see Architectural Overview. [emphasis mine]

This feature is useful for testing/debugging separate versions already, but specifically this enables hot swapping of environments as well, see Deploying Versions With Zero Downtime for a respective walkthrough:

Since AWS Elastic Beanstalk performs an in-place update when you
  update your application versions, you will experience some downtime.
  However, it is possible to avoid this downtime by swapping the CNAMEs
  for your environments. This section walks you through how to perform a
  CNAME swap using the AWS Management Console, the command line
  interface, or APIs. [emphasis mine]

A:

I know this is an old question, but for people googling (like me), Elastic Beanstalk released rolling application version deployments today (11/2/2014).
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.rolling-version-deploy.html?sc_ichannel=em&sc_icountry=global&sc_icampaigntype=launch&sc_icampaign=em_125873140&sc_idetail=em_14124901705&ref_=pe_411040_125873140_8
This allows you to update part of your fleet with your new application at a time, ensuring that there's always hosts available to take traffic.


Q:

Python 2.7: Why regex A|B give me extra element in list

Say I have a input file which contains the following information:
/* Name: David */
/* Age: 30
....
....
/* Name: Ben */
/* Age: 35
....
....

I want to extract the name of each person and find out whether there is any information on age. My idea is to use regex to capture the name (David, Ben, etc) and see whether there is "Age" at the second line.
So my regex pattern looks like this:
regex = ".+Name ?: (.+) .+\n.+ (Age) ?:.+|.+Name ?: (.+) "

Basically I use re.findall(regex, f.read()) to find all the name and "Age" and I get something like this:
[('David','Age',''),('Ben','Age','')]

If Ben don't have information on age:
/* Name: David */
/* Age: 30
....
....
/* Name: Ben */
....
....
....

My output will be:
[('David','Age',''),('','','Ben')]

My question is how am I suppose to get:
[[('David','Age'),('Ben','')]

Note that I do not know the name of each person inside the file. Also, I am using Python 2.7.

A:

The reason it's giving you three elements per tuple is that you have three capture groups, and the reason that it's putting names with no ages into the third element is that they match the third capture group. If you want to signify that the age is optional, you should wrap it in a noncapturing group ((?:)) and use ?, which will give you a final regex of:
.+Name ?: (.+)(?:.+\n.+ (Age) ?:.+)?

It's the same as yours, but instead of having alternation and three capture groups, I have an optional section and only two, which should give you the result you want.