text:
Q: Codeigniter DataGrid Class So, I am building myself a simple(ish) datagrid class for my CodeIgniter app.
What I am wondering is, I have some columns that I would like to "format" in that I mean, some may contain only a 1 or a 0, yet I want to turn them into a Yes or No respectively.
How can I do this?  In other words, I want to be able to pass in another parameter..something like:
$this->_columnCallBack pass it an array like array(column_number=>'NameOfCallBackFunction')
I am assuming that I would do it somewhat like I did the _columnclass, where I pass in the column number, and the class as an array... but I don't know how I would get the function to fire off to do the replacement...
Code
class O7thDG {

    public function __construct($params){
        $this->_table = $params['table'];
        $this->_pk = $params['pk'];
        $this->_fields = (isset($params['fields'])) ? $params['fields'] : null;
        $this->_where = (isset($params['where'])) ? $params['where'] : null;
        $this->_order = (isset($params['order'])) ? $params['order'] : null;
        $this->_extras = (isset($params['extras'])) ? $params['extras'] : null;
        $this->_add = (isset($params['add'])) ? $params['add'] : FALSE;
        $this->_edit = (isset($params['edit'])) ? $params['edit'] : FALSE;
        $this->_delete = (isset($params['delete'])) ? $params['delete'] : FALSE;
        $this->_editlink = (isset($params['editlink'])) ? $params['editlink'] : null;
        $this->_deletelink = (isset($params['deletelink'])) ? $params['deletelink'] : null;
        $this->_editlinkextras = (isset($params['editlinkextras'])) ? $params['editlinkextras'] : null;
        $this->_deletelinkextras = (isset($params['deletelinkextras'])) ? $params['deletelinkextras'] : null;
        $this->_tableid = (isset($params['tableid'])) ? $params['tableid'] : null;
        $this->_tableclass = (isset($params['tableclass'])) ? $params['tableclass'] : null;
        $this->_columnclass = (isset($params['columnclass'])) ? $params['columnclass'] : null;
        $this->_includeheader = (isset($params['includeheader'])) ? $params['includeheader'] : TRUE;
        $this->_allowpaging = (isset($params['allowpaging'])) ? $params['allowpaging'] : FALSE;
        $this->_sorting = (isset($params['sorting'])) ? $params['sorting'] : null;
        $this->_columncallback = (isset($params['columncallback'])) ? $params['columncallback'] : null;
    }

    public function BuildIt($responsive = TRUE){
        $_ci =& get_instance();
        $_ci->load->database();
        $_ci->load->library('table');
        $_ci->load->library('TKCommon', null, 'comm');
        $fldlist = $this->_buildSelectFieldList();
        $_ci->db->select($fldlist);
        $cols = $this->_buildColumnFieldList();
        $ret = '';
        if($this->_where != null){
            // build the where

        }
        if($this->_order != null){
            // build the order

        }
        if($this->_extras != null){
            // build the extras

        }
        // Query the specified table
        $qry = $_ci->db->get($this->_table);
        if($cols == null){
            $cols = $_ci->db->list_fields($this->_table);
            $fldlist = $cols;
        }else{
            $fldlist = explode(', ', $fldlist);
        }
        if($qry){
            // throw the results into an associative array
            $rs = $qry->result_array();
            if($rs){
                $rCt = count($rs);
                $cCt = $qry->num_fields();
                // add our responsive wrapper
                if($responsive){
                    $ret .= '
';
                }
                // fire up our table
                $tid = '';
                $tc = '';
                if($this->_tableid != null){$tid = ' id="' .$this->_tableid . '"';}
                if($this->_tableclass != null){$tc = ' class="' .$this->_tableclass . '"';}
                $_ci->table->set_template(array('table_open'=>'
'));
                // build our header row, but only if we need to
                if($this->_includeheader && $cCt > 0){
                    // see if we need to include the admin column
                    if($this->_edit || $this->_delete){
                        $_ci->table->set_heading(array_merge($cols, array('Admin')));
                    }else{
                        $_ci->table->set_heading($cols);
                    }
                }
                // build each records row
                for($r = 0; $r < $rCt; ++$r){
                    $ca = array();
                    for($c = 0; $c < $cCt; ++$c){
                        if(($this->_columnclass != null) && ($c == key($this->_columnclass))){
                            // figure out which column needs the class, and what class needs to be applied
                            $ca[] = $this->_columnCallback($c, array('data'=>$rs[$r][$fldlist[$c]], 'class'=>$this->_columnclass[key($this->_columnclass)]));
                        }else{
                            $ca[] = $this->_columnCallback($c, $rs[$r][$fldlist[$c]]);
                        }
                    }
                    // see if we need to include the admin column
                    if(($this->_edit || $this->_delete) && ($this->_editlink != null || $this->_deletelink != null)){
                        $txt = '';
                        if($this->_edit &&($this->_editlink != null)){
                            $txt .= '_editlink . '?id=' . $rs[$r][$this->_pk] . '">   ';
                        }
                        if($this->_delete &&($this->_deletelink != null)){
                            $txt .= '_deletelink . '?id=' . $rs[$r][$this->_pk] . '">';
                        }
                        if(($this->_columnclass != null) && ($cCt == key($this->_columnclass))){
                            $ca[] = array('data'=>$txt, 'class'=>$this->_columnclass[key($this->_columnclass)]);
                        }else{
                            $ca[] = $txt;
                        }
                    }
                    $_ci->table->add_row($ca);
                }
                $ret .= $_ci->table->generate();
                // close our responsive wrapper
                if($responsive){
                    $ret .= '
';
                }
            }else{
                $ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
            }
        }else{
            $ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
        }
        return $ret;
    }

    // build our select's field list
    private function _buildSelectFieldList(){
        if($this->_fields == null){
            return '*';
        }else{
            $flds = array_map(function($item){return $item['field'];}, $this->_fields);
            return implode(', ', $flds);
        }
    }

    // build our tables column list
    private function _buildColumnFieldList(){
        if($this->_fields == null){
            return null;
        }else{
            return array_map(function($item){return $item['label'];}, $this->_fields);
        }
    }

    private function _columnCallback($col, $val){
        if($this->_columncallback != null){
            if($col == key($this->_columncallback))
                return $this->_columncallback[key($this->_columncallback)]($val);
        }else{
            return $val;
        }
    }

}

and my external function that I may want to use is simply:
// Format boolean value to Yes or No
public function YesNo($val){
    return ((bool)$val) ? 'Yes' : 'No' ;
}

CI Documentation for the table class has $this->table->function, however, the function(s) passed applies to the entire table

A: These functions will work as you want to, but you need to rewrite a bit for your needs.
function callback1($array, $row_id, $function)
{
    if(function_exists($function))
        return $function($array[$row_id]);
    else
        return 0;
}

function YesNo($val)
{
    return intval($val) ? 'Yes' : 'No' ;
}

#example of array and usage of script.
$array = array('id' => '0', 'id2' => '1');
$ok = callback1($array, 'id2', 'YesNo');

A: Make filters array
$this->filters = ['column_name' => 'function_name', 'column_name2' => 'otherFunction'];

Then you just apply the filter to the data
if ( array_key_exists($column_name, $this->filters) ) {
   // Add row that contains filtered data
   $row_data = $this->filters[$column_name]($column_val);
}else{
   $row_data = $column_val;
}

If your functions aren't available globally (not in a helper or built-in php), you'll have to use something like this:
call_user_func(array($this, $this->filters[$column_name]), $column_val);

OR

$this->{$this->filters[$column_name]}($column_val);

This would run a function from inside the library O7...

A: What about using and/or anonymous functions:
http://docs.php.net/manual/es/function.func-get-args.php
http://php.net/manual/en/functions.anonymous.php
Update 2 "reloaded"
You could also check grocery crud, it's CI library and do some interesting things that can be useful for you project:
http://www.grocerycrud.com/
Grocery crud uses  call_user_func from PHP and allows you to use any function declaread in your controller, if this is what you need then it's just matter of time and check grocery crud code.
In the library a protected property is declared for each callback for example (line #3386 v1.4.1):
/* Callbacks */
protected $callback_before_insert = null;

So you/me/any can set the callback function in case is needed, then check for any callback setted doing something like (line #878 GroceryCrud 1.4.1):
if($this->callback_before_insert !== null)
{
    $callback_return = call_user_func($this->callback_before_insert, $post_data);

        if(!empty($callback_return) && is_array($callback_return))
            $post_data = $callback_return;
       elseif($callback_return === false)
            return false;
}

Of course there's a method to set the callback (line #4518 from v1.4.1):
public function callback_before_insert($callback = null)
{
    $this->callback_before_insert = $callback;
    return $this;
}

And the user/dev set the callback doing:
$crud->callback_before_insert(array($this,'my_callback'));

And/Or this technique allows you use something like:
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));

even if you're usign php 5.3 or greater you can use an anonymous method:
$crud->callback_before_insert(function($post_array){
    $post_array['user_id'] = $this->session->userdata('user_id');
    return $post_array;
});

More info: http://www.grocerycrud.com/documentation/tutorial_using_callbacks
About Grocery Crud:
Author: John Skoumbourdis (more about author/library)
Web: GroceryCrud
License: released with dual licensing, using the GPL v3 and the MIT license.
Update 3
Update I've read more carefully your question, thinking functions varible can work for you:
http://php.net/manual/es/functions.variable-functions.php
See the first and second samples here: http://www.php.net/manual/en/language.oop5.php
Still don't know if they will work "outside" your class, but it could.


text:
Q: Error when sending emails through webform using EmailJS. 'The template ID is invalid' I've just recently added EmailJS to my website as a contact me form. I keep getting this error when I send myself a test email:
'bundle.js:1687          POST https://api.emailjs.com/api/v1.0/email/send-form 400'
The template ID is invalid. To find this ID, visit https://dashboard.emailjs.com/admin/templates
Does anyone know how I can fix this??

A: There is a probability that you did not input one of the keys correctly.I realised i had added an extra letter to my service key and after ommiting it it worked perfectly

redpajama_set_name: RedPajamaStackExchange


text:
Q: internet connection interrupted and Limited My internet connection keeps getting interrupted intermittently.  I'm running windows 8 on an Acer Laptop.  I have checked for any connectivity problems and the driver devices and all are running properly. I disconnected and reconnected the modem and wifi. When it gets interrupted the wifi connection indicates "limited."
Any help?

A: First off- you're using wireless. This is the most likely cause of the intermittent connection, but we have no way of knowing until you take it out of the equation.
So you should find an Ethernet cable, disable the wireless card (in your laptop) for a while, and see how your browsing experience compares when you are plugged in directly.
After a few hours of bypassing the wireless connection, post back and let us know how it went. My guess is it will run absolutely perfectly in this scenario.
Then, after confirming whether wireless is indeed the problem- you can stat looking into resolving that issue. If it's not the wireless, that's great too, let us know.
You should be able to at least identify this issue today- although it may take a little longer to actually fix if your wireless is flaky.

A: You might also want to see if anyone is using a microwave oven nearby. I've known of leaky ovens that can cause intermittent problems, and sometimes you may just have to move around to find a better location, or re-orientate your access point aerial.

A: This thread suggests a few solutions, among which:

*

*Installing the Acer wifi drivers (remove them, install from Acer, restart the device);

*Unchecking "allow the computer to turn off this device to save power" in the network card power settings;

*Changing your network setup.

Could well be the driver problem if you think it's Acer-specific, or the power management one if (as in my case) all is back to normal after a little while if left untouched, or faster if woken up.

A: This issue was an issue I've had before relative to my school's wifi and my laptop. 2 solutions I know of. Speaking of, make sure you are using Google Chrome! ;)
Solutions 1 and 3 will require you to be on the current wifi! And solutions 1 & 3 require you to go here first: Right-click the wifi bar in system tray>Open Network and Sharing Center>Public Network.

*

*Change from Public network to Home network of Business network.
Sometimes Public network will restrict some internet access. Go to Public Network, you can change it there. But you possibly may not have the choice.

*Update network drivers.
 Win (Windows Start Key)+W> search "driver">"Device Manager">"Network Adapters">Right Click "Broadcam 802.11n Netork Adapter">"Update Driver Software...">"Browse my computer for driver software">"Let me pick from a list of drivers on my computer">Click once to highlight "Broadcam 802.11n Netork Adapter (Broadcam)">Next
This was personally my favorite solution since it was the one that fixed mine.

*Turn off Auto-Disable Power Saver
Go to "Wi-Fi (Insert name here)">"Properties">"Configure">Power Management">Uncheck "Allow this computer to turn off this device to save power"
Any of these solutions should work. Now it may seem like a lot of information to take in, but it took me longer to type this.
Here are all the image links: http://pastebin.com/qkeEDg4E


text:
Q: Researching for application server supporting Java 8 I am currently trying to find an application server where I could deploy my Java 8 projects. As far as I am aware, due to a bug in Glassfish 4.0 it is not possible to run any Java 8 projects on it, and Tomcat supports Java up to Java 1.7. Are there any other possibilities I am not aware of?

A: Wildfly 8 supports running on java 8's JRE (don't be confused by downloads page saying "Java EE7", this is about EE spec implemented).


