text:
Q: Designing a weekly calendar with react on rails I am trying to design an appointment schedule layed out by week in my react on rails application. It should look like this when done:

*

*Colored boxes will be bootstrap classes depending on the status of the appointment. They should be links to the individual appointment show pages (I know I don't have this done yet, it's not my primary concern at the moment).

Here is the data structure I'm working with in JSON:
{
  "clients": [
    {
      "id": 2,
      "name": "Oscar",
      "appointments": [
        {
          "id": 2,
          "status": "Not Done",
          "report": "Not Started",
          "start": "2017-09-24T12:06:19.000Z",
          "finish": "2017-09-24T12:36:19.000Z",
          "scheduled": "2017-09-24T12:09:19.000Z",
          "duration": null
        },
        {
          "id": 3,
          "status": "Not Done",
          "report": "Not Started",
          "start": "2017-09-18T13:07:56.000Z",
          "finish": "2017-09-18T13:37:56.000Z",
          "scheduled": "2017-09-18T13:10:56.000Z",
          "duration": null
        }
      ],
      "url": "http:\/\/localhost:3000\/clients\/2.json"
    },
    {
      "id": 3,
      "name": "Molly",
      "appointments": [
        {
          "id": 4,
          "status": "Not Done",
          "report": "Not Started",
          "start": "2017-09-21T11:09:31.000Z",
          "finish": "2017-09-21T11:39:31.000Z",
          "scheduled": "2017-09-21T11:12:31.000Z",
          "duration": null
        }
      ],
      "url": "http:\/\/localhost:3000\/clients\/3.json"
    }]}

Appointments.js.coffee
@Appointments = React.createClass

getInitialState: ->
    clients: @props.clients

  getDefaultProps: ->
    clients: []

  render: ->
    React.DOM.div
      className: 'client-appts'
      React.DOM.h2
        className: 'title'
        'Clients Title'
      React.DOM.table
          className: 'table table-bordered'
          React.DOM.thead null,
            React.DOM.tr null,
              React.DOM.th null, 'Client'
              React.DOM.th null, 'col 2'
              React.DOM.th null, 'col 3'
          React.DOM.tbody null,
            for client in @state.Clients
              React.createElement Client, key: client.id, client: client

This is my client.js.coffee
@Client= React.createClass
  render: ->
      React.DOM.tr null,
        React.DOM.td null, @props.client.name
        for appointment in @props.client.appointments
          React.createElement Appointment, key: appointment.id, appointment: appointment

This is my appointment.js.coffee
@Appointment = React.createClass
    render: ->
      React.DOM.td null,
        React.DOM.p null, @props.appointment.status
        React.DOM.p null, @props.appointment.report

I know rails OK, but am new to react. How do I design the structure so that the appointments show up only when they're supposed to. Once I have that figured out I need to figure out how to click through pages for different weeks. How do I design the react components? Anyone see another good example on S/O or G/H?


text:
Q: Explanation for (t for t in L if t ) in python There was an exercise in python to remove an empty tuple(s) from a list of tuples.
The input:
input: [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
The expected output
output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']
Here is the solution that they have provided.
L = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
L = [t for t in L if t]
print(L)

But i couldn't understand condition  L = [t for t in L if t].  can anyone help me on this?

A: L = [t for t in L if t] can be written in pseudo-code like this:
result_list = []

for t in L:
  if t is True:
    result_list.append(t)

The pseudo code just does not replace the original list, it creates a new one. You also need to know that an empty tuple evaluates to False in Python.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel - MVC and Multiple Views I have the following URL example.com/post with this route Route::get('/post','PostController@index). Furthermore, I have another route and contoller pair: example.com/comment and Route::get('/comment','CommentController@index').
Each path is independently navigatable. Now in my index, I would like to combine both of these two together to show comments and posts together.
What should I do?
1) Make the pair of Route::get('\','IndexController@index') and combine two controllers, that is first echo $commentController->index() and then return $postController->index().
2)Make a separate view for index and pass it the post and comment data.
3)Neither of these methods are proper and I should do something totally different.


text:
Q: nftables meter error: syntax error, unexpected saddr, expecting comma or '}' I have below nftable rule to add a connection rate meter:
nft add rule ip filter input tcp dport @rate_limit meter syn4-meter \{ ip  saddr . tcp dport timeout 5m limit rate 20/minute \} counter accept

It generates the error:
Error: syntax error, unexpected saddr, expecting comma or '}'
add rule ip filter input tcp dport @rate_limit ct state new meter syn4-meter { ip saddr . tcp dport timeout 5m limit rate 20/minute } counter accept
                                                                                ^^^^^

nftables ruleset
table ip filter {
    chain input {
        type filter hook input priority 0; policy accept;
    }
}
table inet filter {
    set rate_limit {
        type inet_service
        size 50
    }

    chain input {
        type filter hook input priority 0; policy accept;
    }
}

Initially I tried just inet but due to the error I added ip to see if it make any difference to no success. Any pointers?

A: You have two problems:

*

*using a too old version of nftables.
I could reproduce the error Error: syntax error, unexpected saddr, expecting comma or '}' using nftables version 0.7 (as found in Debian 9). Meters (nftables wiki) suggests nftables >= 0.8.1 and kernel >= 4.3.
Upgrade nftables. Eg, on Debian 9, using the stretch-backports (stretch-backports, not buster-backports) version 0.9.0-1~bpo9+1, sorry you'll have to search how to do that on other distributions.

*using the wrong table, as told by the command (when using nftables 0.9.2):
# nft add rule ip filter input tcp dport @rate_limit meter syn4-meter \{ ip  saddr . tcp dport timeout 5m limit rate 20/minute \} counter accept
Error: No such file or directory; did you mean set 'rate_limit' in table inet 'filter'?

Indeed, many objects are local to the table where they are declared. So you can't declare it in the inet filter "namespace" and use it in the ip filter "namespace". That's a difference with for example iptables + ipset, where the same ipset set can be used in any table.
This will work (once you get a recent enough nftables):
nft add rule inet filter input tcp dport @rate_limit meter syn4-meter \{ ip  saddr . tcp dport timeout 5m limit rate 20/minute \} counter accept

Or alternatively you can move back the meter definition to the ip filter table.


text:
Q: I have 3 objects in the real world that I want to mark on a x y graph, I know where to plot 2 of them but how to mark the third point? In the real world I have 3 points of interest ABC. A B and C are each 20 cm apart and are placed in a equilateral triangle formation.
A coordinates are (-10, 0) and C coordinates are (10, 0). I'm using these points to show the distance and I will form hyperbolas between each of these points and wish to know where intersection occurs.
What coordinates do I plot B in relation to A and C. Would I find 60 degrees from A (-10,0) and see where it intersects the Y axis. Would it be at (0, 10), (0, 20) or something else, I'm quite confused how this would work.

A: You have an equilateral triangle, ABC, and points A and C are (-10, 0) and (10, 0) respectively.  You appear to know that B will lie directly above the midpoint of AC so the x coordinate of B is 0.  Now imagine drawing a line from B to that midpoint. D.  That divides the equilateral triangle into two right triangles, ABD and CBD.  The distance from A to C is 20 so AB and CB, the hypotenuses of the right triangles, are also 20.  AD and CD, legs of the two right triangles, are 20/2= 10.  By the Pythagorean theorem, h, the y coordinate of B, satisfies $h^2+ 10^2= 20^2$ so $h^2= 400- 100= 300$.  $h= \sqrt{300}= 10\sqrt{3}$ so B has coordinates $(0, 10\sqrt{3})$.


text:
Q: Userland autoboxing? Is it possible to implement autoboxing for your own classes?
To illustrate my example, this is what I might want to write:
Foo foo = "lolcat";

And this is what Java would do (as per my own definitions, somewhere, somehow), under the hood:
Foo foo = new Foo();
foo.setLolcat("lolcat");

So, is this possible somehow, or is it a JVM-feature only?

