text:
Q: All Logs Required when Enabling Circular Logging? (Exchange 2010) Currently looking at cleaning up a mess left by a now-gone tech for one of my clients.  Initially we found that backups hadn't been running for some months. While they're running now, I just found out that Exchange backups haven't. Exchange has been creating a lot of log files, which were moved off onto a NAS in order to keep Exchange 2010 running.  Long story short, we'll be getting a new SAN and a better backup solution in the upcoming months, but for now I need to find a way of truncating these log files.
I'm looking at enabling circular logging for Exchange 2010.  My plan is to enable this option, and then do NTBackup to a NAS device until I'm OKed the hardware I need.  Question is; does Exchange need access to all of the previous log files that haven't been flushed in order to enable circular logging?  This can be done, but will require downtime to move the mount point to the NAS drive.
Also, what's the period of log files kept on-hand with circular logging?  Day, week, specific size?
Thanks in advance for any answers,

A: Enabling Circular Logging with Exchange 2010 is leaving yourself open to potential problems in the future unless you have at least one active and two passive copies of your databases.  If for some reason your databases came into a failed state and needed logs that were overwritten, and you had no other databases that had those transactions committed, you would have some big problems. Did you verify what logs were committed to the databases before moving the logs off to a NAS?
To answer your specific question, I believe you only need access to the logs that have not yet been committed to the databases to enable circular logging.  Check out the following article for some more insight: Exchange 2010 Circular Logging


text:
Q: Open tabs not stacking in toolbar How do i stop items from appearing across the screen. I want them to show stacked like the picture below, however we have had two new computers and they are displaying all across the screen instead. i have unticked the aero peak and desktop composition which has worked on all the other computers but not the new ones.
Using windows 7.
.

redpajama_set_name: RedPajamaStackExchange


text:
Q: check the data coming from arduino to android via USB host My code receive data on my Android phone from Arduino via USB host.
The data (in form of bytes) is transformed to String Output, I write code in the method updateReceivedData(byte[]) that checks if the data contains "Warning" word, to send message containing the warning data
I try to make counter to make delay between sending messages in case of continuous warning received data, then I would to reset the counter if there is no warning message
My problem is that the counter reset every time and continue sending message without making delay.
I think the solution is by making delay while The String output is completed, then check on it, but I don't know how?
private void updateReceivedData(byte[] data) throws UnsupportedEncodingException {
    String Output = new String(data);
    if(Output.contains("Warning")){
        if (warncounter==0){
            Toast.makeText(getBaseContext(), "Warning message sent", Toast.LENGTH_SHORT).show();
            SmsManager.getDefault().sendTextMessage(number, null, Output, null, null);
        }
        warncounter++;
        if(warncounter==52) warncounter=0;
    }
    else warncounter=0;
    mDumpTextView.append(Output);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
    }

To make an approach for finding the problem, I try this code
private void updateReceivedData(byte[] data) throws UnsupportedEncodingException {
    String Output = new String(data);
    if(Output.contains("Warning")){
              SmsManager.getDefault().sendTextMessage(number, null, Output, null, null);
            }
    }
    mDumpTextView.append(Output);
    mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
    }

In the second code, I let all received data contain warning, the result is that the first message contains the whole output string, but after the first, all received messages are trimmed (maybe due to the data was not completely transformed to string before start sending string)
Note: The data are sent from Arduino every one second, and the data in the scrollview text appears correctly 100% (this indicates that the data was transformed to String but maybe the problem is that it takes time)
So please help or make suggestions

A: I found the problem
The problem is that android cannot read the whole data sent from arduino (using Serial.print ()) by a single bulktransfer () function call, so I make the bulktransfer () (or read) in a while loop, then I check on each Sting sent by arduino by building a String when each new line ("\n") is detected in the readed data


text:
Q: How to Determine a Route With Path Value Please, I am having some kinda challenge solving this scenario.
Whenever my app starts, it goes to a DummyComponent which has no url path value (http://localhost:4200/). This have just have two buttons, login and register. Pending on whichever button you click on; it navigates to the page.
Lets assume a user clicks on the login button to auth into the system, once successful, the user is redirected to the dashboard component => http://localhost:4200/dashboard.
Now, even when the user is logged in and manually change the url to http://localhost:/4200. This has no path value, how do I redirect the user back to http://localhost:4200/dashboard
I understand I can use the canActivate guard to protect my route, but the challenge I am having is; how can I determine when a user visit a url without a path value i.e http://localhost:4200/ (when logged in) so that I can redirect the user back to dashboard? …. But again, when the user is not logged in and visit the url without a path, it should go straight to the initial DummyComponent.
Here is how my route looks like:
const routes4: Routes = [
   {path: '', component: DummyComponent},
   {
     path: '',
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard],
     children: [
      { path: 'dashboard', component: DashboardComponent },
       { path: 'user/list', component: PatientsComponent },
       { path: 'user/new', component: PatientComponent },
       { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
     ]
   },
];
****
canActivate(): boolean {
      if (this.authService.isLoggedIn()) {
        return true;
      }
      this.pnotifyService.error('Error', 'You do not have sufficient permission');
      this.router.navigate(['/login']);
      return false;
  }

I did some research but couldn't lay my hands on a scenario like mine.
Any idea on how to tackle this?

A: You can use another gaurd to redirect the user to proper path based on your condition
Something like this:
import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { Router } from '@angular/router';

@Injectable()
export class RedirectGuard implements CanActivate {
  canActivate() {

    if (this.authService.isLoggedIn()) {
         // when user is logged in you redirect it to dashboard url
         this.router.navigate(['dashboard']);
         return true;
    }
  }
 //Constructor
 constructor(private router: Router, private authService: AuthService) { }
}

Now you can use it in your path like this:
const routes4: Routes = [
   {path: '', component: DummyComponent},
   {
     path: '',
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard, RedirectGuard],
     children: [
      { path: 'dashboard', component: DashboardComponent },
       { path: 'user/list', component: PatientsComponent },
       { path: 'user/new', component: PatientComponent },
       { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
     ]
   },
];

Update:
You can re-use your existing code to achieve this behavior
Something like this:
canActivate(): boolean {
      if (this.authService.isLoggedIn()) {
        this.router.navigate['/dashboard'] //redirect if the user is logged in
        return true;
      }
      this.pnotifyService.error('Error', 'You do not have sufficient permission');
      this.router.navigate(['/login']);
      return false;
  }


text:
Q: RSocrata package with Chicago data neglects my token I can not throttle-up my downloads by using the token issued to my app (on data.chicago.com portal, where I had to register)
Error 1:
token <- "___my_app_token__";
fdf <- read.socrata("h___s://data.cityofchicago.org/resource/7edu-s3u7.csv?$where=station_name=\"Foster Weather Station\"", token)

2016-10-06 10:39:53.685 getResponse:
Error in httr GET: 403  h___s://data.cityofchicago.org/resource/7edu-s3u7.csv?%24where=station_name%3D%22Foster%20Weather%20Station%22&app_token=%2524%2524app_token%3D___my_app_token_______

I have NO IDEA where did the first 'token' (2524 2524) come from, do you? Can somebody tell me? Maybe the author of the package is here?
Non-error:
fdf <- read.socrata("h___s://data.cityofchicago.org/resource/7edu-s3u7.csv?$where=station_name=\"Foster Weather Station\"")

WITHOUT A TOKEN (and not throttled-up) works perfectly well!
and this 'open source' h___s://github.com/Chicago/RSocrata/blob/master/R/RSocrata.R doesn't answer the question as well.

A: It looks like the syntax you're using to pass your app token is wrong. I'm no R expert, but I found this example in the documentation for the RSocrata library:
df <- read.socrata("http://soda.demo.socrata.com/resource/4334-bgaj.csv",
                    app_token = "__my_app_token__")

Try passing your app token as a named parameter instead of an indexed parameter, and see if that helps.


text:
Q: Removing substrings from words that start with them.(in C) I'm trying to write a small piece of code(function) that removes the substrings in a string only if the words of the string start with these substrings. Look what I've tried till now:
char *string="internship, is wonderful for people who like programming"
char *prefixes="intern wonder in pe"
char *delsubstr(char *string, const char *prefixes)

 {
 char *tokprefix;
 tokprefix=strtok(prefixes, " ");
 while(tokprefix)
    {
     size_t m = strlen(tokprefix);
     char *p = string;
     while ((p = strstr(p, tokprefix))!= NULL)
        {

                {
                 char *q = p + m;
                 size_t n = strlen(q);
                 memmove(p, q, n + 1);
                 }
         }
     tokprefix=strtok(NULL, " ");
     }
 return string;
}

The prob with it is it removes the substrings from everywhere and I only what the substrings from the beginning to be removed. Also if "intern" and "in" substrings are present, I want the bigger one to be removed from the string, not the smaller one. Anyone got any ideas/suggestions? I think an if condition before the memmove could be enough, but I'm not sure.

A:
I think an if condition before the memmove could be enough, but I'm
  not sure.

Apart from the problem of modifying the prefixes string literal, which is dealt with in the comments above, you're approximately correct:
     while ((p = strstr(p, tokprefix))!= NULL)
        {
            if (p > string && p[-1] != ' ') // not at beginning of word?
                ++p;                        // then just advance pointer
            else                            // else remove start of word
                {
                 …


text:
Q: How to make multiple "FIND" request inside one controller API in express and Mongoose? I have one API to consult data from database. So I want to make multiple "FIND" query on mongoose, join all the responses and send back the result from the query. I am using Nodejs and Express to make the API and Mongoose.
exports.data = (req, res) => {
    //FIND ALL CONSULTATIONS FILTERED BY STATUS
    const result1 = Model.find({ status: 'STATUS1' }).exec(
        (err, item) => {
            if (err) {
                return res.status(400).json({
                    error: 'Erorr en STATUS1',
                });
            }

        }
    );
    const result2 = Model.find({ status: 'STATUS2' }).exec(
        (err, item) => {
            if (err) {
                return res.status(400).json({
                    error: 'Erorr en STATUS2',
                });
            }
        }
    );

    res.json({result1, result2})

};

something like that, but it does not work. How can I achieve that? Make just one API call and response, but in the controller ask for different data, make one object and send it back.

A: Your current problem is that node will start the first find, and before it's done it'll start the second find, and before either of those are done it'll send back the result which will likely be { result1: undefined, result2: undefined }
You need to wait for the result before you send it back.
Your options are callback-hell, promises or async-await. Pick your poison.
// callback hell
Model.find({ status: 'STATUS1' }).exec((err, result1) => {
  if (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS1'
    })
  }
  Model.find({ status: 'STATUS2' }).exec((err, result2) => {
    if (err) {
      return res.status(400).json({
        error: 'Erorr en STATUS2'
      })
    }
    res.json({ result1, result2 })
  })
})

// Promises
exports.data = async (req, res) => {
  //FIND ALL CONSULTATIONS FILTERED BY STATUS
  const promise1 = Model.find({ status: 'STATUS1' }).exec()
  const promise2 = Model.find({ status: 'STATUS2' }).exec()
  Promise.all([promise1, promise2])
    .then(([result1, result2]) => {
      res.json({ result1, result2 })
    })
    .catch(err => {
      return res.status(400).json({
        error: 'Erorr en STATUS2'
      })
    })
}

// Async Await
exports.data = async (req, res) => {
  //FIND ALL CONSULTATIONS FILTERED BY STATUS
  let result1
  let result2
  try {
    result1 = await Model.find({ status: 'STATUS1' }).exec()
  } catch (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS1'
    })
  }
  try {
    result2 = await Model.find({ status: 'STATUS2' }).exec()
  } catch (err) {
    return res.status(400).json({
      error: 'Erorr en STATUS2'
    })
  }
  res.json({ result1, result2 })
}