text:
Q: Populate dropdown based on another dropdown selection I have two dropdown fields in a JSP page and I have type4 connection with oracle 10g. I want that based on one dropdown selection I want that second dropdown should get filled by fetching data from database based on data in first dropdown automatically just like refreshing that JSP page or showing an alert something like "please wait". How can I do it in JSP-Servlet?
<select name="dropdown1">
    <option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>

My objective is: This below dropdown should get filled base don above selection:
<select name="dropdown2">
    <option value="<%out.println(rollno);%>"><%out.println(rollno);%></option>
</select>

I have found one solution :
<body onload="setModels()">
<% // You would get your map some other way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";

String vehtypeout1="";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("");

      PreparedStatement ps=null;
ResultSet  rs=null;

ps=con.prepareStatement("select c1.name, c2.roll from combo1 c1 left join combo2 c2 on      c1.name=c2.name  order by name");

rs=ps.executeQuery();

while(rs.next()){

vehtypeout=rs.getString(1);

vehtypeout1=rs.getString(2);

map.put(vehtypeout, Arrays.asList((vehtypeout1)));// here i want to show multiple value of vehtypeout1 from database but only one value is coming from databse, how can i fetch multiple value?
map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"}));

      }

rs.close();

ps.close();

con.close();
}

catch(Exception e){

out.println(e);

}
%>

<%! // You may wish to put this in a class
public String modelsToJavascriptList(Collection<String> items) {
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean first = true;
for (String item : items) {
    if (!first) {
      builder.append(',');
    } else {
      first = false;
    }
    builder.append('\'').append(item).append('\'');
}
builder.append(']');
return builder.toString();
}

public String mfMapToString(Map<String,List<String>> mfmap) {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (String mf : mfmap.keySet()) {
  if (!first) {
      builder.append(',');
  } else {
      first = false;
  }
  builder.append('\'').append(mf).append('\'');
  builder.append(" : ");
  builder.append( modelsToJavascriptList(mfmap.get(mf)) );
  }
  builder.append("};");
  return builder.toString();
  }
%>

<script>
var modelsPerManufacturer =<%= mfMapToString(map) %>
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;

for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}

for (i = 0; i< modelArray.length; i++) {
 var text = modelArray[i];
  var opt = new Option(text,text, false, false);
  selectBox.add(opt);
  }
  }

  function setModels() {
  var index = document.myForm.manufacturer.selectedIndex;
  if (index == -1) {
  return;
  }

  var manufacturerOption = document.myForm.manufacturer.options[index];
  if (!manufacturerOption) {
  // Strange, the form does not have an option with given index.
  return;
  }
  manufacturer = manufacturerOption.value;

  var modelsForManufacturer = modelsPerManufacturer[manufacturer];
  if (!modelsForManufacturer) {
  // This modelsForManufacturer is not in the modelsPerManufacturer map
  return; // or alert
  }
  setSelectOptionsForModels(modelsForManufacturer);
}

function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
  return;
}
// alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
  <% boolean first = true;
     for (String mf : map.keySet()) { %>
      <option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option>
  <%   first = false;
     } %>
</select>

<select onChange="modelSelected()" id="models">
  <!-- Filled dynamically by setModels -->
</select>

But i am getting only one value in vehtypeout1 where databse contains multiple values. How can i do it?

A: Using jquery, bind a function to the onchange event of "combobox1"    select box.
In that function, send an ajax request (you can use    jquery get function) to a jsp page in your server.
In that jsp page,    retrieve the relevant data from database and send the response back    to the client with those data (may be you need to use JSON format).
In the jquery get function, you can add a callback function to    execute after server send you back the response.
Inside that call    back function, write the code to fill "combobox2" using response data    sent by the server.

A: You'll want an ajax call like below. Have your function that is called return a html-string of
"<option value='myVal'>myText</option>".
The jQuery/Ajax would be:
$("#ddl1").change(function() {
     $.ajax({
          url: "URLyouwanttoaddress",
          data: "myselection=" + $("#ddl1").val();
          type:"get",
          success: function(data) {
                     $("#ddl2").html(data);
          }
      });
});


text:
Q: jQuery Cycle2 multiple slideshow nav I need to work the first slider with a navigation and the second automatically but click on the navigation buttons run both sliders. Code here:

<button data-cycle-cmd="prev">Prev</button>
<button data-cycle-cmd="next">Next</button>

 div">

content

content

content

content

 div"
    >

content

content

content

content

A: When you declare a class with the name 'cycle-slideshow', you're auto initializing your slideshow and this will treat all containers with that class the same way, like any other class would. What you need to do is manually initialize your slideshow by declaring a different class like this:

Then your JQuery code must have these simple lines before you manipulate anything under your custom class for the slidesow:
//Initialize slide1
$('.slide1').cycle();

//Initialize slide2
$('.slide2').cycle();

After that you can do everything as you would normally do with the cycle-slideshow...
Hope that helps you!
Ex:
$('.slide1').cycle('goto', 4);


text:
Q: ebs "available" volume to attach I am trying to attach available ebs volume when ec2 instance is starting up.
I am saving the available volume list in a variable and running for loop to attach but it's not working. Kindly advice
Value stored in $vid variable
vol-0f1afab1e58853cf4
vol-0cda4ca53406a13fa
 foreach ($volumeid in $vid) {
                            $instanceId = Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/instance-id
                            ec2-attach-volume --instance-id $instanceId --volume-id $volumeid  }
              </powershell>

A: 1) You are missing the --device to attach the volume to.
2) Look in the instance logfile which is available in the AWS console and add the error messages that are displayed to your post if #1 does not solve your issue.
3) Have you assigned a role to the EC2 instance with permissions to access and mount EBS volumes? Verify this using the AWS CLI after the instance runs or using PowerShell with your scripts.
4) Under Windows, attached volumes often have to be placed "online" before they can be accessed. After attaching a volume, run diskmgmt.msc to verify if this is necessary. Generally this only happens the first time Windows sees a new disk (volume). Diskpart.exe and diskmgmt.msc have commands for bringing a volume online.


text:
Q: swipeEnabled prop of nested TabNavigator inside Stack Navigator(React Navigation) crashes the app in IOS emulator when set to true