A: No, java does not support operator overloading (http://en.wikipedia.org/wiki/Operator_overloading).
Autoboxing is a compiler feature and not available for your own classes.
The reasoning is explained here:
http://www.cafeaulait.org/javafaq.html#xtocid1902938


text:
Q: WordPress Protected Page Password Cookie When you login to a password protected page, WordPress sets a cookie that looks like wp-postpass_hash.
This cookie seems to stick around forever. I'd like to be able to provide the user with a 'log out' link. Is there a way for me to find and delete this particular cookie if I don't know the hash? Maybe there's a way to get the cookie by finding it based on 'wp-postpass'?
I've seen other solutions for altering WordPress' core files to change the expiration date of the cookie, but this won't last when there's an update. Maybe there's a function I could write to alter the expiration of this particular cookie?
Any tips? Thanks!

A: That's okay if you don't know the hash. Actually cookie hash is the MD5 of the blog url. If you want to know your site cookie hash then try this:
<?php

    $url="http://www.your-blog.com";
    $COOKIEHASH = md5($url);

    //Now, your cookie will be,
    echo 'wp-postpass_' . $COOKIEHASH; // Name of the cookie of your blog

    //Now, you can delete it whenever you want. :)

    //setting your cookie
    //setcookie('wp-postpass_' . $COOKIEHASH, $password, time() + 864000, COOKIEPATH);
?>

A: Have you tried providing the user a link to wp_logout_url(), instead of programming it for yourself?

A: I ended up doing this:
<?php
// turn all cookies into string
$cookie_string = implode(array_keys($_COOKIE));
// find position of desired cookie
$pos = strpos($cookie_string,'wp-postpass');
// extract string starting at $pos
$pass_cookie = substr($cookie_string,$pos);
// set cookie to expire on browser close
setcookie($pass_cookie,'',0);
?>

This probably isn't the most elegant solution, especially because it requires the wp-postpass cookie to be last in the array.

A: <?php
$pass_cookie='';
foreach($_COOKIE as $key=>$value){
  if(!strncmp($key,"wp-postpass_",12)){
    $pass_cookie = $key;
    break;
  }
}
if($pass_cookie){
  setcookie($pass_cookie,'',0);
}
?>

I would rather use something like the above - it doesn't depend on the position of the wp_postpass cookie


text:
Q: In Scala, how would I model a bank account in a stateless, functional manner? Under an OO paradigm you could have something like
class BankAccount(balance: Double) {
    def deposit(...)
    def withdraw(...)

}

I'm wondering how you do the equivalent in the functional paradigm?

A: Have each method in the BankAccount class return a new BankAccount object with the new balance. That way, the balance can be an immutable variable.
class BankAccount(balance: Double) {
    def deposit(amount: Double): BankAccount
    def withdraw(amount: Double): BankAccount
}

A: Make the account be a series of transactions, not just a current amount:
case class Transaction(numberOfSeashells: Int)
case class Account(transactions: Iterable[Transaction])

def addNewTransaction(startingBalance: Int, t: Transaction) = startingBalance + t.numberOfSeashells
def balance(account: Account) = account.transactions.foldLeft(0)(addNewTransaction)

val acct = Account(List(Transaction(3), Transaction(-1)))
val newBalance = balance(acct)

Result:
scala>   val acct = Account(List(Transaction(3), Transaction(-1)))
acct: Account = Account(List(Transaction(3), Transaction(-1)))

scala>   val newBalance = balance(acct)
newBalance: Int = 2

That way you can remove invalid transactions (chargebacks, etc).


text:
Q: Set checkboxes to checked based on Ajax GET request I'm trying to get the checkboxes checked based on data coming from the server through an ajax get request:

var GetTodos = (function () {
//GET/READ
   return $.ajax({
        url: '/api/Todos/GetTodos',
        contentType: 'application/json',
        success: function (todos) {
            var tbodyEl = $('tbody');
            $.each(todos, function (i, todo) {
                if (!todo.isCompleted)
                    $('#myCheckbox').prop('checked', false);
                else
                    $('#myCheckbox').prop('checked', true);
                tbodyEl.append('\

\
                        <input type="checkbox" value="'+todo.id+'" id="myCheckbox" checked/>	\
                        ' + todo.id + '	\
                        <input type="text" class="name" value="' + todo.text + '">	\
                        \
                            <button id="editBtn" class="btn btn-warning">Update</button>\
                            <button id="deleteBtn" class="btn btn-danger">Delete</button>\
                        	\

\
                ');
            });
        }
    });
});

So i'm sending an ajax get request to get json data and the following response is this

[
  {
    "id": 1,
    "text": "Walk the dog",
    "isCompleted": false
  },
  {
    "id": 4,
    "text": "go out with friends",
    "isCompleted": false
  },
  {
    "id": 5,
    "text": "touch the fishy",
    "isCompleted": true
  }
]

This is what I ended up with

So the checkboxes doesn't get checked properly. If someone can help me out with this it will be much appreciated, thanks.

A: Working fiddle.
First of all id should be unique in same document, so in your case replace id myCheckbox by id myCheckbox[todo.id].
And the checked true and false the both will check the input you should add attribute checked just in case you want to check :
$.each(todos, function (i, todo) {
    var checked = '';

    if (todo.isCompleted)
        checked = 'checked';

    tbodyEl.append('\

\
            <input type="checkbox" value="'+todo.id+'" id="myCheckbox['+todo.id+']" '+checked+'/>	\
            ' + todo.id + '	\
            <input type="text" class="name" value="' + todo.text + '">	\
            \
                <button id="editBtn" class="btn btn-warning">Update</button>\
                <button id="deleteBtn" class="btn btn-danger">Delete</button>\
            	\

\
    ');
});

Hope this helps.

A: you are adding checked attribute to every checkbox hence each checkbox is checked so just add checked attribute to those checkbox only which you need
  $.each(todos, function (i, todo) {
            var checkProp="";
            if (todo.isCompleted)
                checkProp="checked='checked'";

            tbodyEl.append('\

\
                    <input type="checkbox" value="'+todo.id+'" id="myCheckbox" '+checkProp+'/>	\
                    ' + todo.id + '	\
                    <input type="text" class="name" value="' + todo.text + '">	\
                    \
                        <button id="editBtn" class="btn btn-warning">Update</button>\
                        <button id="deleteBtn" class="btn btn-danger">Delete</button>\
                    	\

\
            ');
        });


text:
Q: OVS Flows - Ping working, other traffic not Could someone kindly explain why the following flow config (these flows are the only flows on the bridge) does not work as expected ?
I can ping the hosts on each side, but other traffic (e.g. web/ssh etc. does not pass).
ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 dl_type=0x800,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24,actions=output:76
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.1.0/24,actions=output:73
ovs-ofctl add-flow xl1 arp,nw_dst=10.2.2.0/24,actions=output:76

The traces certainly seem to suggest the traffic should pass:
ovs-appctl ofproto/trace xl1 in_port=73,tcp,nw_src=10.
2.1.1,nw_dst=10.2.2.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=73,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.1.1,nw_dst=10.2.2.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.2.0/24
OpenFlow actions=output:76

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=73,nw_src=10.2.0.0/20,nw_dst=10.2.2.1,nw_frag=no
Datapath actions: 76

ovs-appctl ofproto/trace xl1 in_port=76,tcp,nw_src=10.
2.2.1,nw_dst=10.2.1.1,tcp_dst=22
Bridge: xl1
Flow: tcp,metadata=0,in_port=76,vlan_tci=0x0000,dl_src=00:00:00:00:00:00,dl_dst=00:00:00:00:00:00,nw_src=10.2.2.1,nw_dst=10.2.1.1,nw_tos=0,nw_ecn=0,nw_ttl=0,tp_src=0,tp_dst=22,tcp_flags=0x000
Rule: table=0 cookie=0 ip,nw_src=10.2.0.0/20,nw_dst=10.2.1.0/24
OpenFlow actions=output:73

Final flow: unchanged
Megaflow: skb_priority=0,ip,in_port=76,nw_src=10.2.0.0/20,nw_dst=10.2.1.1,nw_frag=no
Datapath actions: 73

A: One issue is that,
10.2.1.0/24 and 10.2.2.0/24 are not in the same network.
So, if a host, like 10.10.1.1 is looking for 2.0. It may not send out an arp for 2.0. It may send out an arp for its own gateway in the 1.0 network.
You can use this command:

arp -n

on the hosts on 1.0 network to look into the arp table of these hosts.
You can also use:

tcpdump -i "eth-name"

on the openvSwitch to see what you can get if you are sending out a non-icmp packet on 1.0 or 2.0 network.


text:
Q: Not able to concatenate string in python I am trying to concatenate filename strings to cat the names of the files as below.
But somehow the sting is not getting concatenated.  I also tried += operator.
import os
from io import StringIO
ca_cert_file_string = ""
def create_ca_cert_file():
    num1 = os.system("ls ca.crt* | wc -l")
    num =  int (num1)

    concat = StringIO()
    for i in range(0,num):
    str = "ca.crt-%d " %i
    concat.write(str)

    ca_cert_file_string = "cat %s > tls_ca_cert" %concat.getvalue()
    return ca_cert_file_string

str  = create_ca_cert_file()
print str

I get output as 3 where as I want concat.getvalue() to print ca.crt-0 ca.crt1 ca.crt-2 ca.crt-4
599> python test4.py
3
cat  > tls_ca_cert


text:
Q: NodeJS socket.io show data from MySQL realtime I'm working on NodeJS and socket.io.
The current function is working good to display data from mysql database to table.
Now I need the page view auto update/refresh (realtime) if there is a new data received.
Here is the HTML

and index.js
var mysql = require("mysql");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('testsql.html');
  //res.sendfile('/login/');
});
http.listen(3000, function(){
  console.log('listening on *:3000');
});
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "crud_db"
});

io.on('connection', function (socket) {

    console.log('a client connected');

    con.query('SELECT * FROM product',function(err,rows){
      if(err) throw err;
      console.log('Data received from Db:\n');
      console.log(rows);
      socket.emit('showrows', rows);
    });
 });

My question, how to make a realtime function to web page if there is a new data received?

A: I never try it before, but I think you can do something like this
1.first listen an event when there is new submitted data
io.on('connection', function (socket) {
    socket.on('new data', function (data) {
       socket.emit('broadcast', data) // send it to the client
    })
})

2.store the io instance to app.locals:
app.locals.io = io

3.then, consider you have an endpoint to create a new data:
app.post('/product', function (req, res) {
    const sql = `INSERT INTO products (name, price) VALUES (${req.body.name},
    ${req.body.price})`

    con.query(sql, function (err, result) {
        if (err) throw err;
        const io = req.app.locals.io
        io.emit('new data', { data: result })
    })
})