None of the code above has been tested. It's just to give you a rough idea.
While promises looks cleaner here, I almost always opt for using async/await when I can. And since this is express, it makes sense to use express style error handler (and factor out the try-catches) which would make async-await look much cleaner.


text:
Q: Execute php script (Windows) A few days ago I published this thread, and it was solved succesfully on Unix.
Now I moved  to Windows and I have the same problem.
I need to execute a command from the web application. It must execute a .jar stored in the system. I looked on Google and found some changes that I needed to do.
The function to execute the command is:
<?php
if($_POST["name"] == "")
    echo "name is empty";
else{
    $path = $_POST["name"];
    //$command = 'DISPLAY=:0 java -jar '.$path'; -> Used in Unix
    //$command = 'java -jar ../../../../simulaciones/tanqueCalentamiento.jar';
        $command = 'java -jar ..\..\..\..\simulaciones\tanqueCalentamiento.jar';
    //system($command);
    exec($command);
}
?>

The comments are different options I have tried. $path is the argument, but  decided to put directly the path, to clarify my question:
Do I need a kind of "trick" as I did for Unix?

A: The one I use:
function _exec($cmd)
{
   $WshShell = new COM("WScript.Shell");
   $oExec = $WshShell->Run($cmd, 0,false);
   error_log($cmd);
   return $oExec == 0 ? true : false;
}

/!\ If your application has an interface, and if you are using vista or 7, your server can't be run as a service!

A: You're just starting 'java'. That means that the Java executable (java.exe) must exist, and must be able to be executed. Since you don't specify a path, it must be in a directory that is in the %PATH% environment variable.
To test, simply start cmd and type java<enter>. If java gets executed, you'll know at least you'll have java installed and startable. If it doesn't, check if you have java and specify the correct path to the java executable.
You can also run the .jar from the command line to see if it works. If it works like this, it is likely to work in PHP too.