const NavBar = TabNavigator({
  HamburgerMenu: {
    screen: HamburgerScreen,
    navigationOptions: {
    tabBarIcon: ({ tintColor }) => <Icon name='bars' style={styles.iconStyle}/>
    }
  },
  Landing: {
    screen: LandingScreen,
    navigationOptions: {
      tabBarIcon: ({ tintColor }) => <Icon name='home' style={styles.iconStyle}/>

    }
  },
  SearchMenu: {
    screen: SearchScreen,
    navigationOptions: {
      tabBarIcon: ({ tintColor }) => <Icon name='search' style={styles.iconStyle}/>

    }
  },
  CategoryMenu: {
    screen: CategoryScreen,
    navigationOptions: {
      tabBarIcon: ({ tintColor }) => <Icon name='th-large' style={styles.iconStyle}/>

    }
  },
  NotificationMenu: {
    screen: NotificationScreen,
    navigationOptions: {
      tabBarIcon: ({ tintColor }) => <Icon name='bell-o' style={styles.iconStyle}/>

    }
  },
  InboxMenu: {
    screen: InboxScreen,
    navigationOptions: {
      tabBarIcon: ({ tintColor }) => <Icon name='comments' style={styles.iconStyle} />,
      tabBarVisible: false
    }
  },

}, {
  tabBarPosition: 'top',
    swipeEnabled:true,
    initialRouteName: 'Landing',
    tabBarOptions: {
    showIcon: true,
    showLabel:false,
    tinColor: '#405ac2',
    activeTintColor: '#eee',
    upperCaseLabel: true,
    indicatorStyle: {
        backgroundColor: '#ccc'
    },
    style: {
        backgroundColor: "#405ac2"
    },
    tabStyle : {
        backgroundColor: 'transparent'
    }
}
  ,
}

);

I am building a react-native application using react-navigation and this is my code for TabNavigator(nested inside StackNavigator) where swipe gesture for switching between the tabs works well on android but is not working on ios emulator.So I used swipeEnabled:true in my tabbar config but the app crashes due to it.
Thanks in Advance!


text:
Q: Port Forwarding on Windows 10 using "HNetCfg.NATUPnP" I am using Delphi XE3 and trying to create a port forwarding (UPnP) using "HNetCfg.NATUPnP". After some research, here is what I got so far:
function PortMapAdd(const ExtPort, IntPort: DWORD;
  const IPAdd, Protocol, Descript: string): Boolean;
var
  Nat, Ports: Variant;
begin
  Result := False;
  try
    CoInitialize(nil);
    try
      Nat := CreateOleObject('HNetCfg.NATUPnP');
      Ports := Nat.StaticPortMappingCollection;
      if not VarIsClear(Ports) then
      begin
        Ports.Add(ExtPort, UpperCase(Protocol),
          IntPort, IPAdd, True, Descript);
        Result := True;
      end;
    finally
      CoUninitialize;
    end;
  except
    on E:Exception do raise;
  end;
end;

The above code works perfectly on Windows 7, but on Windows 10 VarIsClear always returns true.
Application-UPnP is enabled in my router configuration and UPnP User Interface (network discovery) is enabled in Windows 10.
Please, is there any other configuration I must check? Or maybe the code is not compatible with Windows 10? I appreciate any help, thanks!


text:
Q: How to display desired date and time when accessing timestamp object using node-pg I am accessing the timestamp object from a database using node-pg pool.query() and displaying it on a web page using the following code within an ejs file:
<%= obj.date %>