text:
Q: VirtualBox Drive Resize I am trying to increase a dynamically allocated drive
in VirtualBox.
Environment:
Windows 10 guest on a Pop!_OS (Ubuntu derivative) host. VirtualBox 6.0. Windows guest configured with a 50 GB dynamic drive.  Trying to increase to 100 GB.  I have over 500 GB available on the host.
Command: VBoxManage modifyhd "/home/happycoffeebean/Windows/Windows.vdi" --resize 102400
(Also tried VBoxManage modifyhd --resize 102400 /home/happycoffeebean/Windows/Windows.vdi")
Result:
happycoffeebean@pop-os:~$ VBoxManage modifyhd --resize 102400 "/home/happycoffeebean/Windows/Windows.vdi"
0%...
Progress state: VBOX_E_NOT_SUPPORTED
VBoxManage: error: Failed to resize medium
VBoxManage: error: Resizing to new size 107374182400 is not yet supported for medium '/home/happycoffeebean/Windows/Windows.vdi'
VBoxManage: error: Details: code VBOX_E_NOT_SUPPORTED (0x80bb0009), component MediumWrap, interface IMedium
VBoxManage: error: Context: "RTEXITCODE handleModifyMedium(HandlerArg*)" at line 768 of file VBoxManageDisk.cpp

What I've tried:

*

*Verified that 102400 MB == 102 GB.

*Calculated 107374182400 MB is over a petabyte.  Correct number (107 GB) if calculated from bytes. Unclear on this inconsistency.

*Googled the errors, only came up with answers pertaining to people trying to decrease disk space and / or using fixed allocation configs.

*Googled the petabyte number, found a Russian forum with no answer.

*Slept on it, left it for a day or two. Same result.  Left it for another day.  Still nothing.

Response to freddy:
Output of
VBoxManage showmediuminfo /home/happycoffeebean/Windows/Windows.vdi:
UUID:           7921c7ce-fee5-4667-aab1-bc34fc62b079
Parent UUID:    base
State:          locked read
Type:           normal (base)
Location:       /home/happycoffeebean/Windows/Windows.vdi
Storage format: VDI
Format variant: fixed default
Capacity:       51200 MBytes
Size on disk:   51202 MBytes
Encryption:     disabled
In use by VMs:  Windows (UUID: 23e44ce0-e866-4a55-9452-45e407cf693d) [Base Windows Install (UUID: aaadd1bb-c95b-4a2c-91b8-67e7f530ab17)]
Child UUIDs:    e7620931-e60d-421c-894b-b820644e8134

Screenshot of VBox control center:

A: I don't know why the gui reports something different and why the disk is full to its maximum.
You have enough disk space, try to clone and resize the disk as in bu5hman's comment:

*

*Clone the disk:
VBoxManage clonemedium /home/happycoffeebean/Windows/Windows.vdi /home/happycoffeebean/Windows/winclone.vdi

*Optional check. The clone should have type dynamic default now:
VBoxManage showmediuminfo /home/happycoffeebean/Windows/winclone.vdi

*Resize the clone:
VBoxManage modifymedium /home/happycoffeebean/Windows/winclone.vdi --resize 102400

*Resize the guest partition(s):

*

*Swap the disk images in your guest.

*Insert an ISO image of your favourite partition manager (maybe gparted) into the virtual CD/DVD drive, start the guest and resize the Windows partition(s).

*Delete the old disk image.


text:
Q: xcode - with multiple test targets what does the scheme test do Im uncertain what the schema test does when clicking on edit schema.  My project has multiple test targets.  I have tried checking them  off in the schema but  unchecking them affects nothing. My question is what does the test schema menu really do ??
Here is an image how to get to the schema menu:

and here is the actual menu im having difficulty to understand its purpose:

A: This changes which tests are run when selecting Product -> Test (or cmd + U) for the given scheme.


text:
Q: Error while installing mysql-server-5.1 I need to install mysql-server-5.1 on ubuntu 11.10. While installing with apt-get I am getting
dpkg: error processing mysql-server-5.1 (--configure): subprocess installed post-installation script returned error exit status 1

I have tried following things:
sudo apt-get purge mysql-common

rebboting the machine and again trying to install mysql by running sudo apt-get
install mysql-server-5.1 but no success. Still I am getting the similar error.
In SYSLOG I am getting following lines:
Dec 11 20:26:02 ubuntu mysqld[11272]: 111211 20:26:02  InnoDB: Shutdown completed; log sequence number 0 145554
Dec 11 20:26:02 ubuntu mysqld[11272]: 111211 20:26:02 [Note] /usr/sbin/mysqld: Shutdown complete
Dec 11 20:26:02 ubuntu mysqld[11272]:
Dec 11 20:26:02 ubuntu mysqld[11291]: 111211 20:26:02 [Note] Plugin 'FEDERATED' is disabled.
Dec 11 20:26:02 ubuntu mysqld[11291]: 111211 20:26:02  InnoDB: Initializing buffer pool, size = 8.0M
Dec 11 20:26:02 ubuntu mysqld[11291]: 111211 20:26:02  InnoDB: Completed initialization of buffer pool
Dec 11 20:26:02 ubuntu mysqld[11291]: 111211 20:26:02  InnoDB: Started; log sequence number 0 145554
Dec 11 20:26:02 ubuntu mysqld[11291]: 111211 20:26:02  InnoDB: Starting shutdown...
Dec 11 20:26:08 ubuntu mysqld[11291]: 111211 20:26:08  InnoDB: Shutdown completed; log sequence number 0 145554
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08 [Note] Plugin 'FEDERATED' is disabled.
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08  InnoDB: Initializing buffer pool, size = 8.0M
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08  InnoDB: Completed initialization of buffer pool
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08  InnoDB: Started; log sequence number 0 145554
Dec 11 20:26:08 ubuntu mysqld[11306]: ERROR: 1050  Table 'plugin' already exists
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08 [ERROR] Aborting
Dec 11 20:26:08 ubuntu mysqld[11306]:
Dec 11 20:26:08 ubuntu mysqld[11306]: 111211 20:26:08  InnoDB: Starting shutdown...
Dec 11 20:26:13 ubuntu mysqld[11306]: 111211 20:26:13  InnoDB: Shutdown completed; log sequence number 0 145554
Dec 11 20:26:13 ubuntu mysqld[11306]: 111211 20:26:13 [Note] /usr/sbin/mysqld: Shutdown complete
Dec 11 20:26:13 ubuntu mysqld[11306]:

Let me know how to solve this issue.

A: sudo apt-get remove mysql-server-5.1
sudo apt-get purge mysql-common
sudo apt-get purge mysql-server-5.1
sudo apt-get autoremove
sudo apt-get clean

*

*Install mysql-common first
sudo apt-get install mysql-common

*Install the rest of mysql
sudo apt-get install mysql-server

Borrowed from the Ubuntu Forums here.
Please let me know if this helps!

A: Following the steps above, I got the same error. When I tried again, I followed the following procedure and it worked. Note that the only difference is that I installed mysql-server-5.1 before mysql-server:
sudo apt-get remove mysql-server-5.1
sudo apt-get purge mysql-common
sudo apt-get purge mysql-server-5.1
sudo apt-get autoremove
sudo apt-get clean

Install mysql-common first
sudo apt-get install mysql-common

Install mysql-server-5.1 next
sudo apt-get install mysql-server-5.1

Install the rest of mysql
sudo apt-get install mysql-server


text:
Q: add or remove class based on value of PHP variable using jquery I have a profile page on which I show details about the author of site. Site have different authors and moderators. Profile Page has three social media buttons which have links to social media accounts of the author of the site. I fetch social media links from SQL database using PHP. Php is working fine. I want if no link to any social media account, then add hidden class to that social media button using Jquery.
I tried this but not working.

$(document).ready(function() {
  var facecook = '<?php echo $facebook; ?>';
  if (facebook < 0) {
    $('.facebook').addClass('hidden')
  };
  var google = '<?php echo $google; ?>';
  if (google > 0) {
    $('.google').removeClass('hidden')
  }
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    <?php echo $facebook; ?>

    <?php echo $twitter; ?>

    <?php echo $google; ?>

A: Try this script. Typo error in your code.
var facecook = '<?php echo $facebook; ?>'; to var facebook = '<?php echo $facebook; ?>';
facebook not facecook
$(document).ready(function() {
  var facebook = '<?php echo $facebook; ?>';

  if (facebook=='') {
    $('.facebook').addClass('hidden')
  };
  var google = '<?php echo $google; ?>';
  if (google == '') {
    $('.google').removeClass('hidden')
  }
});


text:
Q: How to change value of an object with keyup? Here is the frontend, so when a user key in couple of value, the submit button will insert the value into an object.

Here we already got our object like this
0: {name: "a", club: "b"}
1: {name: "c", club: "d"}

How can I change 'name'/'club' value from 'a' to any value that I typed in the input with keyup?
Here's the code

var player = [];

function insertData() {
  var name = document.querySelector('input[name="name"]').value;
  var club = document.querySelector('input[name="club"]').value;
  player.push({
    name,
    club
  });
  onSetDisplay();
}

function onSetDisplay() {
  document.querySelector('.display').innerHTML = "";

  for (i = 0; i < player.length; i++) {
    var wrapper = onCreateElement('div', null, i);
    var input1 = onCreateElement('input', player[i].name);
    var input2 = onCreateElement('input', player[i].club);

    wrapper.appendChild(input1);
    wrapper.appendChild(input2);

    var deleteBtn = onCreateElement('button', '', "Delete", function () {
      // console.log(this.parentNode)
      player.splice(this.parentNode.getAttribute('data-index'), 1);
      this.parentNode.remove();
    });

    wrapper.appendChild(deleteBtn);

    document.querySelector('.display').appendChild(wrapper);
  }

}

function onCreateElement(element, value, text, ev) {
  var e = document.createElement(element);

  if (element == 'input') {
    e.value = value;
    e.type = 'textfield';
    e.setAttribute('onkeyup', 'editData()');
    e.id = "playerlist";
  } else {
    e.setAttribute('data-index', text)
    e.innerHTML = text;
  }

  if (typeof ev == 'function') {
    e.addEventListener('click', ev);
  }

  return e;
}
<input type="text" name="name"></input>
<input type="text" name="club"></input>

<input type="button" value="Submit" onclick="insertData();"></input>

A: It's missing the implementation of editData() function, I modified your JS, please have a look below, I hope it will meet to your expectation,
var player = [];

function insertData() {
  var name = document.querySelector('input[name="name"]').value;
  var club = document.querySelector('input[name="club"]').value;
  player.push({
    name,
    club
  });
  onSetDisplay();
}

function onSetDisplay() {
  document.querySelector('.display').innerHTML = "";

  for (i = 0; i < player.length; i++) {
    var wrapper = onCreateElement('div', null, i);
    var input1 = onCreateElement('input', player[i].name, '', 'name_'+i, i);
    var input2 = onCreateElement('input', player[i].club, '', 'club_'+i, i);

    wrapper.appendChild(input1);
    wrapper.appendChild(input2);

    var deleteBtn = onCreateElement('button', '', "Delete", "", "", function() {
      // console.log(this.parentNode)
      player.splice(this.parentNode.getAttribute('data-index'), 1);
      this.parentNode.remove();
    });

    wrapper.appendChild(deleteBtn);

    document.querySelector('.display').appendChild(wrapper);
  }

}

function onCreateElement(element, value, text, id, index, ev) {
  var e = document.createElement(element);

  if (element == 'input') {
    e.value = value;
    e.type = 'textfield';
    e.setAttribute('onkeyup', 'editData('+id+')');
    e.id = id;
  } else {
    e.setAttribute('data-index', text)
    e.innerHTML = text;
  }

  if (typeof ev == 'function') {
    e.addEventListener('click', ev);
  }

  return e;
}

// added this editData method,
function editData(id) {
    console.log("id: ", id.id, id.value);
}

Check Below Attached Screenshot with result.


text:
Q: Referencing a Range object set by Range.Row() generates Error 1004 "Application-defined or object-defined error" I've created a range object by setting it from another range object's Rows().  When I reference the newly created range by row and column, it generates error 1004.
I can reference the original range by row and column.  I've included checks to make sure the rng object points to the same range as the dataset object.  When I inspect the rng object, the Value2 shows a single row of data.
Below is the minimum code I'm using that generates the error.
Private Sub TestRangeObject()

Dim i As Long
Dim dataset As Range
Dim rng As Range

    Set dataset = sRoster.Range("B18:E37")

    For i = 1 To dataset.Rows.Count

        Set rng = dataset.Rows(i)

        Debug.Print "Rng is Range Obj: " & (TypeOf rng Is Range)
        Debug.Print "Same worksheet: " & (rng.Parent.CodeName = dataset.Parent.CodeName)
        Debug.Print "Same address: " & (dataset.Rows(i).Address = rng.Address)

        'can reference dataset object by row and column
        Debug.Print "First column (dataset): " & dataset(i, 1).Address

        'error when referencing rng object by row and column
        Debug.Print "First column (rng): " & rng(1, 1).Address

    Next i

End Sub

A: As additional detail: there's a difference between using Rows(somerow) and Range(somerange).
This can be validated with a simple example:
Sub Test()
    Dim rng As Range
    Set rng = Sheet1.Range("1:1")
    Debug.Print rng(1, 1).Address ' returns $A$1

    Dim rng2 As Range
    Set rng2 = Sheet1.Rows(1)
    Debug.Print rng2(1).Address ' succeeds, returns $1:$1
    Debug.Print rng2(1, 1).Address ' fails
End Sub

The solution - to use Rows(myRow).Cells - has already been proposed.
EDIT:
In an attempt to capture and summarize some of the back and forth from comments, a Row, whether it's Range.Rows(somerow) or Sheet.Rows(somerow), refers to a unit as a row, not as individual cells.
For example, Range("A1:E10").Rows would refer to 10 rows, not 50 cells.
In the same way, Sheet1.Rows(1) refers to 1 row, not 16384 cells. The row is the "smallest unit of consideration," for lack of a better term. One row can't have a column index - it's just one row, not a collection of all the cells that make up that row, which each have their own column index.
So you'll need to use Cells if you specifically want to index the cells in a certain row.

A: You can't use:
rng(1, 1)

if rng is a single row range:
Sub jksfhsa()
    Dim sRoster As Worksheet, dataset As Range, rng As Range
    Set sRoster = Sheets("Sheet1")
    Set dataset = sRoster.Range("B18:E37")
    Set rng = dataset.Rows(1)

    MsgBox dataset.Address
    MsgBox dataset(1, 1).Address

    MsgBox rng.Address
    MsgBox rng(1, 1).Address

    End Sub

The last MsgBox will fail.
However:
Sub jksfhsa()
    Dim sRoster As Worksheet, dataset As Range, rng As Range
    Set sRoster = Sheets("Sheet1")
    Set dataset = sRoster.Range("B18:E37")
    Set rng = dataset.Rows(1).Cells

    MsgBox dataset.Address
    MsgBox dataset(1, 1).Address

    MsgBox rng.Address
    MsgBox rng(1, 1).Address

    End Sub

will work just fine.  So in your code replace:
Set rng = dataset.Rows(i)

with:
Set rng = dataset.Rows(i).Cells


text:
Q: unable to telnet 139 port after changing IP on ubuntu 18.04 I am using ubuntu 18.04, now we are changed new ip series in this system and windows server also, then after unable to telnet 139, they show connection refuse. When we set old ip it's working fine.
any idea why this happening.
Thanks


text:
Q: edit message sent in last step in wizard | telegraf-js How can I edit the message sent in the getMessage function at sendToAdmin function?

*

*telegraf-js v4.4.1

*typescript

async function getMessage(ctx: Context) {
  // message
  await ctx.editMessageText("text");

  return (<any>ctx).wizard.next();
}

async function sendToAdmin(ctx: Context) {

  // edit here

  return (<any>ctx).wizard.leave();
}

const superWizard = new Scenes.WizardScene(
  getMessage,
  sendToAdmin
);

A: you can use Context.wizard.state

const bot = new Telegraf(process.env.TOKEN);

async function getMessage(ctx: Context) {

  // message have message id
  const message = await ctx.editMessageText("text");

  // send message id to wizard
  // for use in next step
  (<any>ctx).wizard.state.message = { message: message.message_id };

  return (<any>ctx).wizard.next();
}

async function sendToAdmin(ctx: Context) {

  // use here
  const lastMessageID = (<any>ctx).wizard.state.message.message;

  // edit last message
  bit.telegram.editMessageText(ctx.from.id, lastMessageID, "EDIT_TEXT")

  return (<any>ctx).wizard.leave();
}


text:
Q: How do I create a distinct count of every duplicate values in Cognos Report Studio? These are my current data
ACCOUNT NUMBER     PRODUCT          STATUS   RANK   DESIGN

    1  530033   Wealth Services     Closed    1     Manual
    2  530033   Wealth Services     Closed    2     Manual
    3  530033   Wealth Services     Closed    3     Manual
    4  530033   Wealth Services     Closed    4     Manual
    5  534656   Initial Escrow      Open      1     Manual
    6  534656   Initial Escrow      Open      2     Manual
    7  535161   Markets Integrity   Closed    1     Manual
    8  538379   Prepaid Cards       Closed    1     Manual
    9  538379   Prepaid Cards       Closed    2     Manual
    10 538379   Prepaid Cards       Closed    3     Manual
    11 538379   Prepaid Cards       Closed    4     Manual
    12 538915   Uploaded Cards      Open      1     Manual
    13 538915   Uploaded Cards      Open      2     Manual
    14 538915   Uploaded Cards      Open      3     Manual

I would like to create a column that would uniquely count every duplicate ACCOUNT NUMBER. For example Account number 530033 appeared four times, I would like to count every 530033 as one, same with the other account number 534656 appeared twice is till be counted as one.
I've already tried the following but none of these work.
count(distinct(Account Number))
count(distinct(Account Number) for Account Number)

with Aggregate columns equals to TOTAL, COUNT or AUTOMATIC.
I will use the data to create a cross-tab. My cross-tab gives me a a TOTAL count of 14 because it counts all duplicate account numbers. Because all account number have fourteen rows. But in reality there's only 5 account numbers (530033, 534656, 535161, 538379 and 53891)
                     TOTAL    Open         Closed
Wealth Services        4                       4
Initial Escrow         2         2
Markets Integrity      1                       1
Prepaid Cards          4                       4
Uploaded Cards         3         3
    TOTAL              14

Ideally it should be like this.
                    TOTAL    Open         Closed
Wealth Services        1                       1
Initial Escrow         1         1
Markets Integrity      1                       1
Prepaid Cards          1                       1
Uploaded Cards         1         1
    TOTAL              5

Should I create a new column named Unique count of account numbers? but how do I count the account number individually?
Do I have to create another table with unique account numbers then inner join both tables?

A: I believe the expressions you need are the following:
TOTAL
COUNT(DISTINCT [ACCOUNT NUMBER] for [PRODUCT])

Open
CASE [STATUS]
WHEN 'Open' THEN COUNT(DISTINCT [ACCOUNT NUMBER] for [PRODUCT],[STATUS])
ELSE NULL
END

Closed
CASE [STATUS]
WHEN 'Closed' THEN COUNT(DISTINCT [ACCOUNT NUMBER] for [PRODUCT],[STATUS])
ELSE NULL
END

Make sure you set the Aggregate Function for each data item to 'Calculated' since we are manually specifying the aggregate and rollup.


text:
Q: What status code to use when certifying an upload? I'm working on a direct-to-S3 upload service that operates in two parts described below.  This service would not be used by browsers, but would be a RESTful API used by other software clients.

*

*Make a request to an endpoint which certifies and validates the upload, returning an upload URL if all's well.

*Make a PUT request to the URL returned from #1 to actually do the upload to S3.

How should the server structure the response for the first endpoint?
The first option I am considering would be to use GET and return a status code 302 with a Content-Location header containing the URL to upload to.  However, the intent behind the redirect descriptions in the spec seems to be focussed on redirecting after a form submission.
The other option I'm considering is to use POST for the first endpoint and returning a Location header with the URL, as described here:

If a resource has been created on the origin server, the response
  SHOULD be 201 (Created) and contain an entity which describes the
  status of the request and refers to the new resource, and a Location
  header. RFC 2616 #9.5

Please advise on what other people have used in such circumstances?

A: I think it mainly depends on whether your API itself will have a resource referencing the uploaded file or not. The only one with knowledge of the uploaded file is the S3 itself or your API has something referencing it?
If the first case where only S3 knows about it, then it's OK to use the GET if it acts merely as a generator for the upload parameters, including the URI.
If the second case, then it shouldn't be a GET, since you're changing something on your side. Yes, you should make a POST, but the Location header should be used to return the URI for the created resource that references the uploaded file. That resource may have the upload URI and it could act like a state-machine, tracking if the file is uploaded or not. To avoid the need for clients to GET that resource before being able to upload, you may return the upload URI in the Link header, with a rel reflecting that purpose.


text:
Q: How to make the definition of the constructor outside the header file? I have this constructor in the header file:
class Fan {
  Id id;
  string name;
  Age age;
public:
  Fan(Id id, string name, Age age);
};

And this definition in the .cpp
Fan::Fan(Id id, string name="someone", Age age=0) : id(id), name(name),
  age(age), status(disconnected)
{
  if(id<0 || age<0) {
    throw BadParams();
  }
}

I have this notes: (mtm is the namespace)
..\Fan.h:60:2: note: mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)
..\Fan.h:60:2: note:   candidate expects 3 arguments, 2 provided
..\Fan.h:47:7: note: mtm::Fan::Fan(const mtm::Fan&)
..\Fan.h:47:7: note:   candidate expects 1 argument, 2 provided

I tried to inline before the both the declaration and the definition and get this errors:
..\Fan.h:60:9: note: mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)
..\Fan.h:60:9: note:   candidate expects 3 arguments, 2 provided
..\Fan.h:47:7: note: mtm::Fan::Fan(const mtm::Fan&)
..\Fan.h:47:7: note:   candidate expects 1 argument, 2 provided
..\Fan.h:60:9: warning: inline function 'mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)' used but never defined [enabled by default]

A: You have to put the default arguments in the declaration (i.e. in the .h file), not in the .cpp file.
i.e.:
class Fan {
public:
   Fan(Id id, string name="someone", Age age=0);
};


text:
Q: Yii2 basic use Zend Framework 1 library I have successfully using Zend Framework 1 library in CodeIgniter
This is how I do it

*

*copy the folder Zend in Zend framework's path/library

*paste in CodeIgniter's system/libraries

*in CodeIgniter's system/libraries, add Zend.php with this content
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Zend {
  function __construct($class = NULL) {
  // include path for Zend Framework
  // alter it accordingly if you have put the 'Zend' folder elsewhere

  ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . FCPATH . 'system/libraries');
    if ($class) {
      require_once (string) $class . EXT;
      log_message('debug', "Zend Class $class Loaded");
    } else {
      log_message('debug', "Zend Class Initialized");
    }
  }

  function load($class) {
    require_once (string) $class . EXT;
    log_message('debug', "Zend Class $class Loaded");
  }
}