A: In windows vista, 7 (I don't know if in others too), there is a problemm with xampp.
The apache does not stop, doesn't matter what you do, even switch the computer off. At least for me, the solution was:

*

*Uninstall xamp and reinistall it.

*Start/stop it always as administrator:
path\xampp\xampp_start
path\xampp\xampp_stop
Right click: run as administrator.
In this way apache is finished properly, and I can run my command with no probleems anymore
I hope this helps
http://drupal.org/node/224342


text:
Q: What is the difference between kill , pkill and killall? I am familiar with kill command , and most of the time we just use kill -9 to kill a process forcefully, there are many other signals that can be used with kill. But I wonder what are the use cases of pkill and killall, if there is already a kill command.
Do pkill and killall use the kill command in their implementation?  I mean they are just wrappers over kill or they have their own implementation?
I would also like to know how pgrep command gets the process id from the process name.
Do all these commands use the same underlying system calls? Is there any difference from a performance point of view, which one is faster?

A: The kill command is a very simple wrapper to the kill system call, which knows only about process IDs (PIDs). pkill and killall are also wrappers to the kill system call, (actually, to the libc library which directly invokes the system call), but can determine the PIDs for you, based on things like, process name, owner of the process, session id, etc.
How pkill and killall work can be seen using ltrace or strace on them. On Linux, they both read through the /proc filesystem, and for each pid (directory) found, traverses the path in a way to identify a process by its name or other attributes. How this is done is technically speaking, kernel and system specific. In general, they read from /proc/<PID>/stat which contains the command name as the 2nd field. For pkill -f and pgrep examine the /cmdline entry for each PID's proc entry.
pkill and pgrep use the readproc system call, whereas killall does not. I couldn't say if there's a performance difference: you'll have to benchmark that on your own.

A: kill and killall are tools which provide a way to kill a process. The first by its PID, the second by its name.
pgrep (list) and pkill (kill by default) are tools which provide a way to send message to a process by its name or other attributes
see: http://linux.die.net/man/1/pkill
For more info about signals: http://linux.die.net/man/7/signal

A: A more practical answer:

*

*kill will send a SIGTERM (terminate a process) signal to the OS for a given process id (e.g. 10341), by default this is SIGTERM. You can actually specify other signals too (e.g. -9 to force terminate)

*killall will send SIGTERM to all processes matching a certain name exactly. It also comes wit other goodies such as subsetting by user.

*pkill will send SIGTERM to all processes that match a given pattern. It uses pgrep under the hood.


text:
Q: How does bash's job control handle stopped or terminated background jobs? While studying the internals of bash's job control mechanism under Linux I have came across a little problem of understanding. Let's assume the following scenario:
script is executed in background
user@linux:~# ./script.sh &
same script is executed in foreground at the same time
user@linux:~# ./script.sh
Now the first execution of the script is performed as a background job during the second execution of the script in the foreground. Bash now performs a blocking wait call with the PID of the foreground process until it terminates and then it gets the corresponding information. After the termination of the forground process bash controls the status of all background jobs and informs about every changes before returning to prompt. This is usually the default behavior called "+b".
But there is an other mode called "-b". In this mode bash informs immediately about every background job status change. In my understanding this is done by sending the signal SIGCHLD by the background process. But how could bash react to this signal of a terminated background process and print a message to the terminal although it executes a blocking wait call. Because in my opinion signals are only handled before returning to user mode.
Does bash call wait with the option WNOHANG within a loop until the current foreground terminates?
Furthermore, when operating in mode "-b" bash can write to the terminal although it doesn't belong to the foreground process group of the terminal. Even when I set the option "tostop" with stty, bash can write to the terminal without being part of the foreground process group. Does bash get any special permissions because it is part of the controlling process group of the terminal.
I hope, I could make clear where my problems of understanding are.

A: Yes, bash uses waitpid() with WNOHANG in a loop.  You can see this in waitchld() in jobs.c:
static int
waitchld (wpid, block)
     pid_t wpid;
     int block;
{

...
  do
    {
      /* We don't want to be notified about jobs stopping if job control
         is not active.  XXX - was interactive_shell instead of job_control */
      waitpid_flags = (job_control && subshell_environment == 0)
                        ? (WUNTRACED|wcontinued)
                        : 0;
      if (sigchld || block == 0)
        waitpid_flags |= WNOHANG;

...
  if (block == 1 && queue_sigchld == 0 && (waitpid_flags & WNOHANG) == 0)
    {
      internal_warning (_("waitchld: turning on WNOHANG to avoid indefinite block"));
      waitpid_flags |= WNOHANG;
    }

  pid = WAITPID (-1, &status, waitpid_flags);

...
  /* We have successfully recorded the useful information about this process
     that has just changed state.  If we notify asynchronously, and the job
     that this process belongs to is no longer running, then notify the user
     of that fact now. */
  if (asynchronous_notification && interactive)
    notify_of_job_status ();

  return (children_exited);
}

The notify_of_job_status() function simply writes to the bash process' standard error stream.
I can't unfortunately say much about whether setting tostop with stty should influence the shell that you do this in.


text:
Q: Is there a way to expand an advert outside of the window width within a GPT (Google Publisher Tag) Safeframe? I am trying to create an advert that will expand past the side of the page.
Using the GPT Safeframe preview tool I am receiving the error "Invalid EXPAND_REQUEST message. Reason: Viewport or document body not large enough to expand into."
Is there a setting to override this or is this a self imposed limitation,
Here is an example of what I am trying to do:
you can test it out here: http://publisherconsole.appspot.com/safeframe/creative-preview.html

             $sf.ext.expand by overlay and $sf.ext.collapse

Creative should be expanded when buttons are clicked. Expansion can be performed
            only from collapsed state so subsequent expansion won't work until creative is collapsed.

            <button id="collapse" onclick="collapse();">Collapse</button>
            <button onclick="expand('all');">Expand all</button>

    <button id="left" onclick="expand('left');">&#8656</button>
    <button id="top" onclick="expand('top');">⇑</button>
    <button id="right" onclick="expand('right');">&#8658</button>
    <button id="bottom" onclick="expand('bottom');">&#8659</button>

A: unfortunately, it's not possible to avoid this behaviour, but i made a workaround, that will "wait", until user is scrolled in place, that is suitable to expand, check this example, that will push banner from bottom, when user have enought space from bottom to expand whole creative:

    some lines to make container height

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

    line

hope it helps!
edit:
I found better solution here:
Unable to access contents of a safeframe returned by Google adx


text:
Q: Why I can't migrate database of my rails project on Heroku? I have an existing rails (3.2.14) project on Heroku and need to migrate database. But when I try to run action:
     heroku run rake db:migrate

I just get an error. When we have an R99 error (heroku logs below) it's mean a platform trouble. But heroku status page is silent about any problems. Here's my --trace:
     $ heroku run rake db:migrate --trace
     Running `rake db:migrate --trace` attached to terminal... up, run.4543
     ** Invoke db:migrate (first_time)
     ** Invoke environment (first_time)
     ** Execute environment
     Connecting to database specified by DATABASE_URL
     rake aborted!
     SIGTERM
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:653:in `select'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:653:in `request'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:506:in `block in each_resource'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1023:in `block (3 levels) in          resolv'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1021:in `each'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1021:in `block (2 levels) in resolv'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1020:in `each'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1020:in `block in resolv'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1018:in `each'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:1018:in `resolv'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:498:in `each_resource'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:391:in `each_address'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:115:in `block in each_address'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:114:in `each'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:114:in `each_address'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:92:in `getaddress'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/resolv.rb:43:in `getaddress'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-         3.6.7.152/lib/new_relic/control/server_methods.rb:70:in `resolve_ip_address'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/control/server_methods.rb:59:in `convert_to_ip_address'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/control/server_methods.rb:45:in `server_from_host'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/control/server_methods.rb:19:in `server'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/agent/new_relic_service.rb:28:in `initialize'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/agent/agent.rb:39:in `new'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/agent/agent.rb:39:in `initialize'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/agent/agent.rb:70:in `new'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/agent/agent.rb:70:in `instance'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/new_relic/control/instance_methods.rb:75:in `init_plugin'
     /app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.6.7.152/lib/newrelic_rpm.rb:40:in `block in <class:Railtie>'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `instance_exec'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `run'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/initializable.rb:55:in `block in run_initializers'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `each'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `run_initializers'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/application.rb:136:in `initialize!'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/railtie/configurable.rb:30:in `method_missing'
     /app/config/environment.rb:5:in `<top (required)>'
     /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require'
     /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require'
     /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency'
     /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/application.rb:103:in          `require_environment!'
     /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.14/lib/rails/application.rb:305:in `block (2 levels) in initialize_tasks'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:236:in `call'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:236:in `block in execute'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:231:in `each'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:231:in `execute'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:175:in `block in          invoke_with_call_chain'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:168:in          `invoke_with_call_chain'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:197:in `block in invoke_prerequisites'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:195:in `each'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:195:in `invoke_prerequisites'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:174:in `block in invoke_with_call_chain'
     /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:168:in `invoke_with_call_chain'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/task.rb:161:in `invoke'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:149:in `invoke_task'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:106:in `block (2 levels) in top_level'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:106:in `each'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:106:in `block in top_level'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:115:in `run_with_threads'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:100:in `top_level'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:78:in `block in run'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/lib/rake/application.rb:75:in `run'
     /app/vendor/bundle/ruby/1.9.1/gems/rake-10.1.0/bin/rake:33:in `<top (required)>'
     /app/vendor/bundle/ruby/1.9.1/bin/rake:23:in `load'
     /app/vendor/bundle/ruby/1.9.1/bin/rake:23:in `<main>'
     Tasks: TOP => db:migrate => environment

and heroku logs:
     2013-10-31T11:44:20+00:00 heroku[slug-compiler]: Slug compilation started
     2013-10-31T11:44:52.399896+00:00 heroku[api]: Deploy b311a8a by ex@gmail.com
     2013-10-31T11:44:52.588630+00:00 heroku[api]: Release v10 created by ex@gmail.com
     2013-10-31T11:44:52+00:00 heroku[slug-compiler]: Slug compilation finished
     2013-10-31T11:44:53.144455+00:00 heroku[web.1]: State changed from up to starting
     2013-10-31T11:44:55.603062+00:00 heroku[web.1]: Stopping all processes with SIGTERM
     2013-10-31T11:44:57.453462+00:00 heroku[web.1]: Process exited with status 0
     2013-10-31T11:45:00.188675+00:00 heroku[web.1]: Starting process with command `bundle exec thin start -R config.ru -e $RAILS_ENV -p 32970`
     2013-10-31T11:45:07.793567+00:00 app[web.1]: /app/bin/wkhtmltopdf-amd64
     2013-10-31T11:45:08.480104+00:00 app[web.1]: Connecting to database specified by DATABASE_URL
     2013-10-31T11:45:09.700798+00:00 app[web.1]: >> Maximum connections set to 1024
     2013-10-31T11:45:09.700798+00:00 app[web.1]: >> Listening on 0.0.0.0:32970, CTRL+C to stop
     2013-10-31T11:45:09.700798+00:00 app[web.1]: >> Thin web server (v1.5.1 codename Straight Razor)
     2013-10-31T11:45:09.760592+00:00 heroku[web.1]: State changed from starting to up
     2013-10-31T11:45:43.023857+00:00 heroku[api]: Starting process with command `bundle exec rake db:migrate` by ex@gmail.com
     2013-10-31T11:45:47.706892+00:00 heroku[run.7727]: Awaiting client
     2013-10-31T11:45:55.105222+00:00 heroku[run.7727]: State changed from starting to up
     2013-10-31T11:45:57.322699+00:00 heroku[run.7727]: Error R99 (Platform error) -> Failed to launch the dyno within 10 seconds
     2013-10-31T11:45:57.323016+00:00 heroku[run.7727]: Stopping process with SIGKILL
     2013-10-31T11:45:57.368215+00:00 heroku[run.7727]: State changed from up to complete
     2013-10-31T11:46:04.657083+00:00 heroku[run.7727]: Starting process with command `bundle exec rake db:migrate`
     2013-10-31T11:48:08.633448+00:00 heroku[run.7727]: Stopping all processes with SIGTERM
     2013-10-31T11:48:18.781513+00:00 heroku[run.7727]: Stopping remaining processes with SIGKILL
     2013-10-31T11:48:18.781292+00:00 heroku[run.7727]: Error R12 (Exit timeout) -> At least one process failed to exit within 10 seconds of SIGTERM
     2013-10-31T11:48:19.712818+00:00 heroku[run.7727]: Client connection closed. Sending SIGHUP to all processes
     2013-10-31T11:48:21.005685+00:00 heroku[run.7727]: Process exited with status 137

A: The heroku run command opens a connection to Heroku on port 5000. So, the problem was in my new ISP. Port 5000 is blocking.
Heroku docs: https://devcenter.heroku.com/articles/one-off-dynos#troubleshooting
Another question:  Heroku run console get "Timeout awaiting process"


text:
Q: Why Azure Redis Cache on asp.net use only few connected client of 1000 and throw timeout error? In the last days i'm trying to optimize my website due low performance casued by redis cache when i have a peak of connection.
I'm using redis version 1.2.6 and i have set abortConnect=false in connection string.
here how i get the connection to redis:
private static readonly Lazy<ConnectionMultiplexer> LazyConnection
  = new Lazy<ConnectionMultiplexer>(() =>
ConnectionMultiplexer.Connect(GetRedisConnectionString()));

private static readonly Lazy<ConnectionMultiplexer> LazyConnection
  = new Lazy<ConnectionMultiplexer>(() =>
  {
      var connection = ConnectionMultiplexer.Connect(GetRedisConnectionString());
      connection.PreserveAsyncOrder = false;
      //connection.TimeoutMilliseconds
      return connection;
  });

In global.asax i've changed the min Threads as suggested in this article http://stackexchange.github.io/StackExchange.Redis/Timeouts
    int workerThreads = 500;
    int iocpThreads = 500;

    System.Threading.ThreadPool.SetMinThreads(workerThreads, iocpThreads)

But we still have some error like this one in log:
Timeout performing GET campaign_url_728566_288, inst: 19, mgr: Inactive,
err: never, queue: 7, qu: 0, qs: 7, qc: 0, wr: 0, wq: 0, in: 0, ar: 0,
clientName: RD00155D881345, serverEndpoint:
Unspecified/**********************, keyHashSlot: 6859, IOCP:
(Busy=0,Free=1000,Min=500,Max=1000), WORKER:
(Busy=25,Free=8166,Min=500,Max=8191)

or
Timeout performing GET campaign_url_728566_288, inst: 7, mgr: Inactive, err:
never, queue: 24, qu: 0, qs: 24, qc: 0, wr: 0, wq: 0, in: 4488, ar: 0,
clientName: RD00155D881345, serverEndpoint: Unspecified**********,
keyHashSlot: 6859, IOCP: (Busy=0,Free=1000,Min=500,Max=1000), WORKER:
(Busy=40,Free=8151,Min=500,Max=8191)

Now i notice that the max connection created and showed in the portal are max 20, when i expect to have more than them during high volume.

Is there any setting to increase the number of connection from ConnectionMultiplexer? Or the problem is related to the size of the cache (currently C1 standard) or due limited bandwidth?

A: Such issues can be caused by Server or Client side issues. Have you looked into https://gist.github.com/JonCole/db0e90bedeb3fc4823c2#file-diagnoserediserrors-clientside-md and https://gist.github.com/JonCole/9225f783a40564c9879d#file-diagnoserediserrors-serverside-md?
If you send us the following information (https://gist.github.com/JonCole/132b255425268459ec95#file-supportquestionnaire-md) at azurecache@microsoft.com, we can investigate as well to see if there are any bottlenecks on the server and what recommendations we might have.


text:
Q: Align last element in Span to opposite side of box then first element I have a Span element with a index count, and an exit button in the same line. I need the exit button to be at the opposite side of the Span. However with my current CSS setup, all elements are spaced equally, how do I adjust this so it only affects the button?

      {{ documentInfoLabel() }} ({{ this.count }}/{{ this.filesCount }})

 .index-count {
    display: flex;
    justify-content: space-between;
  }


text:
Q: Practices of MVC3 with AJAX? I have worked with MVC/MVC2 and built some web applications based on Nerddinner. Those applications only use webform and entity framework. I would like to start to use more Ajax and looked for some tutroials but they are a bit out of day. Does any one have found some recent practices/examples/tutorials/ of MVC3 with more integration of Ajax?
Thank you very much!

A: I recommend book 'Pro ASP.NET MVC Framework' by Steven Sanderson - it have examples of real applications and problems in development in begin, if you want - you can go in more detail chapters with description of all mechanisms, ajax and jquery basics included too. Book available for MVC2. To learn more about mvc 3 - read Scott Gu blog.
For ajax read JQuery tutorial:


text:
Q: Is there an application I can use to protect documents? Essentially I would like to have a section of a site, separate from the WP admin, that can hold documents for registered users of a certain group to view accessible only by user/password.  It would really be nice if the documents themselves could not be linked to or accessed by URL unless logged in. Please let me know of any suggestions!

A: Hello Maxwell and welcome to WPSE :)
I want to believe that when you talk about:

*

*an "application" on a site about WordPress, you most likely refer to a "Plugin".

*"a section of a site, separate from the WP admin" you probably mean "A page or Post in the front-end (site/blog)"

*"the documents themselves could not be linked to or accessed by URL unless logged in" you mean that they are "Password Protected" with a "URL that is NOT traceable".

If my assumptions are (hopefully) correct then you are looking for a Download Manager. There are a few in the WordPress Database and these are the links to a couple of them.
WP-Filebase Download Manager, very well supported with a sync feature. !!
WordPress Download Manager, never tried it but looks quite simple and very user friendly.
WordPress Download Monitor - we use it and are very happy with it. :)
Please have a look and see which one meets your needs.

I hope this helps. Let us know how you do,
marikamitsos


text:
Q: Correcting confidence intervals for multiple comparisons using the multcomp package In this excellent post on cross validated an answer mentioned that it is relatively easy to correct confidence intervals for multiple comparisons.
I am wondering whether this is possible using the multcomp package in R
Here's an example model using the mtcars dataset from base R, a multivariate regression predicting miles per gallon (mpg) from a list of predictors.
set.seed(1234)
df <- mtcars

# which variables predict miles per gallon?
sumMod <- summary(mod <- lm(formula = mpg ~ cyl + disp + hp + drat + wt + qsec + vs + gear,
                            data = df))

Now run the model through the multcomp package using the glht function.
# adjust using multcomp
library(multcomp)
K <- length(coefficients(mod))
modGLHT <- glht(model = mod,
                linfct = diag(K))

In multcomp you choose the method of adjustment using the test = adjusted(type = 'foo') argument within the package's summary() function
sumNone <- summary(modGLHT, test = adjusted(type = "none")) # no adjustment
sumSingleStep <- summary(modGLHT, test = adjusted(type = "single-step")) # single-step method

Now if we compare the p-value for the wt coefficient under no correction and with single-step correction...
data.frame(correction = c("none", "single-step"),
           coefs = c(round(sumNone$test$coefficients[6],2),
                     round(sumSingleStep$test$coefficients[6],2)),
           p = c(round(sumNone$test$pvalues[6],3),
                 round(sumSingleStep$test$pvalues[6],3)))

 # output
 #   correction coefs     p
 #         none -4.36 0.003
 #  single-step -4.36 0.024

We can see that the p-value has increased after applying single-step correction. So far so good.
My issue is how to get corrected confidence intervals?
I tried applying adjusted(type = 'foo') within the confint() function (once again for illustration I have focused on the wt predictor) like so...
# get CIs using four different methods
ciNone <- round(as.data.frame(confint(modGLHT, adjusted(type = "none"))$confint)[6,],3)
ciSS <- round(as.data.frame(confint(modGLHT, adjusted(type = "single-step"))$confint)[6,],3)
ciShaffer <- round(as.data.frame(confint(modGLHT, adjusted(type = "Shaffer"))$confint)[6,],3)
ciWestfall <- round(as.data.frame(confint(modGLHT, adjusted(type = "Westfall"))$confint)[6,],3)

# put them all together for comparison
cbind(data.frame(correction = c("None", "Single_Step", "Shaffer", "Westfall")),
      rbind(ciNone, ciSS, ciShaffer, ciWestfall))

# output
#     correction Estimate    lwr    upr
# 6         None   -4.356 -8.274 -0.439
# 61 Single_Step   -4.356 -8.269 -0.444
# 62     Shaffer   -4.356 -8.276 -0.437
# 63    Westfall   -4.356 -8.279 -0.434

No it looks to me as if something is going on, there are some very small differences. But when I run the confint() function on its own and ...
confint(modGLHT, adjusted(type = "Shaffer"))

the output makes no mention anywhere of type of error correction. I also get no error message. So I can't tell if the adjusted(type = 'foo') argument is doing anything nor whether the above differences in the CIs using the different methods are actual differences due to the method itself or simply an artefact of some randomness in a Markov-type procedure used to generate the intervals.
So is it legitimate to add the adjusted(type = 'foo') argument to the confint() function in multcomp?. The help documentation for the function does not say so and although I got no error message when I did it I cannot tell if it worked.
Any help much appreciated.

A: No, you can't specify type of adjustment when computing confidence intervals with multcomp. As discussed in the comments, you can choose between individual confidence intervals and simultaneous confidence intervals.

*

*Individual confidence intervals: Control the coverage probability of each confidence interval separately, ie., each confidence interval will contain the true parameter 100(1-α)% times if the experiment is repeated.

*Simultaneous confidence intervals: Control the overall coverage probability, ie, all confidence intervals will contain their true parameter 100(1-α)% times if the experiment is repeated. This corresponds to family-wise error rate FWER = α because the probability of one or more false discoveries (type I errors) is α. [However, simultaneous CIs are not equivalent to Bonferroni correction; see the update below.]

multcomp takes into account the correlations between hypotheses to get the coverage of simultaneous confidence intervals right and that's all the adjustment needed. The documentation is somewhat clear about all this.
To compute p-values, use the summary function on a glht object and specify how to adjust the p-values with the test = adjusted(type = "method") argument. The available methods include "single-step" (the default) and "bonferroni".
To compute confidence intervals, use the confint function of a glht object and specify how to compute the critical value with the calpha argument. There are two options: univariate_calpha() to compute univariate confidence intervals and adjusted_calpha() to compute simultaneous confidence intervals. Basically, confint ignores the type = "method" argument, if provided.
If multcomp doesn't adjust simultaneous confidence intervals, why does it seem that something is going on? It's because there is randomness in the computation of the critical value, calpha.
multcomp uses mvtnorm::qmvt to compute calpha, which in turn uses as a stochastic algorithm to find the quantiles a multivariate normal distribution.
In effect this is what you did: You fix the random seed once and call a stochastic function multiple times. You get slightly different critical values.
set.seed(1234)
calpha <- qmvt(level, ...)
calpha <- qmvt(level, ...)
calpha <- qmvt(level, ...)

Instead fix the seed before calling the stochastic function. You get exactly the same critical value each time and the simultaneous confidence intervals won't change.
set.seed(1234)
calpha <- qmvt(level, ...)
set.seed(1234)
calpha <- qmvt(level, ...)
set.seed(1234)
calpha <- qmvt(level, ...)

Let's demonstrate this on your example.
library("broom")
library("multcomp")
library("tidyverse")

options(
  pillar.sigfig = 5
)

mod <- lm(
  formula = mpg ~ cyl + disp + hp + drat + wt + qsec + vs + gear,
  data = mtcars
)

# Usually we aren't interested in testing that the intercept is 0.
# So let's skip it.
K <- diag(length(coef(mod)))[-1, ]
rownames(K) <- names(coef(mod))[-1]
K
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#> cyl     0    1    0    0    0    0    0    0    0
#> disp    0    0    1    0    0    0    0    0    0
#> hp      0    0    0    1    0    0    0    0    0
#> drat    0    0    0    0    1    0    0    0    0
#> wt      0    0    0    0    0    1    0    0    0
#> qsec    0    0    0    0    0    0    1    0    0
#> vs      0    0    0    0    0    0    0    1    0
#> gear    0    0    0    0    0    0    0    0    1

modGLHT <- glht(
  model = mod,
  linfct = K
)

methods <- c("none", "single-step", "Shaffer", "Westfall")
names(methods) <- methods

There is randomness in computing the critical value, calpha. So we get slightly different simultaneous confidence intervals for the same set of hypotheses.
set.seed(1234)

methods %>%
  map_dfr(

    # `confint` silently ignores `adjusted`
    ~ tidy(confint(modGLHT, adjusted(type = .))),
    .id = "method"
  ) %>%
  filter(
    contrast == "cyl"
  )
#> # A tibble: 4 × 5
#>   method      contrast estimate conf.low conf.high
#>   <chr>       <chr>       <dbl>    <dbl>     <dbl>
#> 1 none        cyl      -0.52659  -3.3654    2.3122
#> 2 single-step cyl      -0.52659  -3.3665    2.3133
#> 3 Shaffer     cyl      -0.52659  -3.3670    2.3138
#> 4 Westfall    cyl      -0.52659  -3.3624    2.3093

We fix the random seed before computing the critical value calpha, so the simultaneous confidence intervals are computed in a reproducible way.
methods %>%
  map_dfr(

    # `confint` silently ignores `adjusted`
    ~ {
      set.seed(1234)
      tidy(confint(modGLHT, adjusted(type = .)))
    },
    .id = "method"
  ) %>%
  filter(
    contrast == "cyl"
  )
#> # A tibble: 4 × 5
#>   method      contrast estimate conf.low conf.high
#>   <chr>       <chr>       <dbl>    <dbl>     <dbl>
#> 1 none        cyl      -0.52659  -3.3648    2.3116
#> 2 single-step cyl      -0.52659  -3.3648    2.3116
#> 3 Shaffer     cyl      -0.52659  -3.3648    2.3116
#> 4 Westfall    cyl      -0.52659  -3.3648    2.3116

Updates
Bonferroni controls the familiy-wise error rate (FWER) at the α level and simultaneous confidence intervals are 100(1-α)% family-wise confidence intervals. So Bonferroni and simultaneous CIs have the FWER concept in common. But they are not equivalent. Why?
The Bonferroni method divides the p-values of m simultaneous hypotheses by m. The procedure is conservative: it guarantees that the FWER is ≤ α rather than = α and it tends to over-correct, a lot.
In general, we don't know the dependencies between hypotheses. However, we do with regression because we have an estimate of the covariance matrix Var{(β1, β2, ..., βp)}. So we can estimate correlations between hypotheses which are functions of the model coefficients (such as β1 = 0, β2 = 0, ..., βp = 0).
And this is how multcomp computes simultaneous confidence intervals: it takes into account the correlations between hypotheses to correct the critical value calpha "just the right amount". While Bonferroni ignores this information to apply the most stringent correction.

The simultaneous confidence intervals are determined by the set of hypotheses being tested. Changing the other hypotheses can lead to a different confidence interval for the same individual hypothesis because the overall coverage depends in a complex way on the correlations between all hypotheses.
set.seed(1234)

modGLHT <- glht(
  model = mod,
  linfct = c("cyl = 0", "disp = 0")
)

tidy(confint(modGLHT, adjusted(type = .)))
#> # A tibble: 2 × 4
#>   contrast  estimate  conf.low conf.high
#>   <chr>        <dbl>     <dbl>     <dbl>
#> 1 cyl      -0.52659  -2.8330    1.7798
#> 2 disp      0.016565 -0.014587  0.047716


text:
Q: angular ui grid column dropdown filter blank option While using angular ui grid we are using selectOptions to populate dropdown options as column filter. Something similar to the following code:
   angular.module('exampleApp', ['ui.grid'])
   .controller('exampleCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) {
var animals = [
  { id: 1, type: 'Mammal', name: 'Elephant' },
  { id: 2, type: 'Reptile', name: 'Turtle' },
  { id: 3, type: 'Mammal', name: 'Human' }
];

var animalTypes = [
  { value: 'Mammal', label: 'Mammal' },
  { value: 'Reptile', label: 'Reptile'}
];

$scope.animalGrid = {
  enableFiltering: true,
  columnDefs: [
    {
      name: 'type',
      field: 'type',
      filter: { selectOptions: animalTypes, type: uiGridConstants.filter.SELECT }
    },
    { name: 'name', name: 'name'}
  ],
  data: animals
};
}]);

    <link href="http://ui-grid.info/release/ui-grid.css" rel="stylesheet" />

UI Grid Dropdown Filter Example

This shows dropdown filter options for each column but with an extra empty option. How do I remove the empty/blank option or replace the empty/blank option with a 'All' text?

A: You can achieve this using a custom filter.
For your code snippet you would need to change the label property in animalTypes to id, and also add an option of 'All':
var animalTypes = [
  { value: 'All', id: '' },
  { value: 'Mammal', id: 'Mammal' },
  { value: 'Reptile', id: 'Reptile'}
];

Then modify the columnDef for the type column as follows:
columnDefs: [
  {
    name: 'type',
    field: 'type',
    // template for rendering a custom dropdown box
    filterHeaderTemplate: '

',
    filter: {
      // initialize the filter to 'All'
      term: '',
      // the dropdown options (used in the custom directive)
      options: animalTypes
    }
  },
  ...
],

Please note that you will need to use the filter.term property to initialize the filter to 'All'. If you don't you will find that a blank option is inserted at the top of the dropdown box when the grid loads. Initializing the drop down prevents this from happening.
You can then define a custom drop down directive to render a select box containing the animalTypes options:
app.directive('myCustomDropdown', function() {
  return {
    template: '<select class="form-control" ng-model="colFilter.term" ng-options="option.id as option.value for option in colFilter.options"></select>'
  };
});

Please see this Fiddle for a working example


text:
Q: Logs eventsource failed I create a nodejs app.
heroku local web works perfect.
However when I pushed it to heroku and open the application, error message pops up
ui error message
When I tried heroku logs --tail, another error shows up on the console
console error.
Please help me fix this, thank you!

A: I am the author of this post and I figured out where the problem is by executing
heroku run bash and manually restarting the program and soon observed the error in the output.
It was because I omitted installing one dependency, which caused the nodejs program fail to start.
However, the output of heroku logs --tail still needs improving. It does not return anything useful other than a 400 error.


text:
Q: How to run a script forever? I need to run my Python program forever in an infinite loop..
Currently I am running it like this -
#!/usr/bin/python

import time

# some python code that I want
# to keep on running

# Is this the right way to run the python program forever?
# And do I even need this time.sleep call?
while True:
    time.sleep(5)

Is there any better way of doing it? Or do I even need time.sleep call?
Any thoughts?

A: Here is the complete syntax,
#!/usr/bin/python3

import time

def your_function():
    print("Hello, World")

while True:
    your_function()
    time.sleep(10) #make function to sleep for 10 seconds

A: How about this one?
import signal
signal.pause()

This will let your program sleep until it receives a signal from some other process (or itself, in another thread), letting it know it is time to do something.

A: for OS's that support select:
import select

# your code

select.select([], [], [])

A: I know this is too old thread but why no one mentioned this
#!/usr/bin/python3
import asyncio

loop = asyncio.get_event_loop()
try:
    loop.run_forever()
finally:
    loop.close()

A: sleep is a good way to avoid overload on the cpu
not sure if it's really clever, but I usually use
while(not sleep(5)):
    #code to execute

sleep method always returns None.

A: Yes, you can use a while True: loop that never breaks to run Python code continually.
However, you will need to put the code you want to run continually inside the loop:
#!/usr/bin/python

while True:
    # some python code that I want
    # to keep on running

Also, time.sleep is used to suspend the operation of a script for a period of time.  So, since you want yours to run continually, I don't see why you would use it.

A: I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:
#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):
[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:
"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground:
        CTL-C

    ... from same user account but through a different terminal
        $ kill -2 <pid>
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus:
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

A: If you mean run as service then you can use any rest framework
from flask import Flask
class A:
    def one(port):
        app = Flask(__name__)
        app.run(port = port)

call it:
one(port=1001)

it will always keep listening on 1001
 * Running on http://127.0.0.1:1001/ (Press CTRL+C to quit)


text:
Q: How to resolve race conditions on debounced user input? For example, say a page returns search results based on debounced user text.
How do you account for the case where an endpoint has a highly variable latency in which the second call can return before the first call.
E.g.
User is typing "books and movies" with a keyup debounce of 500ms
The user slightly pauses in the middle so the string is "books", this triggers a search call.
The user continues typing and finishes, triggering the second call with "books and movies".
The second call returns first, populating the list based on "books and movies".
Then the first call, which was delayed comes back and re-renders the list based on "books".
The user sees only "books" and is confused.
The surefire way to solve this is with a button to manually trigger the call. I'd like to avoid this though so I've increased the debounce but I'm wondering if there's a better way.

A: We suppose that you use jQuery to make ajax calls.
One solution is to use a pooling system: basically an array containing ajax requests.
Each time, a new request is emitted, you abort all request in the pool.
So you ensure that the last request made will be the only one that will end.
Here is the implementation of the pool:
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
    jQuery(this).each(function (idx, jqXHR) {
        jqXHR.abort();
    });
    jQuery.xhrPool.length = 0;
};

Here is an example on how to use it with the "search repository API" from GitHub (https://developer.github.com/v3/search/#search-repositories):

jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
  jQuery(this).each(function (idx, jqXHR) {
    jqXHR.abort();
  });
  jQuery.xhrPool.length = 0;
};

$(document).ready(function(){
  $("#SearchField").autocomplete({
    source: function( request, response ) {
        // First we abort all other request
        jQuery.xhrPool.abortAll();

        $.ajax({
          url: "https://api.github.com/search/repositories",
          method: "get",
          dataType: "jsonp",
          data: {
            q: request.term
          },
          beforeSend: function (jqXHR) {
            // Before sending the request we add it to the pool.
            jQuery.xhrPool.push(jqXHR);
          },
          success: function(data) {
            var items = new Array();
            for(var i=0;i<data.data.items.length;i++)
            {
              items.push(data.data.items[i].name);
            }
            response(items);
          }
        });
      },
      minLength: 3,
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" >
<input type="text" id="SearchField" />

A: Javascript works synchronously so there is no possibility of race conditions if you write your code correctly.
I guess you are using ajax (ajax is supposed to be async, don't use sync ever, once you go sync, you can't go back) to get the query result. You are probably using some code like this:
var req=new XMLHttpRequest();

req.onreadystatechange=function(){
    if (req.readyState==4){
        if (req.status==200){
            // Your callback here which shows autocomplete suggestions maybe?
        }
    }
}

Hold on to that req variable. So once you do a new request, you can simply discard the old request like:
req.onreadystatechange=null;

You can also abort the ajax request like:
req.abort();


text:
Q: Get multiple values from dynamically generated items with mojolicious I'm developing a small webpage that reads data from a couple of files and render it into a website. In that website, user must be able to choose one or more items and perform some work with those (changing name, append values, etc). I've been able to do most of the work, but now I'm facing a problem. I have this form:

    % foreach my $value ( @{ stash('tagitems') } ) {

            %= form_for 'save' => begin
                <input type="radio" name="radioid">
                %= hidden_field 'id' => $indexnum
                %= input_tag 'tag', value=>"$value", size=>"50%"
                %= submit_button 'Save changes'
                <%= select_field 'levelSelected' => [ @{ stash('levelsArray') }] %>
                <button type="submit" form="insertForm">Insert</button>
            % end
            <form action="/insert" id="insertForm"></form>

        % $indexnum += 1;
    % }

I'm getting everything rendered and it's ok. I can use the save form (that routes to a sub that changes it's name. the problem is with the inserform. The insert is supposed to check every radio button that it's checked and take the value tag and levelSelected.
How can I do this?
Thanks.
Edit:
I've multiple instances that looks like this:

So, I need to have just one insert button (instead of one per item) that find out whatever radio button is checked and get info of all checked items (tag and levelSelected) when clicked the submit button.
EDIT2 - CODE THAT WORKS:
I've found a way to do it. The code is here:
%= form_for 'save' => begin
    <button type="submit" formaction="insert">Insert</button>
    % foreach my $value ( @{ stash('tagitems') } ) {

            <input type="checkbox" name="insert">
            %= hidden_field 'id' => $indexnum
            %= input_tag 'tag', value=>"$value", size=>"50%"
            <button type="submit" formaction="save">save</button>
            <%= select_field 'levelSelected' => [ @{ stash('levelsArray') }] %>

    % }
    % end
</form>

A: This can be done using this piece of code:
%= form_for 'save' => begin
    <button type="submit" formaction="insert">Insert</button>
    % foreach my $value ( @{ stash('tagitems') } ) {

            <input type="checkbox" name="insert">
            %= hidden_field 'id' => $indexnum
            %= input_tag 'tag', value=>"$value", size=>"50%"
            <button type="submit" formaction="save">save</button>
            <%= select_field 'levelSelected' => [ @{ stash('levelsArray') }] %>

    % }
    % end
</form>

Then, in the controller:
get '/insert' => sub {
    my $mojo = shift;
    my @all_values;

    foreach my $field ('id', 'insert', 'tag', 'levelSelected') {
       @all_values = @{$mojo->every_param($field)};
        print Dumper (@all_values);
  }
};


text:
Q: Datatype for formdata at server side I would like to post a audio file to my server. Here is how I am trying to do:
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/test/testMethod',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

And at server side I have a method:
[HttpPost]
public void testMethod(??What datatype??  postedData)
{

}

What would be the datatype for postedData parameter? I tried with object and byte datatype. Any help would help.

A: I got it work by using FormCollection like:
[HttpPost]
public void testMethod(FormCollection frmCollection)
{
    Request.Files[0]  //-- this gives you the posted file
}


text:
Q: special characters and chinese fonts inserting in jsp page not working in spring controller abc.jsp page.   i  am trying to insert chines fonts in the form.
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />

<form id="bform"  action="addemo" method="POST" enctype="multipart/form-data"  class='form-group' accept-charset="utf-8">

                                Book Image <input type='file' name="file"
                                    class='btn' required="required" id="image_file"
                                    onchange="return validateimage();">

                                Book Title <input type='text' name='title'
                                    class='form-control'  placeholder='Title' required="required">

                                <input type='Submit' name='cat_img' value='Add'
                                    class='btn btn-success'> <input type='reset'
                                    name='cat_img' value='Cancel' class='btn btn-primary'>

                        </form>

In the above form when i am  adding chinese fonts "你好"
and submitting the form request goes to controller.
@RequestMapping(value = "addemo", method = RequestMethod.POST)
    public JSONObject view(HttpServletRequest request,@Valid Books model, BindingResult results,
            @RequestPart(name = "file", required = false) MultipartFile image) throws ExecutionException, UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("title");
        System.out.println("encoding: "+request.getCharacterEncoding());
        System.out.println("received: "+username);
        System.out.println("received: "+username);
        JSONObject jsonObject = new JSONObject();
        System.out.println(model.getTitle());

i am getting this on my console
encoding: utf-8
received: 你好
received: 你好
你好
你好
How should i get the utf-8 encoded data in a string params .
please explain.

A: You need to look at UTF-8 support in the following areas:
URLs,
Apache,
HTML,
JavaScript,
POST data
File download,
JSPs,
Java code,
Tomcat,
Oracle,
File system
Go through the following link that might help u :- http://blogs.warwick.ac.uk/kieranshaw/entry/utf-8_internationalisation_with/


text:
Q: Modifying files from external library in Java I have a Spring Framework project which uses Maven for resolving dependencies. The project has a dependency to another Spring project (Spring Social Facebook), which is used for Facebook login. Suddenly, I started to get a lot of errors because the Facebook login functionality broke due to changes in the Facebook API. The solution is extremely simple but requires a minor change within the external library's files - changing a variable from the type integer to long.
Now I know the solution, but I don't have control over this library. I would like to fix this problem myself until the library is updated with the fix, rather than waiting around for days with a broken system.
My question is: is there any easy way in which I can make a change to the source code of this library until a fix is available in the library itself? What is the recommended way of doing this? Two things currently come to mind: forking the library, make the change, and create a private Maven repository and replace the dependency with one that uses the private repository. If I can, I'd like to avoid that. The other way I can think of, would be to fork the library, make the change, compile the updated library into a jar file and replace the Maven dependency to use the jar file.
Is there a better way? What would you recommend in a (temporary) scenario like this? Thanks!

A: From working experience, in more than one company I have seen the following approach:

*

*Fix the issue in the source code

*Package it again with the same Maven coordinates

*Add a classifier, which was usually companyname-patch(ed)

*Put it in the enterprise Maven repository (i.e. Artifactory or Nexus)

As such, you would move from
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.7</version>
</dependency>

To
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.7</version>
  <classifier>company-patch</classifier>
</dependency>

This would help you to keep more traceability:

*

*The classifier makes it clear to internal developers and also to contractors that this is a company patch

*You know exactly to which library and which version the patch was applied (hence, partially self-documenting)

Furthermore, it is actually a legal and good usage of the Maven classifier feature.
Reusing the same Maven coordinates may affect portability (I have a different behavior on my local machine, why?) and maintainability (let's update this library, ops.. it was the patched one, I didn't know), while creating new Maven coordinates may create misunderstanding (what's this library?) and errors (I will replace by this official one, ops.. It doesn't work anymore).

A: The latest Spring Facebook integration lib was released in August:
<dependency>
  <groupId>org.springframework.social</groupId>
  <artifactId>spring-social-facebook</artifactId>
  <version>2.0.2.RELEASE</version>
</dependency>

Since August there were only some minor changes introduced in their API, and it is highly unlikely that this would have broken their API compatibility with thousands of existing applications.
There are literally thousands of applications connected to Facebook, so Facebook would not (cannot really) allow itself to introduce breaking changes in their API. They have an elaborate versioning system with fallbacks and backwards compatibility etc. in order to protect existing integrations.
I understand that you believe you have found a possible fix for the library. What I suggest doing instead is looking into the code which leads to that specific scenario. It is much more likely that some subtle change in the way your code uses the lib leads to this "bug", rather than Facebook making such a mistake.


text:
Q: iOS: How to hook into MPMoviePlayerController? Okay so i am wanting to create a tweak that hooks into the MPMovieController.h file and changes the scaling button to another button. So firstly i checked i can hook into that class just for testing reason, so i hooked into the play function to see if when a video had began playing if i could show a UIAlertView. However I was unable to do so. Even though everything compiled fine and the DEB file was built successfully I still can not get this message to appear when the movie player is playing.
This is my Code:
Tweak.xm:
#import <UIKit/UIKit.h>
@interface MPMoviePlayerController
-(void)play;
@end

%hook MPMoviePlayerController
-(void)play
{
    NSString *Title = [NSString stringWithFormat:@"Title", nil];
    NSString *message = [NSString stringWithFormat:@"Message", nil];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:Title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
%orig;
}
%end

Thanks. P.S. After Installing I have reset and re-sprung my iphone.


text:
Q: is it possible to using socket.io-client under IE 9? is it possible to using socket.io-client under IE 9?
i implement chatting server by NodeJS with Socket.IO.
and implement chatting front-end by standard javascript.
im using Sockket.IO version 1.4.5.
this is my client-side code
var connectionOptions =  {
    "forceNew" : true,
    "reconnectionAttempts": "Infinity",
    "timeout" : 10000,.
    "transports" : ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'],
    'autoConnect': true
};

var socket = io.connect('http://localhost:3000', connectionOptions);

socket.on('connect', function() {
    console.log(1);
});

socket.on('message', function(data) {

});

socket.on('disconnect', function() {

});

on chrome and ie 10(and above version), it works well and console logging 1.
but on ie 9, it doesnt work. and network tracking request is not transmitted.
anybody help me plz.

A: IE9 does not support webSockets which socket.io works best with.  socket.io will detect that webSockets are not supported and will attempt to use one of the other transports (most likely xhr polling) which can work but may have some compromised behavior.   With xhr polling, there is not as reliable a "connect" and "disconnect" event (since there is no persistent connection) so you should try just sending a message to see if that works for you.
Other related answers:
IE and Socket.io compatibility
Will IE9 now be supporting WebSocket?


text:
Q: java.lang.NoSuchMethodError when installing plugin in ktor I am trying to add Resources plugin into my ktor client using the following code:
...
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.java.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.resources.*
import io.ktor.client.request.*
...

...
val HTTP_CLIENT = HttpClient(Java) {
            install(Resources)
        }
...

And here's part of my build.gradle.kts:
val ktor_version: String by project

plugins {
    val kotlinVersion = "1.6.10"
    kotlin("jvm") version kotlinVersion
    kotlin("plugin.serialization") version kotlinVersion
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")

    implementation("io.ktor:ktor-client-core:$ktor_version")
    implementation("io.ktor:ktor-client-java:$ktor_version")
    implementation("io.ktor:ktor-client-resources:$ktor_version")
}

The compile is successful, but when running I got following error:
java.lang.NoSuchMethodError: 'void io.ktor.client.HttpClientConfig.install$default(io.ktor.client.HttpClientConfig, io.ktor.client.plugins.HttpClientPlugin, kotlin.jvm.functions.Function1, int, java.lang.Object)'
2022-04-16 13:28:45 W/stderr:   at NMEBoot-1.1.mirai.jar//NoMathExpectation.NMEBoot.wolframAlpha.Conversation$Companion$HTTP_CLIENT$1.invoke(Conversation.kt:20)
2022-04-16 13:28:45 W/stderr:   at NMEBoot-1.1.mirai.jar//NoMathExpectation.NMEBoot.wolframAlpha.Conversation$Companion$HTTP_CLIENT$1.invoke(Conversation.kt:19)
2022-04-16 13:28:45 W/stderr:   at io.ktor.client.HttpClientKt.HttpClient(HttpClient.kt:41)
2022-04-16 13:28:45 W/stderr:   at NMEBoot-1.1.mirai.jar//NoMathExpectation.NMEBoot.wolframAlpha.Conversation.<clinit>(Conversation.kt:19)

I checked the jar and the source code and they both did have install method, but their signature was different from the signature described in the error.
I don't know if it is my fault or something else. Could someone help me solve this problem?
Edit: Here's a simplified project: KtorInstallTest

A: This is a bug on the Mirai side.

Mirai Console uses Kotlin 1.6.0 and for some reasons forces all plugins to use the same version of Kotlin, causing this problem. We plan to update to 1.6.20 by Mirai 2.11.0.


text:
Q: CQRS & Event Sourcing way to handle a single request that needs to generate multiple commands I am making a genealogy application as I am trying to learn Event Sourcing and CQRS. I have three aggregates in my application: PersonAggregate, FactAggregate, FamilyAggregate.
My request from the UI to the Server to add a spouse to a person is:
{
  personId: "", // And Existing Person in the DB
  personInput: {name: "Bob", birthDate: ""} // Input to create a new person in the DB
}

My Family Aggregate listens to the PersonAggregate for events of PersonCreated to keep a record of all people that have been created.
Would it be a good architecture for the UI to call the PersonAggregate to create the person (with the data about it needing to create a partnership between the two people instead of calling the FamilyAggregate), then on the PersonCreated event to put the data the FamilyAggregate will need to know to add the two people as spouses? Or is that a bad design because now the Event has command data in it?
When a person is created, the Person Aggregate also needs to send data to the FactAggregate to create a Fact about the person's birthdate.

A: The need to update multiple aggregates in a single transaction is a sign that aggregate boundaries are wrong. Because an aggregate is responsible for protecting a transaction boundary by definition. And a single event corresponds to a single transaction.
Let's consider how this case is handled in a non-computer world. The business domain is well designed there. Sharpened through centuries to be as robust and simple as it gets.
The point of decision is not a person or a family. It is the church. Metric book is the aggregate. When a priest makes up a decision, he writes it down into a metric book. Everything else - person's documents, genealogy, list of person's facts - are mere read models in the registration bounded context.
They can be aggregates in other bounded contexts. And some service may listen to registration events and update relevant entities after the original transaction is completed and event is written. Eventually.


text:
Q: Why is Java returning an error rather than an IOException when try and get a file lock This code running with Java 1.8.0_72 25.72-b15 64bit on Windows 8.1
protected FileLock getFileLockForWriting(FileChannel fileChannel, String filePath) throws IOException
    {
        logger.finest("locking fileChannel for " + filePath);
        FileLock fileLock;
        try
        {
            fileLock = fileChannel.tryLock();
        }
        //Assumes locking is not supported on this platform so just returns null
        catch (IOException exception)
        {
            return null;
        }

        //Couldnt getFields lock because file is already locked by another application
        if (fileLock == null)
        {
            throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_FILE_LOCKED.getMsg(filePath));
        }
        return fileLock;
    }

is reporting this error for a particular user
java.lang.Error: java.io.IOException: The specified server cannot perform the requested operation
    at sun.nio.ch.FileKey.create(Unknown Source)
    at sun.nio.ch.SharedFileLockTable.<init>(Unknown Source)
    at sun.nio.ch.FileLockTable.newSharedFileLockTable(Unknown Source)
    at sun.nio.ch.FileChannelImpl.fileLockTable(Unknown Source)
    at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
    at java.nio.channels.FileChannel.tryLock(Unknown Source)
    at org.jaudiotagger.tag.id3.AbstractID3v2Tag.getFileLockForWriting(AbstractID3v2Tag.java:1080)
    at org.jaudiotagger.tag.id3.AbstractID3v2Tag.writeBufferToFile(AbstractID3v2Tag.java:1462)
    at org.jaudiotagger.tag.id3.ID3v23Tag.write(ID3v23Tag.java:751)
    at org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:1011)
    at org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:920)
    at org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:932)
    at com.jthink.songkong.analyse.analyser.SongSaver.realSave(SongSaver.java:798)
    at com.jthink.songkong.analyse.analyser.SongSaver.saveSongToFile(SongSaver.java:623)
    at com.jthink.songkong.analyse.analyser.SongSaver.saveChanges(SongSaver.java:185)
    at com.jthink.songkong.analyse.analyser.SongSaver.call(SongSaver.java:160)
    at com.jthink.songkong.analyse.analyser.SongSaver.call(SongSaver.java:54)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: The specified server cannot perform the requested operation
    at sun.nio.ch.FileKey.init(Native Method)
    ... 21 more

It seems it is returning an Error because file locking is not supported, but it should be returning an IOException, (my code expects an IOException), why should this be
Update
I case relevent it's a Western Digital MyBook Live 3TBNAS, Firmware version is 02.43.10-048 which running Debian 5.0.4

A: All code above FileKey.create can throw a IOException so your assumption that this behaviour is not ok is correct.
Indeed this was already filed as bug. In Java 9 the Error will be gone and a IOException will be thrown instead.
Therefore for now you should be prepared to catch the error and evaluate the inner IOException.


text:
Q: Unable to user link_to_add_fields method from railscast Nested Model Form #196/#197 First of all I watched Railscast #196 and Railscast #197.
I have also read this  and a lot of other similar questions.
Im getting the following error:
Missing partial profils/compagny_fields, application/compagny_fields with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
  * "/home/me/www/Myapp/app/views"
It seems that its not a partial problem cause i can see the puts from my partial.
So on my models i have:

CompagnyModel: belongs_to :profil`
ProfilModel: has_many :compagnies, accepts_nested_attributes_for :compagnies

In my View I have:

          <%= p.label :firstname, "firstname" %>
          <%= p.text_field :firstname %>

          <%= p.label :lastname, "lastname" %>
          <%= p.text_field :lastname %>

<%= p.fields_for :compagnies do |n| %>

   <%= render 'compagnies_fields', :c => n %>
<% end %>

<%= link_to_add_fields "Add Compagny", p, :compagnies %>
<% end %>

<%= f.submit "save"
  %>

Finally here is my partial:

  <%= c.label :name, "Compagny"%>

  <%= c.text_field :name %>

  <%= link_to_remove_fields "remove", c %>

  <% puts "-----!-!-!-!-!-!-!-!-DEBUG-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!------" %>

A: Is that single quote on
CompagnyModel: belongs_to :profil`

in the actual model file?
Is the partial form being called saved in "profils/_compagny_fields.html.erb" or in "compagnies/_compagny_fields.html.erb"?
<%= p.fields_for :compagnies do |n| %>
  <%= render 'compagny_fields', :c => n %>
<% end %>

Try building the Profil.Compagnies model in the console to check that it is valid
new_profil = Profil.new
new_profil.compagnies.build

In the Profil_Controller I take it there is a variable @profil = Profil.new?
@profil = Profil.new
@profil.compagnies.build

Does the views/profil/new.html.erb (or views/profil/_form.html.erb if you're doing the forms in that way) have the form
<%= form_for(@profil) do |p| %>

A: I had the same error. You named your partial "compagny_fields" but you want to render 'compagnies_fields'. This was my problem, mayby it is yours too.

A: I solved this by changing this
render(association.to_s.singularize + "_fields", :f => builder)

to this
render(association.to_s , :f => builder)


text:
Q: Execution failed for task ':app:checkDebugAarMetadata'. Could not resolve all files for configuration ':app:debugRuntimeClasspath' when I want to run my react-native project I get this error. It was in github and before I cloned it it was working.
Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve com.facebook.react:react-native:+.
     Required by:
         project :app
         project :app > project :react-native-vector-icons
         project :app > project :react-native-async-storage_async-storage
         project :app > project :react-native-community_checkbox
         project :app > project :react-native-community_geolocation
         project :app > project :react-native-community_masked-view
         project :app > project :react-native-community_slider
         project :app > project :react-native-geocoder
         project :app > project :react-native-gesture-handler
         project :app > project :react-native-maps
         project :app > project :react-native-reanimated
         project :app > project :react-native-safe-area-context
         project :app > project :react-native-screens
         project :app > project :react-native-svg
      > Failed to list versions for com.facebook.react:react-native.
         > Unable to load Maven meta-data from https://jcenter.bintray.com/com/facebook/react/react-native/maven-metadata.xml.
            > Could not HEAD 'https://jcenter.bintray.com/com/facebook/react/react-native/maven-metadata.xml'. Received status code 502 from server: Bad Gateway

A: First, type the following address in your browser,
https://firebase.google.com
and if you get a 403 error, it means that the IPs of your place of residence are blocked . There are several things you can do to solve this problem:

*

*Uninstall Chrome browser from your system because they use it for location

*Use a valid VPN Or VPS, preferably from Germany, France or the United States

*Change your system clock to the clock of the country to which your IP has changed

A: Bin tray is experiencing some issues on their download network :
https://status.bintray.com/
Also if you are using obselete jCenter(), then replace it with mavenCentral() in your android/build.gradle


text:
Q: Data dump sandbox by RdbHost Rdbhost currently provides a sandbox with the Stack Overflow dump data.  It uses the PostgreSQL engine, and thus PostgreSQL syntax for SQL.
There is a PhpMinAdmin-type web-interface for manipulating the database.  There is also a Python DB API module.  The DB API module is described on our site, as well as an intro
on using SQLAlchemy to access SO data.
If you have any problems with it, please let me know at dkeeney@rdbhost.com.
Update, June 8: The data dump account on has been updated again yesterday with the June 1st data dump.

A: The stackoverflow data dump account on rdbhost.com has been updated to include the April data dump, with data through March 2010.

A: The stackoverflow data dump account on rdbhost.com has been updated again yesterday with data from the latest (June) datadump.
Now, the account has a customized stackoverflow 'look'.


text:
Q: pydot implemetation not extensible. Breaks inheritance I'm having trouble with python inheritance.
This example only outlines the hierarchy for a far more complicated code I can't post here, so bear with me while I give you all the details needed.
I have defined two classes:
class A(pydot.Node):
    def __init__(self):
        # do some init
        pydot.Node.__init__(self)

    def very_useful_method(self):
        return self._valuable_property

class B(A):
    def __init__(self):
        # do some initialization
        A.__init__(self)

if "__main__" == __name__
    # some code that uses add_node and get_nodes
    retrieved_b_instance.very_useful_method() #error, **Node** object has no attribute very_useful_method...

I'm pretty convinced I didn't get the inheritance process right, and that I'm doing something wrong with the __init__ calls.
I'm using python 2.7.
Any advice?
Trace:
Traceback (most recent call last):
  File "/home/reuts/PycharmProjects/AI4/Ex4_pydot.py", line 399, in <module>
    driver.interact()
  File "/home/reuts/PycharmProjects/AI4/Ex4_pydot.py", line 362, in interact
    self.parse_command(cmd)
  File "/home/reuts/PycharmProjects/AI4/Ex4_pydot.py", line 354, in parse_command
    options[args[0]]()
  File "/home/reuts/PycharmProjects/AI4/Ex4_pydot.py", line 344, in print_report
    print "node cpt: %s" % node.get_cpt()
AttributeError: 'Node' object has no attribute 'get_cpt'

Node is the base class from pydot's implementation (pydot.Node), on top of that there are two more classes I used while inheriting from pydot.Node.
I've now examined the code in pydot.py and I'm suspecting there is a conversion there. Coming from a Java and static-type background I'm slow in understanding the operations in get_node_list() and their effects on the returned instance's type.

A: I probably found the error. Apparently pydot.Node had a method that doesn't return what I expected of it (pydot is a graph implementation).
The actual nodes are stored as strings and the get_nodes() methods generates them all over again for each get_nodes call, which causes any extension of the pydot.Node class to be practically meaningless if used later on via get_nodes.
Update: Workaround
The way I found to save data while interacting with the implementation is to use the Node instance's obj_dict property, which is restored via the graph's obj_dict['nodes'] obj_dict elements (saved for all added nodes...)


text:
Q: I have a question about Bubble Process in Javascript When using event of function in addEventlistener(), does the bubble process run when using event.target?

A: Almost all the events "Bubble"
But, if you want to stop an event from "bubbling" then you can use:
event.stopPropagation()
If you want to stop the event flow from event target to top element in DOM, event.stopPropagation() method stops the event to travel to the bottom to top.


text:
Q: Cannot connect to an EC2 instance through web sockets I am running an Akka HTTP service on port 8080 in my EC2 instance. It expects web socket connections, but normal HTTP should return 400 bad request.
I use this code to start Akka service:
Http().bindAndHandle(route, "localhost", 8080)
From the remote terminal I have this expected behavior, but not from outside.
$ wget ec2-XX-XXX-XX-XXX.compute-1.amazonaws.com:8080
--2017-10-01 15:27:31--  http://ec2-XX-XXX-XX-XXX.compute-1.amazonaws.com:8080/
Resolving ec2-XX-XXX-XX-XXX.compute-1.amazonaws.com... XX.XXX.XX.XXX
Connecting to ec2-XX-XXX-XX-XXX.compute-1.amazonaws.com|XX.XXX.XX.XXX|:8080... failed: Connection refused.

Here is my inbound rules configuration:

If I do netstat --listen -p the port 8080 does not appear.
Thanks!

A: I found out the problem. I should be binding the service to the private IP address of the EC2 instance.


text:
Q: AWS DMS Replication Instance quota zeroed According to quota documentation the default value for Replication Instances is 60.
On my view for AWS DMS on target account I see max quota as zero and could not find any permission or configuration to allow that.

On another account (what is the source for the database to be migrated) the values shows as expected:

Other users with complete permissions on AWS account also mentioned they visualize same zero values for quotas.
Am I missing any step in order to have those available?
Thank you!

A: I went to Service Quotas and my console says:

The quotas can be adjusted by clicking on a quota and choosing Request quota increase:


text:
Q: How can i center a div and fill it with other divs so that it fits all the resolutions? I have been creating my website on a 1280*800 resolution computer and it works just fine until I use another computer with a different resolution. Please help me to solve the problem.

A: Use something like this:
#IDdiv {
margin-left:auto;
margin-right:auto;
width:80%; //for example
height:80%; //for example
}

It will look similar on all resolutions.
This will center the div horizontally.


text:
Q: Missing features in Ckeditor Using yii2-ckeditor-widget but missing upload tab and browser, how can I integrate those features ..
I have tried the 2amigos CKEditor Widget for editor.
But cant upload the image though I paste the url of the image.
any solution to get those features in yii2 ?

A: You need to define your Upload Action:
<?= $form->field($model, 'content')->widget(CKEditor::className(), [
        'options' => ['rows' => 6],
        'preset' => 'basic'
        'clientOptions' => [
            'filebrowserUploadUrl' => 'site/url'
        ]
    ]) ?>

And there should be your handler for file uploads on this route (http://hosannahighertech.co.tz/blog/mweledi/11-Yii2-CKEditor-and-Images-Upload).
You also can use file manager plugin which have integration with ckeditor:
https://github.com/MihailDev/yii2-elfinder
https://github.com/MihailDev/yii2-ckeditor


text:
Q: How find the minimum number? I have this task I need to complete:

"There are N athletes competing in a hammer throw. Each of them made M
throws. The athlete with the highest best throw wins. If there are
several of them, then the one with the best sum of results for all
attempts wins. If there are several of them, the athlete with the
minimum number is considered the winner. Determine the number of the winner of the competition."

I can find highest best throw wins, but I can't find the athlete with the minimum number.
Sample Input:
4 3
4 2 7
1 2 7
1 3 5
4 1 6

Sample Output:
1

My code so far:
row,columns = map(int,input().split())
matrix = [[int(i) for i in input().split()] for j in range(row)]
numbers = []
suma = []
for i in range(row):
    numbers.append(matrix[i][0])
    sumaa = sum(matrix[i]) - matrix[i][0]
    suma.append(sumaa)
new_matrix = [numbers,suma]
print(new_matrix.index(max(new_matrix)))

A: input = """4 3
4 2 7
1 2 7
1 3 5
4 1 6
"""

def winner(input):
    athletes = input.split("\n")
    best_throw = max(" ".join(athletes).split(" "))
    best_total = max(map(lambda s: sum(list(map(lambda n: int(n) if n != '' else 0, s.split(" ")))), athletes))

    best_athletes_indexes = []
    for i, athlete in enumerate(athletes):
        if best_throw in athlete.split(" ") and sum(map(int, athlete.split(" "))) == best_total:
         best_athletes_indexes.append(i)

    best_athletes_attempts = list(map(lambda i: len(athletes[i].split(" ")), best_athletes_indexes))

    return best_athletes_indexes[best_athletes_attempts.index(min(best_athletes_attempts))]

print(winner(input))

please please please do not ask me to explain this this is the first python i hav written in 2 years. i come from a world of type safety wth
my search history is literally "remove item from list python" the python standard library is strange

A: It's answer
a = []
b = []
row, columns = map(int, input().split())
for i in range(row):
  a.append(list(map(int, input().split())))
for i in range(row):
  b.append([max(a[i]), sum(a[i])])

print(b.index(max(b)))

A: Try this code:
row, columns = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(row)]
matrix_max_sum_elms = [[max(row), sum(row)] for row in matrix]
best_athlete_ind = matrix_max_sum_elms.index(max(matrix_max_sum_elms)) + 1
print(best_athlete_ind)

Explanation:
First, we create a list of lists with an input value,
then we create a new list of lists, in which each list contains the maximum value and the sum of the elements of the input values. As a result, we take the index of the list that contains the maximum value and add 1, since indexing starts from 0


text:
Q: MariaDB are bitwise operators defined on strings? Is the behavior of BITAND, (bitwise and) defined in MariaDB over strings?
SELECT '0011' & '0011', 'ff' & 'ff', 'yy' & 'YY', '5' & '5';
+-----------------+-------------+-------------+-----------+
| '0011' & '0011' | 'ff' & 'ff' | 'yy' & 'YY' | '5' & '5' |
+-----------------+-------------+-------------+-----------+
|              11 |           0 |           0 |         5 |
+-----------------+-------------+-------------+-----------+

I'm just wondering what is exactly happening here.

A: It appears that MariaDB (and MySQL for that matter) attempts to implicitly cast operands of bitwise operators to integers, and it is known MySQL behaviour when converting strings to integers to ignore the rest of the string if it encounters non-digits, e.g. cast('123abc' as integer) will yield integer 123, and cast('ff' as integer) will yield 0.
This is a feature of the bitwise operators and bit functions, not the BIT type itself, as stated in the MySQL manual (I assume MariaDB inherits this behaviour):

Currently, bit functions and operators require BIGINT (64-bit integer) arguments and return BIGINT values, so they have a maximum range of 64 bits. Arguments of other types are converted to BIGINT and truncation might occur.

It looks like this behaviour is going to change in MySQL version 8:

An extension for MySQL 8.0 changes this cast-to-BIGINT behavior: Bit functions and operators permit binary string type arguments (BINARY, VARBINARY, and the BLOB types), enabling them to take arguments and produce return values larger than 64 bits.

which will bring it in line with your expectations.