The result is Fri Aug 13 2021 08:22:18 GMT-0400 (Eastern Daylight Time) which is not how I want it to be displayed (in my database this value is stored as 2021-08-13 08:22:18. I've tried using JSON.stringify as follows:
<%= JSON.stringify(obj.date) %>

But I get the following result  "2021-08-13T12:22:18.179Z". How am I able to get the time value to be displayed as T08:22:18  instead of  T12:22:18? I'm assuming that it is using a different timezone when calling JSON.stringify for some reason but I just don't understand why it wouldn't stay as the time displayed in the database and in the obj.date variable.


text:
Q: Aurelia ref=theCanvas is undefined when i will render more charts in a repeat.for loop The problem is that a ref it doesn't work in a repeat.for loop. if I remove the repeat.for then it works fine, that is, it chart is rendered. I suspect that I have a bug with the life-cycle of the components. I first get data in the activated method and in the method attachment I call the method that gets the canvas reference to render the chart.
The error message is the following:
"TypeError: _this.theCanvas is undefined"
Here the view:
<template>

                Historie Filialen an allen Standorte

                        <button name="defaultbutton" type="button" click.delegate="changeTimeWindow(1)" class="btn btn-default">1h</button>
                        <button type="button" click.delegate="changeTimeWindow(8)" class="btn btn-default">8h</button>
                        <button type="button" click.delegate="changeTimeWindow(24)" class="btn btn-default">1d</button>
                        <button type="button" click.delegate="changeTimeWindow(120)" class="btn btn-default">5d</button>

${device.boardType}

                                                ${device.locationName} ${device.room}

                                                <canvas class="chart" ref=theCanvas></canvas>

</template>

here the view-model:
import 'aws-sdk/dist/aws-sdk';
import * as _ from "lodash";
import * as Chart from "chart.js"; // TODO: use @types/chartjs (then the null check below is not needed anymore)
import * as Moment from "moment";
import { AmbientDevice } from "./model/ambient-device";
import { DeviceData } from "./model/device-data";
import { DeviceLocDataDTO } from "./dto/device-loc-data-dto";
import { autoinject } from 'aurelia-framework';
import { View } from "aurelia-framework";

@autoinject( DeviceData )
@autoinject( DeviceLocDataDTO )
export class HistoricalViewAll {

    private location: string;
    private deviceSelection: string;
    private devices: Array<DeviceData> = new Array<DeviceData>();
    private timewindowHours: number = 8;
    private findDevice: DeviceData = new DeviceData();
    private theCanvas;
    private ctx: CanvasRenderingContext2D;

    constructor( private deviceDataDTO: DeviceLocDataDTO, private deviceData: DeviceData ) {
        console.log( "HistViewAll constructor called..." );
        ..
        ..
        ..
        ..

        // init necessary to show correct boardType and deviceName in device-container
        this.devices.push(this.deviceData);
        //this.theCanvas = new HTMLCanvasElement();

        this.location = "Zurich";
        this.deviceSelection = "allDevices";
    }

    activate( params, routeConfig, navigationInstruction ) {
        //necessary to get first the data before UI will be renderet...
        return this.deviceDataDTO.getReqAllDeviceDataFromAllLocation();
    }

    created( owningView: View, myView: View ) {
        console.log( "created() call in HistoricalViewAll" );
        console.log( owningView );
        console.log( myView );
    }

    bind(bindingContext: Object, overrideContext: Object) {
        console.log( "HistoricalViewAll is bindet..." );
        console.log(bindingContext);
        console.log(overrideContext);
        //this.devices = this.deviceDataDTO.getDeviceLocationList();
        console.log(this.devices);
        console.log(bindingContext);
    }

    attached() {
        console.log( "HistoricalViewAll is attached..." );
        this.devices = this.deviceDataDTO.getDeviceLocationList();
        this.changeTimeWindow( this.timewindowHours );
    }

    getDevices() {
        return this.devices;
    }

    changeTimeWindow( hours: number ) {
        this.timewindowHours = hours;

        this.devices.forEach(( device, i, arr ) => {
            //const ctx: CanvasRenderingContext2D = ( document.getElementById( 'chart-' + device.location_id ) as any ).getContext( '2d' );
            //console.log( this.ctx );
            //console.log( document.getElementById( 'chart-' + device.location_id ) );
            //if (typeof this.theCanvas !== null) {
                this.ctx = this.theCanvas.getContext( '2d' );
                this.drawDevice( this.ctx, device.locationName );
            //}
        } );
    }

    changeTimeWindowForOneDevice( hours: number, deviceKey: string, ctx: CanvasRenderingContext2D ) {

        this.timewindowHours = hours;

        Object.assign( this.findDevice, this.devices.find( device => device.device_id === deviceKey ) );
        this.drawDevice( ctx, deviceKey );
    }

    drawDevice( ctx: CanvasRenderingContext2D, devicename: string, correctionFactor: number = 1 ) {

    // the chart

    }

}

please any suggestion what I make wrong?

A: I think you can define some canvases=[] in your code, and then use something like:
canvases.ref="canvases[$index]"


text:
Q: Getting debug assertion errors in program I'm just trying to create a simple program to practice some C++, but I'm unsure as to why I'm getting this current error. The output provides my desired outcome, but after succesful output I keep getting debug assertion errors. Is it a memory leak or something? I have no idea what it could be.
Header:
#include <iostream>
class Record {
    char* rec;
public:
    Record();
    Record(const char*);
    Record(const Record&);
    ~Record();
    void display(std::ostream&);
    Record& operator=(const char*);
};

std::ostream& operator<<(std::ostream& os, Record& r);

cpp:
#define _CRT_SECURE_NO_WARNINGS
#include "Record.h"

Record::Record() {
    rec = nullptr;
}

Record::Record(const char* s) {
    if(s != nullptr) {
    rec = new char[strlen(s) + 1];
    strcpy(rec, s);
    } else {
    *this = Record();
    }
}

Record::Record(const Record& r) {
    *this = r;
}

Record::~Record() {
    delete [] rec;
}

void Record::display(std::ostream& os) {
    os << rec;
}

Record& Record::operator=(const char* s) {
    if (rec != s)
    delete [] rec;
    if(s != nullptr) {
    rec = new char[strlen(s) + 1];
    strcpy(rec, s);
    }
    else {
    rec = nullptr;
    }
    return *this;
}

std::ostream& operator<<(std::ostream& os, Record& r) {
    r.display(os);
    return os;
}

Main:
#include <iostream>
#include "Record.h"
using namespace std;

int main() {
    Record rec1("inheritance"), rec2 = rec1;

    cout << rec1 << endl;
    cout << rec2 << endl;
    rec1 = "overloading";
    cout << rec1 << endl;
    rec2 = rec1;
    cout << rec2 << endl;

    return 0;
}

A: I'll put this as an answer, since it is important in how your class behaves and concluding that "everything is working" is one of the reasons why C++ is not that easy of a language.
The main() program you wrote does not test something very simple.  Look here:
int main() {
   Record rec1("inheritance");
   Record rec2 = rec1;
}

If you debug this code, you will see that this function is called for the rec2 = rec1 line:
Record::Record(const Record& r) {
    *this = r;
}

Ok, so the copy constructor is called.  But what does this line of code do?:
*this = r;

It does not call the assignment operator that you wrote that takes a const char*.  Instead, it calls the default assignment operator that takes a Record&,  The problem is that -- you didn't write one.  So what winds up happening is that the compiler generated assignment operator is called, which does a shallow copy.
In the main() program, when main() returns, both rec2 and rec1 will have their respective destructors called.  The problem is that rec2 will delete the pointer value, ok, but then rec1 will delete the same pointer value (no good), causing a corruption of the heap.  I ran your code with Visual Studio 2013, and immediately an assertion dialog popped up when main() returned.
So you need to write a user defined assignment operator that takes this signature:
Record& Record::operator=(const Record&)

A: Don't call the assignment operator, *this =, from the const char* and copy constructors. This is generally bad practise. In your case, because you haven't defined an assignment operator that takes a const Record&, the default assignment operator is called, which simply copies the pointer and does a shallow copy, meaning that both Records will have the same pointer in their recs -- this was pointed out and described in detail in PaulMcKenzie's answer. However even if you did define that assignment operator, if you did the same thing as your existing assignment operator, the member variable rec would be uninitialized and deleteing it causes undefined behaviour.
See Calling assignment operator in copy constructor for a discussion, and what you could do instead of calling the assignment operator from a constructor.
Edit
One way to make your program work would be for your constructors to look something like this.
void Record::InitFrom(const char* s)
{
    if(s != nullptr) {
        rec = new char[strlen(s) + 1];
        strcpy(rec, s);
    } else {
        rec = nullptr;
    }
}

Record::Record(const char* s) {
    InitFrom(s);
}

Record::Record(const Record& r) {
    InitFrom(r.s);
}

You could also incorporate the new InitFrom method into your assignment operator.
Record& Record::operator=(const char* s) {
    if (rec != s) { // this test only really necessary if assigning from Record
        delete [] rec;
        InitFrom(s);
    }
    return *this;
}

You also might have an assignment operator that takes a const Record&. You do need the destructor.

A: It's difficult to say for sure what's going one without seeing the value with which you have initialized the Record.  Based on your description of the program's behavior and the code, I can think of one possible explanation of what's happening, although there might be others.
My guess is the std::ostream is handing the char* like a c-string, which expects a sequence of charcters terminated by a \0.  If your Record has been initialized with a sequence of characters that doesn't terminate with a \0, it would keep doing pointer incrementation, streaming out a character at a time, until it reaches an invalid section of memory.  This will cause undefined behaviour, which might trigger a debug assertion in your implementation of the standard (i.e. the compiler you are using).
I provide you this guess as you say this is a learning exersize, so I don't question your class design but try to help you understand what's happening.  The comments elsewhere are quite relevant however.  If you have record store a std::string instead of a character array, this problem (and several other possible problems) will not occur.  That answer may not help you lean what you are trying to learn of course.


text:
Q: Encode downstream messages in Netty's IO worker threads I'm using io.netty-3.9.0.Final with protobuf to create and send messages with large size. I noticed that serialization and writing to CodedOutputStream takes a lot of time, and slows down my application thread.
I expected this kind of work to be processed in Netty's IO worker threads. The Channel.write(Object) documentation says: "Sends a message to this channel asynchronously." Besides, upstream messages decoding occurs in I/O worker thread.
So how can I move encoding from Channel.write() invokation thread to Netty's IO worker threads?
The ChannelPipelineFactory#getPipeline() method looks like this:
public ChannelPipeline getPipeline() throws Exception {
    final ChannelPipeline pipeline = Channels.pipeline();

    // Decoder
    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
    pipeline.addLast("protobufDecoder", new ProtobufDecoder(MessageProto.pMessage.getDefaultInstance()));
    pipeline.addLast("protoMessageDecoder", new ProtoMessageDecoder());

    // Encoder
    pipeline.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
    pipeline.addLast("protobufEncoder", new ProtobufEncoder());
    pipeline.addLast("protoMessageEncoder", new ProtoMessageEncoder());

    pipeline.addLast("handler", upstreamHandler);

    return pipeline;
}

A: Unfortunately Netty 3.x doesn't work like this. It does send a message asynchronously but the asynchronous part kicks in if Netty is unable to write to the network buffers immediately. In this case it queues the message and will eventually write it out using the I/O thread.
I believe your best option is to upgrade to Netty 4 which I understand has the behaviour you desire. Otherwise you could try adding an OrderedDownstreamThreadPoolExecutor to your pipeline. The write still won't be processed by the I/O thread, but it should ease the pressure on your application thread.


text:
Q: Android dim screen after FLAG_TURN_SCREEN_ON I have Activity that is started from GCM with FLAG_TURN_SCREEN_ON
Below is the code snippet:-
@Override
    public void onAttachedToWindow() {

        super.onAttachedToWindow();
        addFlags();
    }

    private void addFlags() {
        //Screen On
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

    private void clearFlags() {
        //Don't forget to clear the flags at some point in time.
        getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {

        if (!hasFocus) {
            clearFlags();
        }

        super.onWindowFocusChanged(hasFocus);
    }

After device wake up I want to schedule screen DIM (after 15 sec I use AA framework). I have try to clearFlags() after 15 sec but nothings changed.
@UiThread(delay = 15000)
        void dimDisplay() {
            if (!isFinishing()) {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.screenBrightness = 0.0f;// i needed to dim the display
                getWindow().setAttributes(params);
            }
        }

and after user touch screen screenBrightness=1
@Touch
    void container() {
        if (!isFinishing()) {
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.screenBrightness = 1f;
            getWindow().setAttributes(params);
        }
    }

Do you know more clean solution of the problem.. this code DIM display only one time. And I want to avoid usage of deprecated PowerManager.SCREEN_DIM_WAKE_LOCK
/** @deprecated Most applications should use
     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
     * of this type of wake lock, as it will be correctly managed by the platform
     * as the user moves between applications and doesn't require a special permission.
     */
    @Deprecated
    public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;


text:
Q: Random and unique array's string to list I can't get to work a random game per
. Each game should be unique.

var randomGames = ['Life is Strange', 'Titanfall', 'Call of Duty', 'Tales from the Borderlands', 'Assassin\'s Creed', 'Tomb Raider', 'FIFA']

These are the games that James like the most

...

...

...

A: You can do something like this with jQuery.

var randomGames = ['Life is Strange', 'Titanfall', 'Call of Duty', 'Tales from the Borderlands', 'Assassin\'s Creed', 'Tomb Raider', 'FIFA'];

var filteredArr = [...new Set(Array.from(randomGames))]

for(var i = 0; i < filteredArr.length; i++) {
  $('.list-group').append('
' + filteredArr[i] + '
');
}

These are the games that James like the most

Or just pure JS.

var randomGames = ['Life is Strange', 'Titanfall', 'Call of Duty', 'Tales from the Borderlands', 'Assassin\'s Creed', 'Tomb Raider', 'FIFA'];

var filteredArr = [...new Set(Array.from(randomGames))]

for(var i = 0; i < filteredArr.length; i++) {
  var node = document.createElement("li");
  var textnode = document.createTextNode(filteredArr[i]);
  node.appendChild(textnode);
  document.getElementById("list-group").appendChild(node);
}

These are the games that James like the most

A: Pick random item from array, add it as current li text and remove it from array.

var randomGames = ['Life is Strange', 'Titanfall', 'Call of Duty', 'Tales from the Borderlands', 'Assassin\'s Creed', 'Tomb Raider', 'FIFA']
var li = document.querySelectorAll('li')

for(var i = 0; i < li.length; i++) {
  var n = parseInt(Math.random(randomGames.length) * randomGames.length)
  li[i].textContent = randomGames[n]
  randomGames.splice(n, 1)

}

These are the games that James like the most

...

...

...

A: This will randomize the array and filter out duplicates, then add the games as new li elements to the ul (which I gave an id for easier access):

var randomGames = ['Life is Strange', 'Titanfall', 'Call of Duty', 'Tales from the Borderlands', 'Assassin\'s Creed', 'Tomb Raider', 'FIFA'];

// randomize the array:
// (shuffle function taken from http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array)

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

randomGames = shuffle(randomGames);

// remove duplicates
randomGames.filter(function (elem, index, self) {
  return elem !== "" && index == self.indexOf(elem)
});

// add the games to the list
var gameslist = document.getElementById('gameslist');
for (var i = 0; i < randomGames.length; i++) {
  var newLi = document.createElement('li');
  newLi.className = 'james list-group-item';
  newLi.textContent = randomGames[i];
  gameslist.appendChild(newLi);
}

These are the games that James like the most


text:
Q: MapKit doesn't center on right location I have a problem with my MapKit in Swift. I want it to center on a specific coordinate, but the default center doesn't change at all. The first (and most important part of) my viewController.swift file looks like this:
import UIKit
import Parse
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    var map : MKMapView! = MKMapView()
    var locManager:CLLocationManager!

    @IBOutlet var txtUsername: UITextField!
    @IBOutlet var txtPassword: UITextField!

    override func viewDidLoad() {
        var centerCoordinate = CLLocationCoordinate2DMake(41.8796677, -87.6198131)

        var mapSpan = MKCoordinateSpanMake(0.01, 0.01)

        var mapRegion = MKCoordinateRegionMake(centerCoordinate, mapSpan)

        self.map.setRegion(mapRegion, animated: true)

        locManager = CLLocationManager()
        locManager.delegate = self
        locManager.desiredAccuracy = kCLLocationAccuracyBest
        locManager.requestAlwaysAuthorization()
        map.showsUserLocation = true
        super.viewDidLoad()
    }

What could be the reason that the center of the map is not changed by the variable 'centerCoordinate'?

A: There are func's that are called automatically when the map is in use.  One of them is
func mapViewDidFinishLoadingMap(mapView: MKMapView)
Try doing this.
  func mapViewDidFinishLoadingMap(mapView: MKMapView) {
    map.setRegion(mapRegion, animated: true)
}

If this doesn't work type func mapView and look in the list and find one you think might but I feel this is where it needs to be.

A: In ViewController.swift, find viewDidLoad and add the following to the end of the method:
// set initial location in Honolulu
let initialLocation = CLLocation(latitude: 21.282778, longitude: -157.829444)

You'll use this to set the the starting coordinates of the map view to a point in Honolulu.
When you are trying to tell the map what to display, you can't just give a latitude and longitude. That's enough to center the map, but you need to specify the rectangular region to display to get a correct zoom level too.
Add the following constant and helper method to the class:
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
  let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
    regionRadius * 2.0, regionRadius * 2.0)
  mapView.setRegion(coordinateRegion, animated: true)
}

The location argument is the center point. The region will be have north-south and east-west spans based on a distance of regionRadius – you set this to 1000 meters (1 kilometer), which is a little more than half a mile. You then use regionRadius * 2.0 here, because that works well for plotting the public artwork data in the JSON file.
setRegion tells mapView to display the region. The map view automatically transitions the current view to the desired region with a neat zoom animation, with no extra code required!
Back in viewDidLoad, add the following line to the end of the method:
centerMapOnLocation(initialLocation)

This will call the helper method to zoom into initialLocation on startup.
Build and run the app, and now it should zoom in to the heart of Waikiki :]
Font: http://www.raywenderlich.com/90971/introduction-mapkit-swift-tutorial

A: Swift 5.
In the MKMapViewDelegate, I recommend using the regionDidChangeAnimated method and setting the region of the mapView based on the user's coordinate. Change the span according to your use case.
extension MapViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        mapView.setRegion(MKCoordinateRegion(center: userLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
    }
}


text:
Q: Whether one could use the verb drink with ice-cold tea? I have the idea that we need to say "I took (not drank) my tea (or coffee) . . ." because we consume these beverages hot.
If my idea is true, should we use take even when referring to cold tea or coffee?

A: Any liquid can use "drink". Even dangerous things. Temperature does not matter.

Coke, tea, water, bleach, milk, juice, ...

"take" is either used literally, or to refer to the consumption of medicine.

Take some Tylenol. I hope it will make you feel better.

Food often uses "eat".

I ate sausages, he eats corn, Manny is eating yogurt, Jacqueline had eaten a large turkey, ...

Any food/drinks also often use "have" to refer to their consumption:

had breakfast, had a glass of water, had some tea, will have ice cream, have steak for dinner, had some cereal, will have a coke, have hot chocolate, ...


text:
Q: How to check if my ISP is changing in any way a request to Google's DNS? The problem is that superuser.com, stackexchange.com and many other sites didn't work.
When I was debugging the problem, I tried nslookup:
user@host:~$ nslookup superuser.com 8.8.8.8
Server:     8.8.8.8
Address:    8.8.8.8#53

** server can't find superuser.com: SERVFAIL

user@host:~$ nslookup superuser.com 8.8.4.4
Server:     8.8.4.4
Address:    8.8.4.4#53

** server can't find superuser.com: SERVFAIL

But then, using this page: http://www.kloth.net/services/nslookup.php
... here is the nslookup result for superuser.com from server 8.8.8.8, querytype=A :

 DNS server handling your query: 8.8.8.8
 DNS server's address:  8.8.8.8#53

 Non-authoritative answer:
 Name:  superuser.com
 Address: 104.16.32.193
 Name:  superuser.com
 Address: 104.16.125.192
 Name:  superuser.com
 Address: 104.16.126.192
 Name:  superuser.com
 Address: 104.16.127.192
 Name:  superuser.com
 Address: 104.16.33.193

So there was clearly a problem trying to reach Google's DNS IP. I then made a telnet to see if port 53 was open in my router:
user@host:~$ telnet 8.8.8.8 53
Trying 8.8.8.8...
Connected to 8.8.8.8.
Escape character is '^]'.
Connection closed by foreign host.

Everything is working, so my last suspect is that the ISP is hijacking the IP somehow.
How could I test it?
EDIT:
mtr trace:
 Host                                                          Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 192.168.2.254                                               0.0%   120    0.5   0.4   0.2   0.7   0.0
 2. 170.210.178.1                                               0.0%   120    1.1   1.0   0.7   1.3   0.0
 3. riu-unpaz-100M.BUENOS-AIRES.riu.edu.ar                      0.0%   120    1.8   4.4   1.7 182.0  18.3
 4. rgda3-dc-sol.riu.edu.ar                                     0.0%   119    2.8   3.2   2.1   7.1   0.8
 5. google-riu.riu.edu.ar                                       0.0%   119    2.3   2.5   2.0  16.1   1.5
 6. 66.249.95.205                                               0.8%   119    2.6   2.8   2.4   3.6   0.0
 7. google-public-dns-a.google.com                              0.0%   119    2.5   2.5   2.2   3.2   0.0


text:
Q: System.getProperty("line.separator") and " \n " Causes listview not to populate In my app I have a List view,
The view is populated by an array of strings
Here is the code and explanation to help you guys
So the string is
StaffList= Client + " Rates: " + Rates + " " + Staff + " Budget Hours: " + BudgetHoursPassData + " Member Budget: " + MemberBudgetPassData + "Notes" + NotesPassData;

That String is then added to an Array
StaffArray.add(StaffList);

This Array is then passed using intents to another activity and displayed in the list view
public  void PassData(){
    Intent GoToReport=new Intent(getApplicationContext(), createProject.class);
    MemberBudgetPassData= MemberBudget.getText().toString();
    BudgetHoursPassData = budgetHours.getText().toString();
    NotesPassData= Notes.getText().toString();

    Toasty.info(popupActivity.this, StaffArray.toString(),Toasty.LENGTH_LONG).show();

    GoToReport.putStringArrayListExtra("Array",StaffArray);
    startActivity(GoToReport);
    Animatoo.animateCard(popupActivity.this);
}

Here is the adapter
final ArrayAdapter arrayAdapter =new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Array);