*This is example how I use it in CodeIgniter's controller
//load it inside function __construct()
$this->load->library('Zend');
$this->zend->load('Zend/Feed');
$this->zend->load('Zend/Search/Lucene');

//use it inside function
$index = new Zend_Search_Lucene( "assets/index" );
query = "yes";
$hits = $index->find($query);

Now, I want to use Zend Framework 1 library in Yii2 basic
I have copied the folder Zend in Zend framework's path/library
Pasted it to Yii2 basic path/vendor folder
How to set and use Zend Framework 1 library in Yii2 basic?
Brief explanation appreciated! Thanks before


text:
Q: Mouse click and hold event? Does anyone have an idea how to handle a mouse click and hold event  in VB.NET?
Suppose I want to click and hold in a button and do some stuff behind the code like change the button BackColor or close a window faster( just like when you click in the ms office 2013 file menu then use a left-arrow to close that menu).
Hope you know what I mean
Thank you

A: You could create a timer that is defined globally that begins when MouseDown is called, then ends on Mouse Up. You can then set a condition on how many milliseconds need to pass before you deem it a 'long click'. See example code below:
Public Class Form1
Dim WithEvents timer As New Timer
Dim milliseconds As Integer

Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown
    timer.Start()
End Sub

Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles MyBase.MouseUp
    timer.Stop()
    Label1.Text = "Button held down for: " & milliseconds & " milliseconds"
    If milliseconds >= 10 then 'Mouse has been down for one second
      DoSomething()
    End If
End Sub

Private Sub EggTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer.Tick
    milliseconds += 1
End Sub

End Class

A: MouseDown is what you are looking for