if (Array == null){
    Toasty.info(createProject.this,"Select a Staff Memebr",Toasty.LENGTH_LONG).show();
}else{
    StaffListView.setAdapter(arrayAdapter);
}

Now You can go back to the same activity and add a second Item to the array
public  void DialogBuilder(){
    Intent GoToReport=new Intent(getApplicationContext(), popupActivity.class);
    GoToReport.putStringArrayListExtra("Array", Array);
    startActivity(GoToReport);
    Animatoo.animateCard(createProject.this);
}

So Now My problem I am having is that The list populates fine with the above code
But As Soon As I add a System.getProperty("line.separator") or " \n " to the string
like
StaffList= Client + "\n"+ " Rates: " + Rates + "\n"+ " " + Staff + "\n"+ " Budget Hours: " + BudgetHoursPassData + "\n"+ " Member Budget: " + MemberBudgetPassData + "\n"+ "Notes" + NotesPassData;

The second/third etc. item in the list does not populate, So only the first Item is displayed in the List BUT without the /n or System.getProperty("line.separator") All the items are displayed

A: I solved this By changing the Listview to A Spinner
 and calling a spinner adapter
  StaffList.setAdapter(new ArrayAdapter<>(createProject.this, android.R.layout.simple_spinner_dropdown_item, Array));

A: Try Environment.NewLine instead.


text:
Q: how to fix the corrupted base environment I accidentally install a lot of packages using pip install -r requirements.txt under base environment. Then I tried to pip uninstall, but it seems that the uninstalling process is unsuccessful.
I am using the miniconda on Windows. How can I recover the base environment to clean state? Or do I have to reinstall miniconda to remove the whole base environment?

A: Unlike Conda, Pip doesn't seem to track revisions and Conda doesn't actively what Pip does (it passively detects installed packages in the lib/python*/site-packages).
One idea around that conundrum might be to export a --from-history YAML:
conda env export -n base --from-history

That will include a section of pip: installed packages and you could use that as the list of packages to remove. It could still be problematic if, for example, Pip installed a newer version of a package from PyPI that is essential for the conda package to function.
If truly broken, you can also restore basic Conda functionality by using a standalone tool like Micromamba. See https://stackoverflow.com/a/75381135/570918, but you'll need to check the docs for Windows installation steps.


text:
Q: Separate forms, 2 actions in specific order I've got a form asking for user input.  The input should be a name which exists in my database.

* required field.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name: <input type="text" name="name" value="<?php echo $name;?>">
    * <?php echo $nameErr;?>

    <input type="submit" name="login" value="Login">
</form>

I'm trying to first check user input, and then if the input is clean, send the user off to another site.
This is what I'm using to scrub the input:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
}

Then I would like to send to the next site after querying to my database and receiving an ID:
<form action = "http://website.com/~username/site.php" method="get">
    Name: <input type="text" name="name">

    <Input type="submit">
</form>

How should I go about doing this?

A: Use header() function to achieve your goal
header('Location: yourfile.php?id=' . $yourIdValue); // adopt to your needs

In your target script fetch id with
$id = $_GET['id'];


text:
Q: Does ASP.net identity uses open id connect? I want to use OpenID for my authentication. Does ASP.net identity uses google open id connect? because google says:

Important: Google has deprecated OpenID 2.0 and will shut it down
  after a migration period. If your app uses OpenID 2.0, you must
  migrate your app by the shutdown date April 20, 2015, as shown in the
  migration timetable.

A: It can use both:

Microsoft.Owin.Security.Google - Contains middlewares to support Google's OpenId and OAuth 2.0 authentication workflows.

Source.


text:
Q: Tocar uma musica por vez em uma TAG de Audio no HTML5 que é criada dinamicamente com mesmo ID Bom dia!
Estou com uma dúvida referente a estar trabalhando com áudio em uma aplicação Web, tenho um App feito em Python utilizando Flask que varre um determinado diretório que possui vários MP3, sendo assim eu crio dinamicamente as DIV contendo os Players  de Áudio e os mesmos possuem os mesmo ID.
Segue o Exemplo:

                    library_music
                     audio1.mp3

                            Your browser does not support the audio tag.

                    library_music
                     audio2.mp3

                            Your browser does not support the audio tag.

                    library_music
                     audio3.mp3

                            Your browser does not support the audio tag.

A aplicação funciona perfeitamente, porém preciso que seja tocado uma única musica por vez, sendo assim acredito que o caminho seja utilizar JavaScript porém não sei como proceder neste caso que as TAGS são criadas dinamicamente com o mesmo ID.
Se alguém puder dar uma força eu agradeço!


text:
Q: How to configure PyCharm to add leading periods to relative imports (PEP328)? When using the refactoring tools in PyCharm (for instance extracting a class), it adds statements like from concept import Concept, that I have to manually change to from .concept import Concept for PEP328-compability. How can I configure PyCharm to add relative import statements correctly (with leading dots)?
Tried to look in Preferences, esp. under "Code Style", where there is a tab called "Imports", but couldn't find a setting for this. Under "Project Structure", I did set the <package> folder to be a "Sources" folder.
<project>
├── <package>
│   ├── __init__.py
│   ├── concept.py
│   ├── job.py
│   └── <etc..>.py
├── setup.py
└── tests
    ├── __init__.py
    ├── <etc..>.py
    ├── test_concept.py
    └── test_job.py


text:
Q: Adding a "more" Button I'm trying to add a "load more" button and limit the results below, so that there aren't 1000 things loading all at once in the portfolio page, here: http://typesetdesign.com/portfolio/
My knowledge of PHP isn't very good, so I'm not sure what I'm supposed to do. I know I could limit the projects here:
<?php query_posts( 'post_type=project&posts_per_page=200' );

But how would I then load more if I limited that result?
Here is the page coding for that entire page:

<?php $page_skills = get_post_meta($post->ID, "_ttrust_page_skills", true); ?>

<?php if ($page_skills) : // if there are a limited number of skills set ?>
    <?php $skill_slugs = ""; $skills = explode(",", $page_skills); ?>

    <?php if (sizeof($skills) > 1) : // if there is more than one skill, show the filter nav?>

<?php _e('All', 'themetrust'); ?>

            <?php
            $j=1;
            foreach ($skills as $skill) {
                $skill = get_term_by( 'slug', trim(htmlentities($skill)), 'skill');
                if($skill) {
                    $skill_slug = $skill->slug;

                    $skill_slugs .= $skill_slug . ",";
                    $a = '
';
                    $a .= $skill->name;
                    $a .= '
';
                    echo $a;
                    echo "\n";
                    $j++;
                }
            }?>

        <?php $skill_slugs = substr($skill_slugs, 0, strlen($skill_slugs)-1); ?>
    <?php else: ?>
        <?php $skill = $skills[0]; ?>
        <?php $s = get_term_by( 'name', trim(htmlentities($skill)), 'skill'); ?>
        <?php if($s) { $skill_slugs = $s->slug; } ?>
    <?php endif;

    $temp_post = $post;
    $args = array(
        'ignore_sticky_posts' => 1,
        'posts_per_page' => 200,
        'post_type' => 'project',
        'skill' => $skill_slugs
    );
    $projects = new WP_Query( $args );

else : // if not, use all the skills ?>

<?php _e('All', 'themetrust'); ?>

        <?php $j=1;
        $skills = get_terms('skill');
        foreach ($skills as $skill) {
            $a = '
slug.'">';
            $a .= $skill->name;
            $a .= '
';
            echo $a;
            echo "\n";
            $j++;
        }?>

    <?php
    $temp_post = $post;
    $args = array(
        'ignore_sticky_posts' => 1,
        'posts_per_page' => 200,
        'post_type' => 'project'
    );
    $projects = new WP_Query( $args );

endif; ?>

<?php  while ($projects->have_posts()) : $projects->the_post(); ?>

    <?php
    global $p;
    $p = "";
    $skills = get_the_terms( $post->ID, 'skill');
    if ($skills) {
       foreach ($skills as $skill) {
          $p .= $skill->slug . " ";
       }
    }
    ?>
    <?php get_template_part( 'part-project-thumb'); ?>

<?php endwhile; ?>
<?php $post = $temp_post; ?>

Thanks so much, any input is a help!

A: Edit
Using Tables with pagination bootstrap style http://datatables.net/examples/basic_init/multiple_tables.html
Massive data base with pagination take a look here: https://stackoverflow.com/a/3707457/2293454
I didn't see your site, now I have, what you might need is something like this:
https://stackoverflow.com/a/21408418/2293454

as you can see that example has a limiter iMyLoadLimit = 5, so, wen the user scroll down the page, it will load more based on the total number of fetched data, if you load 100 articles or 1000, they will be divided by the limiter in the java, the result will be that every time the user scroll down it will display the next 5 or whatever number you want to display...
I hope that helps...

A: You need pagination (server side) and might want infinite scrolling (client side)
You may want to look at:
Simple PHP Pagination script
http://jscroll.com/
How to paginate query results for Infinite Scroll?


text:
Q: Problems uploading data from CSV autodesk forge Good Morning,
I'm using Forge Autodesk Data visualization API. I'm trying to upload the CSV data that is exactly in this format https://github.com/Autodesk-Forge/forge-dataviz-iot-reference-app/blob/main/server/gateways/csv/Hyperion-1.csv, but what i get is internal error 500
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
 Hyperion.Data.Adapter.js?73b8:543

SyntaxError: Unexpected token s in JSON at position 0 Hyperion.Data.Adapter.js?73b8:543
eval    @   Hyperion.Data.Adapter.js?73b8:543

It could be tha the problem is in the format of the csv file? this are my enviromental variables setted:
ADAPTER_TYPE= csv
CSV_MODEL_JSON=server\gateways\synthetic-data\device-models.json
CSV_DEVICE_JSON=server\gateways\synthetic-data\devices.json
CSV_FOLDER=server\gateways\csv
CSV_DATA_START=  #Format: YYYY-MM-DDTHH:MM:SS.000Z
CSV_DATA_END=  #Format: YYYY-MM-DDTHH:MM:SS.000Z
CSV_DELIMITER="\t"
CSV_LINE_BREAK="\n"
CSV_TIMESTAMP_COLUMN="time"
CSV_FILE_EXTENSION=".csv"

this is the code i'm using https://github.com/Autodesk-Forge/forge-dataviz-iot-reference-app

A: I have just answered a similar question here: Setting up a CSV Data Adapter locally. When you follow the steps listed in the answer the sample app should read the CSV data without problems.


text:
Q: Studies on how the wording employed on the explanation of mathematical concepts helps students to learn? I remember that I had to learn division in my childhood, I could handle all the other mathematical concepts that were presented until then but division was a real pain to learn, somehow the idea of $n$ divided by $m$ equals $p$ was devilishly to grasp.
Then my father tried to teach me, and then he reworded it:
$$m \text{ divided by }n$$
To:
$$ \text{ how many n's are in m?}$$
Somehow, the rewording made complete sense for me, I could understand what is division about. Until the present date, thinking in the first form still doesn't make sense to me, if I think:
$$4\div 2=2$$
$$6\div 2=3$$
I know the answer because I've memorized the set of numbers, but if I think:
$$1657\div 1254$$
The meaning of $\div$ gets completely obscure and I have to reword it to perform the desired operation. It happened with me, I guess the effect do exist and I believe it could be very important to learn about it and use it to learn advanced concepts in higher mathematics. I don't know if there are studies about it (the nearest thing I know about is Polya's work) - But I'm almost certain that there may be a thing or two.


text:
Q: Turn off Trigger and Classes - Code coverage error below 75% I need your help on this one.
Need:
We have several triggers that use classes and we need to disable or deactivate both the triggers and classes in production because they are causing issues with another active trigger.
Issue:
I have made all of the triggers we want deactivated Status = Inactive through the use of the check box when in sandbox and also commented out my test classes.  The classes are still active because I don't know how to make those inactive.  The issue is that editing the triggers and classes brought the overall coverage down to 16% which is obviously too low for deployment.  The triggers and classes we still want active have the appropriate code coverage but I can't deploy the the triggers and classes we want to deactivate because the overall code coverage is only 16%.  A simple way would be ideal as I do not have a ton of knowledge in this arena.

A: Looks like the test classes are fine just that the triggers are de activated, causing the coverage to suffer.
If the triggers can be refactored to determine if its running in test context, and bail out if not, in case of triggers that you want to deactivate. i.e. if (!Test.isRunningTest()) return; . Idea is to let the tests run but not otherwise even when they are active.
Long term solution will be to, move the trigger code to respective classes, get a Apex trigger framework. Control unwanted invocation. For reference may read blogs of Dan Appleman, Hari Krishna.


text:
Q: Decoherence via environmental photons I am reading the book "Decoherence and the Quantum-to-Classical Transition" by Maximilian A. Schlosshauer, and I have come to understand that for a two-level system with eigenstates $|a\rangle$, $|b\rangle$ for which the environmental respectively adopts eigenstates $|E_a\rangle$, $|E_b\rangle$ corresponding to the system states, the suppression of the coherent terms in the $a,b$ basis is proportional to $\langle E_a|E_b\rangle$. I also learned the general formula for how scattering of light environmental particles carries away information about a system, thereby reducing the environmental wavefunction overlap and decohering it. My question is: what about the kind of decoherence caused by photons either being absorbed or not being absorbed in a given molecule. For instance, if a molecule A absorbs at frequency $\omega$ in its ground state, and the excited molecule $A*$ absorbs at frequency $\omega_1$, it seems reasonable to me that irradiating the sample with $\omega$-frequency photons should suppress the ability of $A$ to exist in a coherent superposition of excited and ground states. However, I can't think of a mathematical theorem for what this decoherence would look like, and I can't find one in my book either. Does anyone know what theorem describes this specific type of decoherence?