text:
Q: Can I avoid using global variables in python while coding a bot with discord.py? I'm working on my first programming project, a discord bot, using discord.py. I wanted to add a minigame with a dice, but for that I used global variables. I understood that it's recommended not to use them and I was wondering, is there a way I can do the same thing without using global variables?
This is my code:
dice_list = ['1', '2', '3', '4', '5', '6']
roll_1 = ''
roll_2 = ''
player_1 = ''
player_2 = ''
@client.command()
async def dice(ctx):
    global roll_1
    global roll_2
    global player_1
    global player_2
    if roll_1 == '':
        roll_1 = random.choice(dice_list)
        player_1 = ctx.message.author
        await ctx.send(f'{ctx.message.author.mention} rolled **{roll_1}**!')
    else:
        if ctx.message.author != player_1:
            roll_2 = random.choice(dice_list)
            player_2 = ctx.message.author
            await ctx.send(f'{ctx.message.author.mention} rolled **{roll_2}**!')
        else:
            await ctx.send(f'You already rolled {roll_1}, wait for someone to play with you.')
        if roll_1 > roll_2 and player_2 != '':
            await ctx.send(f'{player_1} won!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''
        elif roll_2 > roll_1 and player_2 != '':
            await ctx.send(f'{player_2} won!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''
        elif player_2 != '':
            await ctx.send('Tie!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''

A: You can set attributes of your bot.
client.roll_1 = "..."

These are available everywhere you have your client object.
If you want to use the variable elsewhere, of course it would be best if you declare a standard value at the beginning of you code, but you can also check if the attribute exists
if hasattr(client, "roll_1"):
    # work with client.roll_1
else:
    # roll_1 wasn't defined yet

I hope I could help


text:
Q: Java Service Layer Method - Primary Key or Hibernate Entity Arguments? Which is more idiomatic if using Spring Boot? If using Java (Spring Boot), imagine there is one method in the service: updateCompanyName
Which is the more idiomatic method signature in the SERVICE LAYER of Spring Boot app:
......
updateCompanyName(Company company, String newName);
-or-
updateCompanyName(Long companyID, String newName);
......
In other words, should the controller hydrate the object from a DAO and pass a hibernate entity into a service layer, or should the service layer expect the primary key and hydrate the entity from hibernate?

A: In general, in a Layered architecture, the Controller (from the Presentation layer) extracts the data (i.e. companyID) from the input (i.e. request body) and calls an Application service by passing this data.
The Application service loads the Aggregate from the Repository, calls the appropriate method on it and then persists the Aggregate back to the Repository. This Application service show be thin, with no Business logic (which belongs in the Aggregate).
So, in your case, the answer is: the Controller calls updateCompanyName(Long companyID, String newName); on the Application service.


text:
Q: Redirect to other controller when click Tab Bar item I have a Tab Bar that connect to 2 TableView, said that Tab1 go to Test1TableController, and Tab2 go to Test2TableController, what I want when I click Tab2, it check session first and If the session doesn't exists it will go to other controller before go to Test2TableController but my code can't do that
This is my code:
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {

    if(self.tabBarController?.selectedIndex == 1) {
        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
        if (isLoggedIn != 1) {
            let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
            let destination = storyboard.instantiateViewControllerWithIdentifier("LoginController") as! LoginController
            navigationController?.pushViewController(destination, animated: true)
        }
    }

}

please help me how to do that ? I have search for several web but can't find like what I want.
Just give me some hint. Thanks


text:
Q: Fitting html list to parent element height Alright, well describing this problem is very simple.
http://gflclan.com/gamemann/screenshots/Screenshot_09-15-14-17-06-10.png
I want that black hover color to fit the height of the divider. I know there have been questions asked about this before but I tried their solutions and it just isn't working.
Here's my CSS code:
#navbar {
    text-align: center;
    margin-left: 20%;
    margin-right: 20%;
    background-image: url('navbg.png');
    border-radius:15px 15px 0px 0px;
    padding:1px 1px 1px 1px;
    box-shadow: 5px 5px 10px #121212;
    height: auto;
}

#navbar ul {
    list-style-type: none;
}

#navbar ul li {
    font-size: 150%;
    font-weight: 300;
    margin-left: 30px;
    vertical-align: middle;
    display: inline-block;
}

#navbar ul li a {
    text-decoration:none;
}

#navbar li:hover{
    background-color: black;
}

This may be an easy fix, but I cannot figure it out.
Any help would be appreciated.
EDIT:
HTML Code:

Home

GFL

Forums

Thanks,
Roy (Gamemann)

A: You can use this:
css
#navbar {
    text-align: center;
    margin-left: 20%;
    margin-right: 20%;
    background-image: url('navbg.png');
    border-radius:15px 15px 0px 0px;
    padding:1px 1px 1px 1px;
    box-shadow: 5px 5px 10px #121212;
    height: auto;
}
#navbar ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
#navbar ul li {
    font-size: 150%;
    font-weight: 300;
    margin-left: 30px;
    vertical-align: middle;
    display: table-cell;
    height: 75px;
    width: 1%;
}
#navbar ul li a {
    text-decoration:none;
}
#navbar li:hover {
    background-color: black;
}

fiddle


text:
Q: Strictly nondecreasing permutations of numbers Suppose I have a 6 digit lock that accepts 0-9 as inputs for the 6 slots.
And I was told that the numbers in order from left to right are never less than the number to their left.
so 0,0,0,0,0,0 would be valid but 0,1,2,3,2,9 would not.
I tried to brute force it by looking for a pattern in increasing the number of slots on the lock.
If it allowed a single digit, 10 passwords.
if it allowed 2 digits, 55 passwords (I think)
10 that start with 0,
9 that start with 1,
8 that start with 2,
ect.
10+9+8+...+3+2+1=55
3 gets a lot bigger, 100 that start with 0, then 9 that start with "1,1" 8 that start with "1,2" but from there I get lost with my counting and its going to be a huge nightmare when I get up to 6.
Please tell me there is a better way!
Thank you.

A: This is a "stars and bars" problem.  If you know how many examples of each digit appear in your number, the non-decreasing condition forces a unique solution.  So you need to know how many solutions there are to:
$$\sum_{k=0}^9 x_k=n,$$
where $x_k$ is the number of times the digit $k$ appears in your number, and $n$ is the length of your number.  That number is $\binom{n+9}{9}$.


text:
Q: Open Outlook to send a webpage by email I would like to send a webpage to Outlook from Java but without initially specifying the person to whom I am sending it too. In short, I would like to implement Internet Explorer's functionality of sending a web page by email. I currently can't figure this out.
This is what I have tried but it's not working, it gives the error :

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalArgumentException: URI scheme is not "mailto"

This is my code :
File htmlFile = new File("http://stackoverflow.com/questions/ask");

try {
    Desktop.getDesktop().mail( htmlFile.toURI() );
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

A: You are getting this error because you are specifying web page URI which is "http" and not "mailto" which is expected. Check the documentation, you could use utility method.
So, to send email use something like this:
    String subject = URLEncoder.encode("Test subject").replace("+", "%20");
    String body = URLEncoder.encode("Test body").replace("+", "%20");
    Desktop.getDesktop().browse(new URI("mailto:?subject="+subject+"&body="+body));

Or this (if mail() is preffered):
Desktop.getDesktop().mail(new URI("mailto:?subject="+subject+"&body="+body));

This will set subject and body without recipient. Also mail client might be Outlook, but depends of system settings (what is set for default mail client).
If you would like to send webpage in content of mail, you should first read it, if you would like to send just URL address, then encode it and send in body.


text:
Q: Smarty Foreach Columns I am converting a Regular Template to Responsive One. I have some trouble at generating columns.
My Code which is not working correctly

    {foreach name=aussen item=module_data from=$module_content}
    {php} $col++; {/php}

Heading

Text

View details »

    {php} if ($col>=4) {$col=0;echo '';}{/php}
    {/foreach}

The Responsive Theme has this structure

Heading

Text

Button »

Heading

Text

Button »

Heading

Text

Button »

Heading

Text

Button »

Heading

Text

Button »

Heading

Text

Button »

How can I rewrite My Code to generate a Row with the Class "row-fluid" each time if each Row has reached maximum give columens of 3, 4 or 5?

A: You can find out which iteration of a {foreach} loop you are in using the iteration and index properties as described in the Smarty 3 manual (or the equivalent page for Smarty 2).
In this case, you want to do something different "every 4 iterations", so you can use Smarty's is even by 4 construct. Your foreach loop has a name of aussen, so the variable to test is $smarty.foreach.aussen.iteration.
Alternatively, you can use your existing {$col} variable (although see my comment above about not using {php} tags): if the column number is zero, open a container div to start a new row; if it is 4, close the container div to mark the row's end. This approach will also require you to spot if you are on the last row of the loop, in case it is not divisible by 4, so you always close the row: {if $col==4 or $smarty.foreach.aussen.last}
{/if}.


text:
Q: How to grant all privileges to a new user in Debian I just created a new user on my Debian server, but I noticed that it hasn't all privileges to write in specific folders. So, I executed the command chown -R newuser:newuser / and it worked again.
But my question is: Is it secure to solve with this way? If not, how can I solve it?
Thanks for the reply :)

A: Definitely not secure.
I suggest you learn how Access Control Lists work, apart from the special permissions. Mainly the getfacl & setfacl commands.
Access Control Lists
Special Permissions in Linux

A: Nooo, if you ran that as root (or sudo) you just basically ruined the whole filesystem permission structure. You should probably reinstall or find a way to recreate the original set of permissions.
You might want to read more about the permissions in Unix. You have a separate set of permissions for the owner, a group, and everybody else. And then you have extended attributes.
Also, you can get new privileges for some time, using sudo.


text:
Q: Avalonia: Is there a way embed Process' Window on Linux Hello as you know the VLCPlayer not supporting RTSP stream on debian bullseye and pardus21 anymore.
I'm searching a way put native window to Control on Linux for Avalonia.
On windows it's so easy.
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, int X, int Y, int cx, int cy, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
...
if (ffProcess.MainWindowHandle != IntPtr.Zero) {
  SetParent(ffProcess.MainWindowHandle, ctrl.Handle);
  MoveWindow(ffProcess.MainWindowHandle, 0, 0, ctrl.Width, ctrl.Height, true);
}

is there a way embedding process' window for Linux?


text:
Q: How do you return values from javascript functions I'm using the js library in Dart to access OpenLayers. Pertinent code looks like:
js.scoped(() {
  ol = js.retain(js.context.OpenLayers);
  var max_extent = new js.Proxy(ol.Bounds, -13652354.432172, 6026153.418145, -13574082.915218, 6065289.1766216);
  var restricted_extent = max_extent;

  if (controls == null){

    var options = js.map ({
      'maxExtent': max_extent,
      'restrictedExtent' : restricted_extent,
      'units' : 'm',
      'projection': new js.Proxy(ol.Projection, 'EPSG:900913'),
      'displayProjection' : new js.Proxy(ol.Projection, 'EPSG:4326'),
      'controls' : js.array([ new js.Proxy(ol.Control.Attribution),
                              new js.Proxy(ol.Control.Navigation),
                              new js.Proxy(ol.Control.ArgParser),
                              new js.Proxy(ol.Control.PanPanel),
                              new js.Proxy(ol.Control.ZoomPanel)
                             ])
    });
    _treemap = js.retain( new js.Proxy( ol.Map, map_div_id, options ) );
  }

  var roads = new MapLayer(ol, layer_type:'road').layer;
  var aerial = new MapLayer(ol, layer_type:'hybrid').layer;

  _treemap.addLayers(js.array([roads, aerial]));
  _treemap.setBaseLayer(roads);
  _treemap.zoomToMaxExtent();
  var result = _treemap.layers();
});

All works as expected except for the last line. _treemap.layers() is supposed to return an array of OpenLayer.Layer. When that line executes I get an error:

Exception: TypeError: Object [object Array] has no method 'apply'

So, what is the correct way to get/handle return values from javascript functions in my Dart code?

A: layers is an array (see OpenLayers.Map.layers). So you should use :
var result = _treemap.layers;

With _treemap.layers() you was trying to call layers as it was a function.
One side note on your code : when you use js.map({}) you don't need to use js.array or js.map in the object tree. You can simply give a JSON-like structure.
var options = js.map ({
  'maxExtent': max_extent,
  'restrictedExtent' : restricted_extent,
  'units' : 'm',
  'projection': new js.Proxy(ol.Projection, 'EPSG:900913'),
  'displayProjection' : new js.Proxy(ol.Projection, 'EPSG:4326'),
  'controls' : [ new js.Proxy(ol.Control.Attribution),
                 new js.Proxy(ol.Control.Navigation),
                 new js.Proxy(ol.Control.ArgParser),
                 new js.Proxy(ol.Control.PanPanel),
                 new js.Proxy(ol.Control.ZoomPanel)
               ])
});


text:
Q: Set first screen as current item on launcher when user presses home? I'm building a launcher/home screen replacement app and I've noticed all launchers allow the user to press home to go to the first screen of the launcher. So it's obviously possible to listen to the home key for home replacement apps but I haven't been able to figure out how.
How can I listen to the home key and trigger setCurrentItem(0) when the user presses home while inside my launcher?
EDIT
I have two options until now:
@Override
public void onPause() {
    super.onPause();

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    if(!this.isFinishing())
    {
        if (sharedPrefs.getBoolean("user_called", false))
        {
            // Si fue por una llamada del usuario eliminar bandera y no hacer nada
            Utils.setUserCalled(getApplicationContext(), false);
        }
        else
        {
            mPager.setCurrentItem(0);
        }
    }
}

The other method is this:
Boolean appState = false;

@Override
public void onPause() {
    super.onPause();
    appState = false;
}

@Override
public void onResume() {
    super.onResume();

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    if(!appState)
    {
        if (sharedPrefs.getBoolean("user_called", false))
        {
            // Si fue por una llamada del usuario eliminar bandera y no hacer nada
            Utils.setUserCalled(getApplicationContext(), false);
        }
        else
        {
            mPager.setCurrentItem(0);
        }
    }
}

Both use a flag callsed user_called to know if the user started a call. My problem right now is that both methods fail when the phone rings. Is there a way to filter these cases?

A: isFinishing()

  return TRUE when activity is going to  finish or destroyed.
isFinishing()

  return FALSE when activity is going to  background.
@Override
protected void onPause() {

    super.onPause();
    if (!this.isFinishing()){

        //Insert code for HOME  key Event
    }
}

A: Ovverriding onUserLeaveHint() works with me - I can make actions as soon as the user leaves using the Home button, and it's not called in case of incoming calls.
Don't know if this would work with a home activity.
@Override
public void onUserLeaveHint() {
    super.onUserLeaveHint();
    mPager.setCurrentItem(0);
}

A: You can use the OnPause() of course, but you can also try this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if(keyCode == KeyEvent.KEYCODE_HOME) {
        //do things
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

A: As noted in the previous answers, you can hook home key pressed event. However, this will work only when your app is running (i.e. displayed on your screen).
But if I understand you right, you actually want something else. You are making a custom launcher, so you would like that Android launches your app when home button is pressed. To achieve this, you need to properly set your AndroidManifest.xml file.
Here is a complete step-by-step guide, how to make a custom launcher application. Section 3  has a detailed description, how to register your application as a launcher.
http://code.tutsplus.com/tutorials/build-a-custom-launcher-on-android--cms-21358

A: You cannot listen to home button press since it is a system event and is not delivered to the applications. That is described in the documentation here and also can be seen from Android codes here. The idea behind is simple - you should not be able to write an app which will hijack the phone. You can "break" the back button functionality, but not the home button functionality.
Now what the third-party launchers are usually doing is first of all declaring the launcher activity launch mode as singleInstance in manifest: android:launchMode="singleInstance". Then, in addition to overriding the onCreate() you also override onNewIntent(). It is usually called instead of onCreate() when the activity is already running but someone fired an intent to start it again. In case of a launcher it will be called when your launcher is already running but system fires an intent to launch it because the user pressed the home button. In that function you can go to your default 'home' page.


text:
Q: What is Get-NetIPInterface in C# .NET Does anybody know what is Powershell commands: "Get-NetIPInterface" and "Set-NetIPInterface" in C# .NET? I want to write a simple application to do these commands jobs.
Thanks for your help.


text:
Q: Generate replacement How can I generate different combinations of the word "password" and it can include upper and lower case and both 'S' characters can be replaced with 5 and the 'o' character can be replaced with the number 0
eg Results:

Password
  p@s5word
  pa5sWord
  pa55w0rd
  PAssw0rd
  etc

Any help will be appreciated
This is what I have so far, but only returns the same string of "ppassword"
char[] CharList = new char[]
       {'p','a','s','s','w','o','r','d','@','5','5','0','P','A','S','S','W','O','R','D'};
string password = "password";
int _base = CharList.Length;

int current = IntPasswordsGenerated++;

do
{
    password = CharList[current % _base] + password;
    current /= _base;
} while (current != 0);

return password;

A: Okay so I have an idea for that. I rebuild simple "permutation" function and made it use a custom list of objects instead of pure char :
    public class CharData
    {
        char[] _char= new char[0];
        public char[] Characters { get { return _char; } set { _char= value; } }
    }

// method to initialize character data
    public static List<CharData> Initialize()
    {
        List<CharData> charData = new List<CharData>();
        charData.Add(new CharData {
            Characters = new char[] { 'p', 'P' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 'a', 'A' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 's', 'S', '5' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 's', 'S', '5' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 'w', 'W' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 'o', 'O', '0' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 'r', 'R' }
        });
        charData.Add(new CharData {
            Characters = new char[] { 'd', 'D' }
        });
        // Add your characters in order you want them to be processed
        return charData;
    }

// rebuilded permutation
    public static void Build(List<CharData> data, string build = "", int startingIndex = -1)
    {
        if( build.Length == data.Count )
        {
            Console.WriteLine(build);
        }
        else
        {
            for ( int i = startingIndex + 1; i < data.Count; i ++ )
            {
                for ( int j = 0; j < data[i].Characters.Length; j++)
                {
                    Build(data, build + data[i].Characters[j], i);
                }
            }
        }
    }

    public static void Main(string[] args)
    {
        Build(Initialize());
    }

Test it on rextester

A: Side Note: As Tinwor mentioned this a char replacement not permutation.
So, here is one way to do it:

*

*Build a set of lists that contain possible replacement chars for each 'unique' character in the word you are interested in this case its 'password';

*Write a function that accepts a word to operate on and the lists or replacement chars;

A quick sample:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    private static readonly Dictionary<char, List<char>> _replacementChars = new Dictionary<char, List<char>>{};

    public static void Main()
    {
        // Fill replacement chars collection
        _replacementChars.Add('p', new List<char>{'p', 'P'});
        _replacementChars.Add('a', new List<char>{'a', 'A', '4'});
        _replacementChars.Add('s', new List<char>{'s', 'S', '$', '&', '5'});
        _replacementChars.Add('w', new List<char>{'w', 'W'});
        _replacementChars.Add('o', new List<char>{'o', 'O', '0', '@'});
        _replacementChars.Add('r', new List<char>{'r', 'R', '4'});
        _replacementChars.Add('d', new List<char>{'d', 'D'});

        // We want to search on lower variants of each char of the source word, beacuase it's simple this way
        var sourceWord = "password".ToLower();

        var sourceWordChars = sourceWord.ToCharArray();
        var targetWordChars = new char[sourceWord.Length];

        // TODO: This will need a different implementation if we want to get all possible variations of the sourceWord rather than just a random version of it
        for(var i = 0; i < sourceWordChars.Length; i++)
        {
            var replacement = GetReplacementChar(sourceWordChars[i]);

            targetWordChars[i] = replacement;
        }

        var targetWord = string.Join("", targetWordChars);

        Console.WriteLine(string.Format("Source word: {0}", sourceWord));
        Console.WriteLine(string.Format("Target word: {0}", targetWord));
    }

    private static char GetReplacementChar(char charToReplace)
    {
        if(!_replacementChars.ContainsKey(charToReplace))
        {
            return charToReplace;
        }

        var chars = _replacementChars[charToReplace];

        // Get random char from list
        var rand = new Random();
        var index = rand.Next(0, chars.Count);

        return chars[index];
    }
}

Here is the fiddle for code above.


text:
Q: iPad Mini can't open apps I've had my iPad for a year now. When I tried to open Safari and my iPad froze and I came back to the home screen. This started after the new software update. Since then no apps will open, not even the App Store. I've tried restarting it and let it die (letting the battery run out) and recharging, but it didn't help.
How can I open apps on my iPad?

A: *

*As 'Dempa' said in comments, you should do a hard-reset:
https://support.apple.com/en-us/HT201559 <- "Force Restart"

*If this does not solve the problem, you should back up your info in iTunes (Assuming that you cant open Settings app):
https://support.apple.com/en-us/HT203977 <- "iTunes Backup"

*And if restoring doesnt solve the problem, you will have to go into an Apple Service Shop/Center, however they are called in your country, and ask for technical assistance.
**Im pretty sure the HARD RESET step is what you need.
Hope it helps.


text:
Q: Sharing database connection pool between Spring Boot apps running Embedded Tomcat My current production setup requires me to share Oracle database connection pools between multiple Spring Boot apps where each app runs via an embedded Tomcat instance.
What options do I have to share the database connection pool among these Spring Boot apps?
Is JNDI an option? If so, could someone explain how storing the connection pool details in say LDAP accessed via JNDI works?


text:
Q: Connecting to torrent trackers / peers I'm currently trying to implement a minimal torrent client, in nodeJS.
I'm reading through this specification: https://wiki.theory.org/index.php/BitTorrentSpecification
I've got 2 magnet URIs:
magnet:?xt=urn:btih:633ab5b0cc27218bca2f9fec9b68ae4f7cbf0c5f&dn=dmb2017-05-31.dpa4021.flac16

xt=urn:btih:633ab5b0cc27218bca2f9fec9b68ae4f7cbf0c5f
dn=dmb2017-05-31.dpa4021.flac16

magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969

xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871
dn=Ubuntu+16.04.1+LTS+Desktop+64-bit
tr=udp://tracker.leechers-paradise.org:6969
tr=udp://zer0day.ch:1337
tr=udp://open.demonii.com:1337
tr=udp://tracker.coppersurfer.tk:6969
tr=udp://exodus.desync.com:6969

From what I've read, the tracker is used to find peers, from which data is downloaded. How would one download the first torrent then? It has no tracker.
How do I actually do conduct this connection?
The specification has nothing on magnet links, and states that trackers can be used via the HTTP(S) protocols, but these are clearly UDP.
I gave a stab at this:
var PORT = 6969 ;
var HOST = 'tracker.leechers-paradise.org';