A: There are papers treating decoherence of relatively large molecules like fullerenes to test models of decoherence:
https://arxiv.org/abs/quant-ph/0402146
See also Section 4 of
https://arxiv.org/abs/1911.06282
which is a review of decoherence, which includes discussions of decoherence of atoms and molecules. The specific form of the decoherence depends on what regime is relevant, e.g.- the comparitive size of the wavelength of the molecule and the radiation it's interacting with, and it's unclear from your question what regime you're interested in.

A: Yes, shining light which is more/less likely to be absorbed by the excited vs unexcited states will certainly cause decoherence, as will any interaction which carries away information about the state of the system into the environment. As Schlosshauer discusses, this effect explains why it's so hard to keep atoms in coherent superpositions of energy eigenstates (see discussion in 2.8.2, although the assumption that $H_S >> H_{int}$ is not good in the case of laser light with enough energy to excite an atom).
Regarding a "mathematical theorem for what this decoherence would look like", the procedure would be very similar to that for photon scattering without absorbtion, but you'd have to use a Fock space to describe the system since the number of particles changes, and the S matrix would also encode information about photon creation/destruction. I recommend reading the section on Second Quantization in Sakurai (starts on page 461 of the second edition) or another good quantum mechanics text if you aren't familiar with Fock spaces. If a photon was definitely absorbed by an unexcited atom and definitely not absorbed by an excited atom, then the overlap between these states would be zero. A more realistic interaction would result in a final states which are some superposition of photon absorbed/scatter/unchanged and the overlap would be non-zero.


text:
Q: Debugging tool for Chrome Extension notification window I created a notification window using the Chrome Extension API:
var notification = webkitNotifications.createHTMLNotification("notification.html");
notification.show();

Also there is an external notification.js for all the scripts I would like to run in the notification window (Since the manifest version 2 discourages inline javascript). Everything works fine except I couldn't open developer tools for the notification window to inspect the page. I can do it for the background as well as the popup pages, so not sure if I didn't find it or I simply can't inspect notification through the developer tool. I know I can send messages between background and notification so that outputs show up on the console, but it would be nice if I could inspect directly.
Thanks much!

A: Navigate to chrome://inspect/ and you can see all the pages that can be inspected. Under the section "Extensions" you should be able to see your notification page and you can inspect it.
Adding this answer for completeness, because @JJin's answer may had been working before but not in Chrome versions 24 and 25.

A: After some experimenting I accidently found that the developer tool is available for the notification page. The trick is to

*

*fire up the notification window first and keep it on;

*navigate to chrome://extensions and notification.html should appear alongside the background.html or whatever name the background page's name is,
as shown in the screenshot:

Make sure the notification window is on otherwise the notification.html would disappear.


text:
Q: How did you handle with the Eliminate render-blocking resources and Limit unused CSS in Magento 2 How did you handle with the Eliminate render-blocking resources in Magento 2 and Limit unused CSS it is about real treatments.
I have enabled Varnish, Minify CSS, JS, WebP, Image attributes added.

A: Following should be done :

*

*For server end: -- Varnish -- make sure most of the pages are delivered from varnish Cache.
For Front end: 2. CDN: for JS, CSS, and Media use of CDN will reduce hop time which in turn means faster pages.

*Critical CSS

*Remove unwanted JS using requierJS and Require config JS.

*Differ JS or Async objective load it as late as possible.

*Advance Bundle JS

*WebP and responsive images to reduce image payload.
Check google PSI tool apply FCP and LCP filters and check.
Also go through this link :
Guide to Magento optimization


text:
Q: Compute centroid for each group using dplyr For each cluster in temp3, compute it's centroid. I would ultimately like not plot the cluster number on it's centroid's coordinates.
Data:
> head(temp3)
                             X         Y Transcripts Genes Timepoint Run Cluster
6B_0_GACCGCGATATT -102.1425877 13.944831      134028 11269     Day 0  6B       2
6B_0_ATTGCGGAGACA  -38.6617527  0.600154      106849 10947     Day 0  6B       3
6B_0_ATGGTCACCACT  -23.3275424 34.178312      105817 10495     Day 0  6B       4
6B_0_ATATTGCTAATC   -0.6069128 52.449397       79920  9650     Day 0  6B       4
6B_0_ATCTAATCTACC   -0.4738788 54.756711       72912  9294     Day 0  6B       4
6B_0_CGCAGTGTGCCC  108.5333675 76.637930       70132  9291     Day 0  6B       6

Code:
library(dplyr)
temp3 %>% group_by(Cluster) %>% mutate(., Centroid=rowMeans(cbind(.$X, .$Y), na.rm = TRUE))

Which returns:

Error: incompatible size (13792), expecting 198 (the group size) or 1

EDIT:
another approach:
library(cluster)
temp3 %>% group_by(Cluster) %>% mutate(., Centroid=pam(cbind(.$X, .$Y), 1)$medoids)

returns:

Error: incompatible size (2), expecting 198 (the group size) or 1

A: How about just
temp3 %>% group_by(Cluster) %>% mutate(meanX=mean(X), meanY=mean(Y))

if you want a result with the same dimensions as the input.
Or, if you just want one row per cluster (which seems more likely):
temp3 %>% group_by(Cluster) %>% summarise(meanX=mean(X), meanY=mean(Y))


text:
Q: Django create empty formset with fixed number of form I would like to create an empty formset with fixed number ( more than 1)
I am not sure is it possible to do it in views.py. I saw many methods using jquery to create a new form.
here is my code to create a new form, however the number of form is only one.
MyStuffSet = modelformset_factory( MyStuff )

formset =  MyStuffSet( queryset = MyStuff.objects.none() )

A: You can use extra parameter . like :
MyStuffSet = modelformset_factory(MyStuff, extra=3)

OR Condition based :
MyStuffSet = modelformset_factory(MyStuff, extra=1 if request.POST.has_key('any_key') else 0)


text:
Q: Adding AspectJ to pom.xml changed Java version with Maven, why? UPDATE: here is my maven-compiler-plugin configuration:
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>

I work on a multi-project application that I build with Maven. We decided to add AspectJ so I added the following code to pom.xml in the top level project: (from the official documentation)
<project>
  ...
  <dependencies>
    ...
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.7.3</version>
    </dependency>
    ...
  </dependencies>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
        <version>1.5</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>    <!-- use this goal to weave all your main classes -->
              <goal>test-compile</goal> <!-- use this goal to weave all your test classes -->
            </goals>
          </execution>
        </executions>
      </plugin>
      ...
    </plugins>
  <build>
  ...
</project>

and the following fragments to each subordinate projects:
</project>
      ...
      <build>
        ....
           <plugins>
               ...
            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            </plugin>
         </plugins>
    </build>

        <dependencies>
          ...
         <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
         </dependency>
         ....
      </dependencies>
     ...
 </project>

Somehow this modification has overridden the Java version I use. If I run build I get multiple errors like this:

Syntax error, annotations are only available if source level is 1.5 or greater

That gives me the suspicion that my Java version (originally 1.6) was somehow reverted to 1.4. I did nothing - at least not knowingly - that could influence the Java version, so I suspect that the above mentioned AspectJ related code is responsible for the change.
My question is how can AspectJ change the Java version and what should I do to fix this problem. Or do I misunderstand something completely and am I on the wrong track?

A: I think the problem is with the default source, target and complianceLevel settings of the aspectj-maven-plugin (according to the documentation linked previously, 1.4, 1.2 and 1.4 respectively). You should set these explicitly in your parent pom:
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.5</version>
            <!-- new configuration is here -->
            <configuration>
                <complianceLevel>1.6</complianceLevel>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        ...
    </plugins>
<build>

A: I was missing
<complianceLevel>${java.level}</complianceLevel>

in my pom.xml

A: If you don't have define the version, the compiler plugin assumes that your Java source conforms to Java 1.3 and that you are targeting a Java 1.1 JVM.
Maybe, you should define it:
http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

A: You can find last versions of dependecy and plugin for aspectj.

A: I was missing the java version with jdk version at the top of my pom properties.
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.2</version> <!-- 1.5 dint work for me -->
    <dependencies>
        <!-- You must use Maven 2.0.9 or above or these are ignored (see MNG-2972) -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
    </dependencies>
    <executions>
        <execution>
            <phase>process-sources</phase> <!-- or any phase before compile -->
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <outxml>true</outxml>
        <source>${jdk.version}</source>  <!-- I was missing this -->
        <target>${jdk.version}</target>  <!-- jdk.version property -->
    </configuration>
</plugin>

and at the top of my pom.xml I had set jdk.version property like,
<properties>
    <jdk.version>1.7</jdk.version>
</properties>


text:
Q: Android Studio XML code issue why do I get
 xmlns: android="http://schemas.android.com/apk/res/android"