var dgram = require('dgram');
var message = new Buffer("xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871");

var client = dgram.createSocket('udp4');

client.on('listening', function () {
    var address = client.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

client.on('message', function (message, remote) {

    console.log(remote.address + ':' + remote.port +' - ' + message);

});

client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {

    if (err) throw err;
    console.log('UDP message sent to ' + HOST +':'+ PORT);
    console.log(bytes);

});

Obviously, this doesn't work, but I can't find any documentation to help.

A: The inofficial Wiki.theory.org/BitTorrentSpecification is without doubt the very best place to start learning about the BitTorrent protocol, but it is incomplete. It only covers the base protocol and the extensions that was developed in the early years. That's why you can't find all the information you need there.
Since 2008 the official* documentation of the protocol can be found at BitTorrent.org.
The official version of the base protocol is the terse and dense BEP3 - The BitTorrent Protocol Specification.
Magnet links is covered in BEP9 - Extension for Peers to Send Metadata Files.
There can you read:

If no tracker is specified, the client SHOULD use the DHT to acquire peers.

The DHT is specified in BEP5 - DHT Protocol.
As you have noticed, trackers nowadays use UDP, that is specified in BEP15 - UDP Tracker Protocol.

footnote: * Official only means that it's run by BitTorrentInc, not that it's superior or the only source to use. The BitTorrent protocol is not governed by authority. None client has pledged allegiance to BEP. The protocol is formed by consensus from what clients in the real do.


text:
Q: Using Applescript run powerpoint slide show of specified slide in the presentation I want to run PowerPoint slide show for only a particular slide.
After my research, I tried following but I did not get expected result.
Both of the scripts, starts slide show but from the first slide.
1)
`tell application "Microsoft PowerPoint"
    activate
    open "/Users/sanjeev/pppp.ppt"
    set slideShowSettings to slide show settings of active presentation
    set starting slide of slideShowSettings to 4
    set ending slide of slideShowSettings to 4
    run slide show slideShowSettings
end tell`

2)
`tell application "Microsoft PowerPoint"
    activate
    open "/Users/sanjeev/pppp.ppt"
    set slideShowSettings to slide show settings of active presentation
    run slide show slideShowSettings
    go to slide slide show view of slide show window 1 number 4
end tell`

The second script gives an error also:
error "Microsoft PowerPoint got an error: slide show view of slide show window 1 doesn't understand the go to slide message." number -1708 from slide show view of slide show window 1
I saw a question Want Applescript to change a Keynote presentation to a particular slide
But I think that works only for KeyNote.
Can anyone help?
Thanks

A: This seems to work. It looks buggy to me. When the script is run the screen goes black, then flashes the slide then goes black then finally displays the slide. I don't know if this is due to the script or the implementation of Applescript/ppt from Microsoft. I say the latter.
tell application "Microsoft PowerPoint"
    set temp to active presentation's slide show settings
    set temp's starting slide to 2
    set temp's ending slide to 2
    set temp's range type to slide show range
    set temp's advance mode to slide show advance manual advance
    run slide show temp
end tell


text:
Q: Getting position value 0 while retrieving hi i'm passing the value of Context,Actionmode,list and position in my class Topratedfragment.java through a function Actionmodecallback
 And while retrieving the values in function i am getting all values fine except the value of position when i'm trying to save its value in my global variable of class . and i'm sorry if my question is stupid i have very less idea about passing in java
My both classes are
Topratedfragment class
public class TopRatedFragment extends Fragment {

Intent i;
TextView studentid;
Button Bite;
DBHelper mydb;
Cursor mcursor;
ListView list;
// Context context;
Simpleadapter adapter;
int nr = 0;
ArrayList<String> array_list;
ActionMode mActionMode;
String valstudentid;
int _position;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_top_rated,
            container, false);
    DBHelper mydb = new DBHelper(getActivity().getApplicationContext());

    array_list = mydb.getAllCotacts();

    list = (ListView) rootView.findViewById(R.id.listview1);

    adapter = new Simpleadapter(getActivity(), array_list);

    list.setAdapter(adapter);

    list.clearChoices();
    for (int i = 0; i < list.getCount(); i++)
        list.setItemChecked(i, false);
    list.post(new Runnable() {
        @Override
        public void run() {
            list.setChoiceMode(ListView.CHOICE_MODE_NONE);
        }
    });

    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {

            if (mActionMode == null) {

                int id_To_Search = position + 1;
                Bundle dataBundle = new Bundle();
                dataBundle.putInt("id", id_To_Search);
                Intent intent = new Intent(
                        getActivity().getApplicationContext(),
                        info.meritech.project.databasefiles.DisplayContact.class);
                intent.putExtras(dataBundle);
                startActivity(intent);
            } else {

                onListItemCheck(position);
            }

        }
    });

    list.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long id) {
            onListItemCheck(position);
            return true;

        }
    });

    return rootView;
}

private void onListItemCheck(int position) {
    // TODO Auto-generated method stub

    _position = position;
    adapter.toggleSelection(position);
    boolean hasCheckedItems = adapter.getSelectedCount() > 0;

    if (hasCheckedItems && mActionMode == null)
        // there are some selected items, start the actionMode
        mActionMode = getActivity().startActionMode(
                new ActionModeCallback(getActivity()
                        .getApplicationContext(), array_list, list,
                        mActionMode, position));
    else if (!hasCheckedItems && mActionMode != null)
        // there no selected items, finish the actionMode
        mActionMode.finish();

    if (mActionMode != null)
        mActionMode.setTitle(String.valueOf(adapter.getSelectedCount())
                + " selected");

}

public Context getActivity(Context context) {

    context = getActivity().getApplicationContext();
    return context;

}

}

Actionmodecallback class
public class ActionModeCallback implements ActionMode.Callback {

Context _context;
ActionMode _mActionMode;
ArrayList<String> _array_list;
ListView _list;
int _position_list;

public ActionModeCallback(Context context, ArrayList<String> array_list,
        ListView list, ActionMode mActionMode, int position) {
    super();
    this._context = context;
    this._mActionMode = mActionMode;
    this._array_list = array_list;
    this._list = list;
     this._position_list=position;
}

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    // inflate contextual menu
    mode.getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

    return false;
}

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    // retrieve selected items and print them out

    switch (item.getItemId()) {
    case R.id.add:

        int id_To_Search = +1;
        Bundle dataBundle = new Bundle();
        dataBundle.putInt("id", id_To_Search);
        Intent intent = new Intent(_context, Edit.class);
        intent.putExtras(dataBundle);
        _context.startActivity(intent);

        Toast.makeText(_context, "new class", Toast.LENGTH_SHORT).show();

        // close action mode
        mode.finish();

        break;
    }
    return false;

}

@Override
public void onDestroyActionMode(ActionMode mode) {
    // remove selection
    Simpleadapter adapter = new Simpleadapter(_context, _array_list);
    adapter.removeSelection();
    _mActionMode = null;
    _list.clearChoices();
    for (int i = 0; i < _list.getCount(); i++)
        _list.setItemChecked(i, false);
    _list.post(new Runnable() {
        @Override
        public void run() {
            _list.setChoiceMode(ListView.CHOICE_MODE_NONE);
        }
    });
}

}

i am getting the value of this._position_list=0 at line 13 in ActionmodeCallback.class where as the values of other variables are perfectly fine why it is happening with this variable position
 this._position_list=position;


text:
Q: I want to pull data into a Visualforce stacked bar chart using an Apex controller Every example I've seen is of Visualforce stacked bar charts with the data hard-coded in the Apex controller, similar to https://hub.appirio.com/tech-blog/building-dynamic-stacking-bar-charts-in-visualforce.
If I have 3 parent records with up to 10 child records, I want to display 3 stacked bars. The below code display as a simple bar chart, not stacked:
Apex Controller
public with sharing class PFResidentialSchoolExpendController {
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        List<Residential_School_Expenditure_Details__c> queryResults =
            [SELECT Id, Name, (SELECT Residential_School_Expenditure_Phase__c, Expenditure_Type__c,
                              Expected_Expenditure__c FROM Phase_wise_Expenditure_Details__r)
            FROM Residential_School_Expenditure_Details__c
            ORDER BY Name DESC];
        if(queryResults.size() > 0) {
            for(Residential_School_Expenditure_Details__c r : queryResults) {
                for(Phase_wise_Expenditure_Details__c p : r.Phase_wise_Expenditure_Details__r) {
                    data.add(new PieWedgeData(r.Name,p.Expected_Expenditure__c));
                }
            }
            return data;
        }
        else {
            System.debug('No expenditures found.');
            return null;
        }
    }
    public class PieWedgeData {
        public String name1 {get; set;}
        public Decimal data1 {get; set;}
        }
    }
}

Visualforce:
<apex:page showHeader="false" sidebar="false"
           controller="PFResidentialSchoolExpendController" title="Residential School Expenditures">
    <apex:stylesheet value="https://fonts.googleapis.com/css?family=Roboto"/>

    <apex:chart height="300" width="800" data="{!pieData}" colorSet="#405395, #E5763E, #009345">
        <apex:axis type="Category" position="left" fields="name1" title="Phase"/>
        <apex:axis type="Numeric" position="bottom" fields="data1"
                   title="Expenditures"/>
        <apex:barSeries orientation="horizontal" axis="bottom" xField="data1" yField="name1"
                        stacked="true"
                        title="Agricultural Development,Construction,Demolition,Earthwork,Furniture/Fixture/Equipment,Inspection,Land,Operations,Other,Sitework"/>
        <apex:legend position="right"/>
    </apex:chart>

</apex:page>


text:
Q: PROC SQL - Case when with multiple tables I need to create a dataset (TABLE3) in order to check if some variables from other two tables are equals. If so, the code must return 0, otherwise 1. But, as I'm a new user of SAS and SQL I'm struggling to figure out how to do that.
I'm trying something like that but it's not working.
PROC SQL;
CREATE TABLE TABLE3 AS
SELECT A.*, B.*
CASE WHEN B.VARIABLE1 = A.VARIABLE2 THEN 0 ELSE 1 END AS VARIABLE_1_2,
CASE WHEN B.VARIABLE3 = A.VARIABLE4 THEN 0 ELSE 1 END AS VARIABLE_3_4
FROM TABLE1 AS A
LEFT JOIN TABLE2 AS B;

P.S.: Variables 1, 2, 3 and 4 are all character variables.

A: For a JOIN condition to work, there must a ON clause
PROC SQL;
CREATE TABLE TABLE3 AS
SELECT A.*, B.*,
CASE WHEN B.VARIABLE1 = A.VARIABLE2 THEN 0 ELSE 1 END AS VARIABLE_1_2,
CASE WHEN B.VARIABLE3 = A.VARIABLE4 THEN 0 ELSE 1 END AS VARIABLE_3_4
FROM TABLE1 AS A LEFT JOIN TABLE2 AS B
**ON TABLE1.SOME_COLUMN_NAME = TABLE2.SOME_COLUMN_NAME**
;

A: In addition to the tables relation you must add after the join, You miss a coma "," just before the first case.