after the text view class when I'm trying to run the basic XML code?
On android studio, it runs fine with it, but on Udacity ( where I'm learning from ) it's not a part of code.

A: When you use
android:id="@+id/yourViewId"
You are actually calling:
http://schemas.android.com/apk/res/android:id
You can also call other namespaces like app and tools.
You can find more information here: Android XML Namespaces


text:
Q: Clean algorithm for generating Scrabble tile sequences I am trying to come up with an algorithm that generates every possible combination of Scrabble tile sequence on a player's rack. I want the sequence to be comprised of n number of indices depending on the number of tiles on a player's rack.
So for example, in Scrabble, a player MUST have at least 1 tile on his rack but no more than 7.
Therefore, there are 7 possible scenarios to consider:
Player has 1 tile on his rack (minimum)
Player has 2 tiles on his rack
Player has 3 tiles on his rack
Player has 4 tiles on his rack
Player has 5 tiles on his rack
Player has 6 tiles on his rack
Player has 7 tiles on his rack (maximum)

In the case where the player only has 1 tile, this is easy since we only have a single index to worry about.
The answer is:
1: [0] - This means the tile on index 0 on the rack can not be repositioned any further.

In the case where the player only has 2 tiles, this too is easy since we only have 2 combinations.
The answer is:
1: [0][1] – First tile on the rack remains in position 0
            Second tile on the rack remains in position 1
2: [1][0] - First tile on the rack swaps to position 1
          - Second tile on the rack swaps to position 0

In the case where the player has exactly 3 tiles on his rack, there are even more combinations:
The answer is:
1: [0][1][2]
2: [0][2][1]
3: [1][0][2]
4: [1][2][0]
5: [2][0][1]
6: [2][1][0]

Of course, in the 3 examples above, the answers represent those situations where the player has managed to play ALL his tiles on a single play.
In Scrabble, however, a player can play any number of tiles on his rack or even none at all. Ignoring the situation where no tiles are played, we need sets to encompass any type of play.
Let's revisit a rack with 1 tile. We have no more extra sets to create; the answer is still:
1: [0]

For 2 tile racks, the answer is now:
1: [0][1] – All 2 tiles are played
2: [1][0] – All 2 tiles are played
3: [0] – Only 1st tile is played, other stays on rack
4: [1] – Only 2nd tile is played, other stays on rack

For 3 tile racks, the answer is:
 1: [0][1][2] - All 3 tiles played
 2: [0][2][1] - All 3 tiles played
 3: [1][0][2] - All 3 tiles played
 4: [1][2][0] - All 3 tiles played
 5: [2][0][1] - All 3 tiles played
 6: [2][1][0] - All 3 tiles played
 7: [0][1] - Only 2 of 3 tiles played
 8: [0][2] - Only 2 of 3 tiles played
 9: [1][0] - Only 2 of 3 tiles played
10: [1][2] - Only 2 of 3 tiles played
11: [2][0] - Only 2 of 3 tiles played
12: [2][1] - Only 2 of 3 tiles played
13: [0] – A single tile played
14: [1] – A single tile played
15: [2] – A single tile played

The number of combinations grows dramatically when we start looking at racks with 4, 5, 6 and 7 tiles but can we use a clean reusable algorithm that will work in all cases?
I did come up with a solution but it is not very clean as I needed to create 7 separate classes, one for each possible tile count for a given rack.
For example, here is the java class for generating all combinations for a 7 tile rack but I am looking for something that can be expressed more elegantly.
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class TileCombinationSet07 {

    private static final int NUM_TILES = 7;
    private static final List<TileCombination> TILE_01_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_02_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_03_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_04_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_05_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_06_COMBOS = new ArrayList<TileCombination>();
    private static final List<TileCombination> TILE_07_COMBOS = new ArrayList<TileCombination>();

    static  {
        Set<Integer> unique = new LinkedHashSet<Integer>();
        Set<String> UNIQUE_TILE_SET_01 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_02 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_03 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_04 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_05 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_06 = new LinkedHashSet<String>();
        Set<String> UNIQUE_TILE_SET_07 = new LinkedHashSet<String>();

        for(int one = 0; one < NUM_TILES; one++) {
            for(int two = 0; two < NUM_TILES; two++) {
                for(int three = 0; three < NUM_TILES; three++) {
                    for(int four = 0; four < NUM_TILES; four++) {
                        for(int five = 0; five < NUM_TILES; five++) {
                            for(int six = 0; six < NUM_TILES; six++) {
                                for(int seven = 0; seven < NUM_TILES; seven++) {
                                    unique.clear();
                                    unique.add(one);
                                    unique.add(two);
                                    unique.add(three);
                                    unique.add(four);
                                    unique.add(five);
                                    unique.add(six);
                                    unique.add(seven);

                                    String result = "";
                                    for(Integer value : unique) {
                                        result += value;
                                    }

                                    if(unique.size() == 1) {UNIQUE_TILE_SET_01.add(result);}
                                    else if(unique.size() == 2) {UNIQUE_TILE_SET_02.add(result);}
                                    else if(unique.size() == 3) {UNIQUE_TILE_SET_03.add(result);}
                                    else if(unique.size() == 4) {UNIQUE_TILE_SET_04.add(result);}
                                    else if(unique.size() == 5) {UNIQUE_TILE_SET_05.add(result);}
                                    else if(unique.size() == 6) {UNIQUE_TILE_SET_06.add(result);}
                                    else if(unique.size() == 7) {UNIQUE_TILE_SET_07.add(result);}
                                    else {
                                        throw new IllegalStateException("FATAL: Set size is wrong");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        initTileCombinationList(UNIQUE_TILE_SET_01, TILE_01_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_02, TILE_02_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_03, TILE_03_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_04, TILE_04_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_05, TILE_05_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_06, TILE_06_COMBOS);
        initTileCombinationList(UNIQUE_TILE_SET_07, TILE_07_COMBOS);
    }

    public static final List<TileCombination> tileCombinations(int tilesToPlay) {
        if(tilesToPlay == 1) {return TILE_01_COMBOS;}
        if(tilesToPlay == 2) {return TILE_02_COMBOS;}
        if(tilesToPlay == 3) {return TILE_03_COMBOS;}
        if(tilesToPlay == 4) {return TILE_04_COMBOS;}
        if(tilesToPlay == 5) {return TILE_05_COMBOS;}
        if(tilesToPlay == 6) {return TILE_06_COMBOS;}
        if(tilesToPlay == 7) {return TILE_07_COMBOS;}
        throw new IllegalArgumentException("FATAL: tilesToPlay is wrong");
    }

    private static final void initTileCombinationList(
                         Set<String> unique,
                         List<TileCombination> list) {

        for(String tokens : unique) {
            list.add(new TileCombination(tokens));
        }
    }
}

A simple pseudocode or suggestion on a more elegant algorithm would be appreciated.
Thanks!

A: Start with generating all combinations of k elements out of n, where you let k loop from one to n. For each combination, you then generate all the permutations of those k elements. If you are looking for code in Java, google for "algorithm Java combinations", or "algorithm Java permutations", I am sure you will find plenty of links.
There is also some room here for optimization when there are several tiles showing the same letter on the rack.

A: Here was the solution based on Doc Brown's suggestion (I just printed out all combinations of 1 or 2 tiles to be played from a rack containing 1 to 7 tiles to see if this works and it seems to be working fine).
import java.util.Arrays;

public class TileComboDemo {

    public static void main(String[] args) {
        for(int numTiles = 1; numTiles <= 7; numTiles++) {
            int[] arr = new int[numTiles];
            for(int index = 0; index < numTiles; index++) {
                arr[index] = index;
            }
            System.out.println("==================");
            System.out.println(Arrays.toString(arr));
            for(int play = 1;  play <= arr.length; play++) {
                System.out.println( "Tiles to play: " + (play));

                if(play <= 2) {
                    combinations2(arr, play, 0, new int[play]);
                }
            }
            System.out.println("==================");
        }
    }

    public static final void combinations2(int[] arr, int len, int startPosition, int[] result){
        if (len == 0) {
            heapPermutation(Arrays.copyOf(result, result.length), result.length, result.length);
            return;
        }
        for (int i = startPosition; i <= arr.length-len; i++){
            result[result.length - len] = arr[i];
            combinations2(arr, len - 1, i + 1, result);
        }
    }

    private static final void printArr(int a[]) {
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    private static void heapPermutation(int a[], int size, int n) {
        if (size == 1) {
            printArr(a);
        }

        for (int i = 0; i < size; i++) {
            heapPermutation(a, size - 1, n);

            if (size % 2 == 1) {
                int temp = a[0];
                a[0] = a[size - 1];
                a[size - 1] = temp;
            }

            else {
                int temp = a[i];
                a[i] = a[size - 1];
                a[size - 1] = temp;
            }
        }
    }
}

Output:
==================
[0]
Tiles to play: 1
0
==================
==================
[0, 1]
Tiles to play: 1
0
1
Tiles to play: 2
0 1
1 0
==================
==================
[0, 1, 2]
Tiles to play: 1
0
1
2
Tiles to play: 2
0 1
1 0
0 2
2 0
1 2
2 1
Tiles to play: 3
==================
==================
[0, 1, 2, 3]
Tiles to play: 1
0
1
2
3
Tiles to play: 2
0 1
1 0
0 2
2 0
0 3
3 0
1 2
2 1
1 3
3 1
2 3
3 2
Tiles to play: 3
Tiles to play: 4
==================
==================
[0, 1, 2, 3, 4]
Tiles to play: 1
0
1
2
3
4
Tiles to play: 2
0 1
1 0
0 2
2 0
0 3
3 0
0 4
4 0
1 2
2 1
1 3
3 1
1 4
4 1
2 3
3 2
2 4
4 2
3 4
4 3
Tiles to play: 3
Tiles to play: 4
Tiles to play: 5
==================
==================
[0, 1, 2, 3, 4, 5]
Tiles to play: 1
0
1
2
3
4
5
Tiles to play: 2
0 1
1 0
0 2
2 0
0 3
3 0
0 4
4 0
0 5
5 0
1 2
2 1
1 3
3 1
1 4
4 1
1 5
5 1
2 3
3 2
2 4
4 2
2 5
5 2
3 4
4 3
3 5
5 3
4 5
5 4
Tiles to play: 3
Tiles to play: 4
Tiles to play: 5
Tiles to play: 6
==================
==================
[0, 1, 2, 3, 4, 5, 6]
Tiles to play: 1
0
1
2
3
4
5
6
Tiles to play: 2
0 1
1 0
0 2
2 0
0 3
3 0
0 4
4 0
0 5
5 0
0 6
6 0
1 2
2 1
1 3
3 1
1 4
4 1
1 5
5 1
1 6
6 1
2 3
3 2
2 4
4 2
2 5
5 2
2 6
6 2
3 4
4 3
3 5
5 3
3 6
6 3
4 5
5 4
4 6
6 4
5 6
6 5
Tiles to play: 3
Tiles to play: 4
Tiles to play: 5
Tiles to play: 6
Tiles to play: 7
==================


text:
Q: position div to the bottom How can I get the content div to get at the bottom instead of that odd position?
http://jsfiddle.net/madprops/6FFXL/1/

name

date

comments

content

EDIT: removed float:top

A: It is at the bottom for me in your example, (FF5), but you should probably make it safe by setting content to clear your floated divs, like this:

content

Also, the float:top on your first div is invalid, there is no top property of float.