text:
Q: Amazon AWS + Varnish + varnish-devicedetect Can somebody help setup this?
In my instance (RHEL), installed Varnish it work well.
Then setup varnish-devicedetect,
 yum  list installed | grep varnish
 varnish.x86_64                        3.0.5-1.16.amzn1             @amzn-main
 varnish-libs.x86_64                   3.0.5-1.16.amzn1             @amzn-main
 varnish-release.noarch                4.0-3.el6                    installed

When I tried add any code example to defaul.vcl, Varnish fails to start. This code is OK:
 include "devicedetect.vcl";
 sub vcl_recv {
     call devicedetect;
 }

But after this Varnish fails to start:
 sub vcl_backend_response {
     if (bereq.http.X-UA-Device) {
         if (!beresp.http.Vary) { # no Vary at all
             set beresp.http.Vary = "X-UA-Device";
         } elsif (beresp.http.Vary !~ "X-UA-Device") { # add to existing Vary
             set beresp.http.Vary = beresp.http.Vary + ", X-UA-Device";
         }
     }
     # comment this out if you don't want the client to know your classification
     set beresp.http.X-UA-Device = bereq.http.X-UA-Device;
 }

Tried, even empty:
 sub vcl_backend_response {

 }

Caused same problem.
What I missed?

A: It seems found answer: need use rules from Varnish ver. 3, used this set:
sub vcl_fetch {
    if (req.http.X-UA-Device) {
        if (!beresp.http.Vary) { # no Vary at all
            set beresp.http.Vary = "X-UA-Device";
        } elseif (beresp.http.Vary !~ "X-UA-Device") { # add to existing Vary
            set beresp.http.Vary = beresp.http.Vary + ", X-UA-Device";
        }
    }
    set beresp.http.X-UA-Device = req.http.X-UA-Device;
}
sub vcl_deliver {
    if ((req.http.X-UA-Device) && (resp.http.Vary)) {
        set resp.http.Vary = regsub(resp.http.Vary, "X-UA-Device", "User-Agent");
    }
}

Found here: https://www.varnish-cache.org/docs/3.0/tutorial/devicedetection.html

A: You could have found the error by trying to compile your vcl:
varnishd -C -f default.vcl (or whatever the path is to your vcl file)
This will tell you if your vcl has valid syntax or not - which will let varnish start without failure.


text:
Q: Incomplete Ajax Request after Form Submission I am currently running a mobile-focused site that supports file upload and what I am attempting to do is save the user a lot of idle time when they upload a file to a form.
My goal is as follows:
 xhr = new XMLHttpRequest();

 xhr.open("POST", "http://myServer/myEndpoint");
 xhr.setRequestHeader("Cache-Control", "no-cache");
 xhr.setRequestHeader('Content-Type', 'text');
 xhr.setRequestHeader('foo', "bar");
 xhr.send( myData );

 //PseudoCode
 if( xhr.DataIsSent ) myForm.submit();

As you can see, I'm aiming to prevent the user having to wait for an ajax response before submitting the form, Ideally i'd like this to run in the background irrespective of what the user does.
My understanding of ajax was that once the request is dispatched, unless it is manually cancelled, it will be completed, however, I have had cases where the data which reaches the server is incomplete
Any Suggestions on how i could achieve this reliably would be greatly appreciated. So far it appears that once the form is submitted, the partially completed request is terminated.

A: As i can read on the Mozilla Developer Pages,
XmlHttpResponses are stateful, as well.
I would recommend you to use jQuery:
1. create a promise for your ajax request
2. use when().then() before the Form submit
3. catch errors
Do you need any code example for it?


text:
Q: Program execution time in accuracy better than ms I am using time_taken = ((double)t * 1000) / CLOCKS_PER_SEC;
Where
    t = clock();
    myFunctionToMeasureTimeTaken();
    t = clock() - t;

But at best it only give the running time in ms. And that function runs way too fast.
Is there anything I can use to measure in times of micro or even nanosec?
I am using MS Visual Studio 2013

A: The usual way to time functions with short execution times, when only a coarse timer is available, is to run the function repeatedly in a loop, say, a million times, and measure that.
If you are willing to sacrifice Standard C conformance, there may be system specific timers with higher resolution.


text:
Q: Connecting to remote cassandra database I am trying to connect to a remote cassandra database using dbeaver.
I installed cassandra over an ubuntu machine from digital ocean, and I am running the dbeaver from my local machine.
When I leave the default /etc/cassandra/cassandra.yaml file, and then run the netstat -ntlp | grep 9420 I find that the connection is on and waiting for connection but once I update both the listen_address and the rpc_address to the public IP address of the remote machine, I found that I am no longer able to connect even locally to the database, using cqlsh cli.
What are the steps I should do to connect to a remote cassandra database, I read a lot of articles, but obviously there is something missing I can't understand


text:
Q: How high is a tab bar in iPhone OS? I tried to get that info, but google returns me just nothing about that. Does anyone know that exactly? I remember a value around 40 units, but I am not sure. The Constants.h of UICatalog.xcodeproj doesn't mention it.

A: If you mean the height then it is 49 px.
To find this I went into Interface Builder, created a blank view, then set Simulated Metrics -> Bottom Bar -> Tab Bar and noted the new dimensions of the view (320x431).
480 - 431 = 49px

A: You can also drop a
    NSLog(@"Tab Bar dimensions : %@", NSStringFromCGRect(yourTabBarController.tabBar.frame));

To see a string containing {{x, y}, {width, height}} wherever you alloc'ed the UITabBarController. You'll get 49 though, maybe this is overkill.

A: If you are like me, and don't like hardcoding these things, try:
UITabBarController *tabBar = [[UITabBarController alloc] init];
tabBarHeight = tabBar.tabBar.frame.size.height;

I put the first line in a utilities class (which is initialized at app startup), and just access tabBarHeight after that.


text:
Q: Application Cache or Service Workers - which to use in 2016/Q2? Quick question for discussion really, as I wanted to have input from different people.
I am in the process of developing a web page app that must be available offline.
Now to do this, as I understand it, you would go about using either the application caching feature or by using service workers.
However, here is the conundrum I have. When researching the application cache, the MDN clearly states:

Deprecated:
  This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

After which another dialog box suggests using service workers instead.
The Service Workers page then goes on to state how Service Workers are an experimental technology, and it is best to consult the compatibility table.
The compatibility table says that Safari and Internet Explorer do not support Service Workers. Further consulting this site and assuming it is accurate, it states that work has begun by Microsoft to integrate service workers, however for Safari they are "Under consideration" with " Brief positive signals in five year plan."
Now this is a concern for the current project as it is essential that it be safari compatible, however, I also do not want it to break in other browsers.
What would be your recommendations? Simply go with the older Application Caching and update in the near future? Determine the users browser and act appropriately? Or, is there another way I am missing?

A: You're right, appcache is becoming unsupported.
And there are other options that store data and/or assets inside IDB such as:

*

*Offline Web Applications with CouchDB, PouchDB and Emeber CLI

*Ember-Pouch

*Offline apps using Ionic Framework, PouchDB and AngularJS
Try googling "offline pouchdb ember" or "offline pouchdb angular" for more examples.
The only mechanisms for ensuring offline availability right now are service workers and appcache. Period.
All of these techniques rely on your site being a single page application and the entry point to be reachable. So if you are not using appcache or service workers to ensure the entry point is always reachable, you must fallback to http cache and properly set cache-related headers when serving your assets. Anyway, http cache can be evicted at any moment by the UA.
Facing this decision, if it is mandatory for the application to run offline and in Safari, the only option is to use appcache (AFAIK, there are no news about removing appcache from Safari).
To reduce the risk you could opt for combining one of the previous techniques (those that store assets on IndexedDB) in addition to appcache so the only thing you cache is the entry point for the SPA. If appcache becomes unsupported and there is no service worker alternative you could switch to the cache headers alternative.
Anyway, you can use feature detection (if ('serviceWorker' in navigator) { ... }) to see if service workers are available and use it in case it is. There is a polyfill for appcache based on service workers called JakeCache (not tested) and others are to come.

A: According to Mozilla's HTML5 Service Workers Doc:

Note: One great thing about service workers is that if you use feature
  detection like we've shown above, browsers that don't support service
  workers can just use your app online in the normal expected fashion.
  Furthermore, if you use AppCache and SW on a page, browsers that don't
  support SW but do support AppCache will use that, and browsers that
  support both will ignore the AppCache and let SW take over.

Code "above":
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
  .then(function(reg) {
    // registration worked
    console.log('Registration succeeded. Scope is ' + reg.scope);
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
}

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers

A: You could choose to use Service Workers and AppCache on the same web app. What happens in such a case is that browsers that don't support Service Workers will use AppCache, and those that do will ignore the AppCache and let the Service Worker take over.
Sources: https://www.w3.org/TR/service-workers/#activation-algorithm, https://crbug.com/410665

A: There is definitely the option to use both at the same time. If you want to deploy a cross-browser application in the next couple of years, my impression is that you have to keep using AppCache, as iOS is only "thinking about" implementing Service Workers in the next 5 years.
Here's some JavaScript that we are using to detect whether to use one or the other and to initialize both
if ( 'serviceWorker' in navigator && b ) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
showMsg('ServiceWorker registration successful with scope: ', registration.scope);
if ( registration.installing ) {
  showMsg( 'Service worker installing' );
} else if ( registration.waiting ) {
  showMsg( 'Service worker installed' );
} else if ( registration.active ) {
  showMsg( 'Service worker active' );
}
  }).catch(function(err) {
    // registration failed :(
    showMsg('ServiceWorker registration failed: ', err);
  });

// Listen for claiming our ServiceWorker
navigator.serviceWorker.addEventListener('controllerchange',
function(event) {
      // Listen for changes in the state of our ServiceWorker
      navigator.serviceWorker.controller.addEventListener('statechange', function() {
        // If the ServiceWorker becomes "activated", let the user know they can go offline!
        if (this.state === 'activated') {
        // This example is refreshing the app directly, but you can inform the user with a fancy modal window or similar
            window.location.reload( true );
        }
      });
    });

// Browsers not using Service Workers
    } else  if ('applicationCache' in window) {
      var iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = 'load-appcache.html'
      document.body.appendChild(iframe);
      showMsg("Iframe loaded for AppCache management");

    } else {
      showMsg("no service worker - no appCache");

 }

The code described to initialize AppCache helps refreshing the new pages when the appcache file changes. I grabbed it from several sources but all coming from the powerful presentation that Patrick Kettner delivered during the PWA Dev Summit 2016: (https://www.youtube.com/watch?v=IgckqIjvR9U&t=1005s)
load-appcache.html contains nothing but
<!DOCTYPE html>
<html manifest="offline.appcache">
    <head>
        <title>loding appCache</title>
   </head>
   <body></body>
</html>

There are of course multiple possibilities that SW provides to deliver a fancier app, but with AppCache and IDB you can indeed do pretty much any business logic you want, including offline capabilities.
Beware that you will not be able to test AppCache functionality with Chrome as they have disabled it, but you can still force Firefox (I have tested with 50.1.0). You can always use Safari though :)