text:
Q: Simple combinatorics dice problem How would you explain, how ${5\choose4}$ corresponds to the pattern $6-6-6-6-3$ when throwing five dice. The pattern is meant to form a sum of $27$ in total.
What I do understand is that you could shift the place of $3$ to form $4$ different patterns than the one above. However that would mean that this combination (${5\choose4}$) somehow acts as a permutation in some sense. But then I would like to know what do I choose from (5), and why do I choose that what I choose (4).

A: The expression
$${5 \choose 4}$$
counts the number of ways that you can roll $5$ dice to come up with $4$ sixes and a single three.
You have five dice.  That's the $5$.  You're choosing $4$ of them to have a value of six.  The remaining one has a value of three.
Note that you can also count them as
$${5 \choose 1}.$$
You're choosing $1$ die of the $5$ to have a value of three, and the others have a value of six.
In general,
$${n \choose k} = {n \choose n-k}.$$

A: You have gone dice, four of them are sixes and one is a three. ${5 \choose 4} = 5$ is the number of ways to pick which of the dice show $6$.

A: In this particular instance, imagine that you are allowed to sit all five dice in front of you, and then fix the values of each.  It is also important to assume that the dice are in some way distinct, (different size, different colors, etc) otherwise we do not have any natural orderings.
Now, we know that we would like to obtain the sum 27 out of four 6s and one 3, and we want to show that there are (5 choose 4) ways to do this.  The most natural way to see this is to simply choose 4 out of the 5 dice, and fix their values to be 6.  There are exactly (5 choose 4) ways to do this.  The final die must then be the 3 by default.

A: Yes, binomial coefficients are not only combinations, it have many meanings depending what you are doing.
You can understand easily if you think the binomial coefficient as a multinomial coefficient that is used to count permutations with repetition but just for 2 sets/groups, where you can think repetition as a class or set of something (not just ONE number... it can means a group or set of something).
$$\binom{n}{k_1,k_2,...,k_n}=\frac{n!}{k_1!k_2!\cdots k_n!};\ where\space\ n=k_1+k_2+\cdots+k_n$$
In your case 5 is the total number of elements, and 4 and 1 are the multiplicities for each group, the group of 6 and the group of 3.
$$\binom{5}{4}=\frac{5!}{1!4!}$$
Additional example: for this sequence a-a-a-a-b-b-c-c-c-d the amount of permutations is
$$\binom{10}{4,2,3,1}$$


text:
Q: Rails 3 - find condition on a many to many through association I have three models: User, Task and Assignation.
User has many tasks through assignation.
Tasks has many users through assignation.
class User < ActiveRecord::Base
  has_many :assignations
  has_many :tasks, :through => :assignations
  ...

class Task < ActiveRecord::Base
  has_many :assignations
  has_many :users, :through => :assignations

I have a partial which shows all the tasks of the selected user.
How can I make the condition efficiently so I can get the collection of tasks?
i.e.
user_id = params[:user_id]
@tasks = Task.find(:all, :conditions=> .....)

Regards.

A: @tasks = User.find(params[:user_id]).tasks

should work fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make second autocomplete options dependent on first autocomplete selection using jQuery? I have a form with a text input and select option box.  The text field uses an autosuggest to allow users to pick options from a list.  Once a a value is selected from the autosuggest, the select option box is populated with options dependent on the selection.
I am working to change the code over so that the second box is a text input as well, so as not to limit the users choices (i.e. both fields should allow free text entries if the user does not want to select from the available choices).
I think I've stared at this code too long, and would love some help.  Clearly the changes need to come in the loadCountry, populateSelect and loadcountrySelect functions.
I am using PHP, jQuery and jQuery UI Autocomplete.
Any help you could provide would be very much appreciated!
Scripts:

HTML:

     Continent Name:
    <input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" />

     Country:
    <input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" />

continent.php
<?php

$db_host        = 'XXX';
$db_user        = 'XXX';
$db_password    = 'XXX';
$db_name        = 'XXX';

$db = new mysqli($db_host , $db_user ,$db_password, $db_name);

if(!$db) {

    echo 'There was a problem connecting to the database';
} else {

    if(isset($_GET['startkey'])) {
        $mysearchString = $db->real_escape_string($_GET['startkey']);

        if(strlen($mysearchString) >0) {

            $query = $db->query("SELECT DISTINCTROW Continent
                                FROM locations
                                WHERE Continent
                                LIKE '$mysearchString%'
                                LIMIT 10");

            if($query) {

                while ($result = $query ->fetch_object()) {

                        print ucwords(strtolower($result->Continent))."\n";
                }

            } else {

                echo 'ERROR: There was a problem with the query.';
            }

        } else {

        }

    } else {

        echo 'Access denied.';
    }
}
?>

country.php
<?php
$db_host        = 'XXX';
$db_user        = 'XXX';
$db_password    = 'XXX';
$db_name        = 'XXX';

$db = new mysqli($db_host , $db_user ,$db_password, $db_name);

if(!$db) {

    echo 'There was a problem connecting to the database';

} else {

    if(isset($_GET['key'])) {

        $mysearchString = $db->real_escape_string($_GET['key']);

        if(strlen($mysearchString) >0) {

            $query = $db->query("SELECT Continent,Country,Abbrev
                                 FROM locations
                                 WHERE Continent
                                 LIKE '$mysearchString%'
                                 ORDER BY Country
                                 LIMIT 20");

            if($query) {

                while ($result = $query ->fetch_object()) {

                    print ucwords(strtolower($result->Country))."/".
                          ucwords(strtolower(strtok($result->Abbrev,";")))."\n";

                }

            } else {

                echo 'ERROR: There was a problem with the query.';

            }

        } else {

        }

    } else {

        echo 'Access denied.';

    }

}
?>

A: You're going to need to modify your PHP to get this to work optimally (filtering occurring on the server). I would update your PHP so that it queries your database with two parameters (one for country, one for continent):
$continent = $db->real_escape_string($_GET['continent']);
$country = $db->real_escape_string($_GET['country']);

$query = $db->query("SELECT Continent,Country,Abbrev
    FROM locations
    WHERE Continent ='$continent' and Country like '$country%'
    ORDER BY Country
    LIMIT 20");

(Please take with a grain of salt; I don't know PHP)
Basically, pass a continent (which was selected in the first input) along with the country search string (which was typed in the second input).
Next, you're going to need to apply the autocomplete widget to the second input. Something like:
$("#country_autocomplete").autocomplete({
    source: function (request, response) {
        var continent = $("#continent_autocomplete").val()
            , country = request.term;

        $.ajax({
            url: '/db/country.php?continent=' + continent + "&country=" + country,
            success: function(data) {
                response(parseLineSeperated(data));
            },
            error: function(req, str, exc) {
                alert(str);
            }
        });
    }
});

Just for some polish, you'll probably want to clear #country_autocomplete when #continent_autocomplete changes. You can do that by adding an event handler for autocomplete's change event:
$("input.continent_autocomplete").autocomplete({
    source: loadcontinent,
    change: function () {
        $("#country_autocomplete).val('');
    }
});

Lastly, you'll want to remove any code that has to do with populating the country select, since you no longer need it.

A: The jQuery plugin Autocomplete like Google supports such functionality:
autocomplete.php (agly style, the whole logic at one place -- just to show the principle)
if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) {
    $sql = 'SELECT ... FROM ... WHERE';
    $db = new MySQLi(...);
    $db->query($sql);
    $numbers = [];
    while($row = $result->fetch_assoc()){
        $numbers[] = $row['bar_number'];
    }
}
echo json_encode($numbers);

autocomplete.html
<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css">

<input type="text" name="foo_name" id="foo-name" value="">
<input type="text" name="bar_number" id="bar-number" value="">

autocomplete.js
$(function() {
    $("#foo").autocomplete({
        minLength: 3,
        limit: 5,
        source : [{
            url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%",
            type:'remote'
        }],
    });
});

$(function() {
    $("#bar").autocomplete({
        minLength: 3,
        limit: 5,
        appendMethod:'replace',
        source : [
            function(query, add) {
                fooName = $('#foo-name').val();
                $.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) {
                    add(response);
                })
        }],
    });
});


text:
Q: How to disable model binding for one action method in asp.net mvc We are using custom model binders, how to disable model binding for one action method, so that i can directly post data from angular http post request,
I have taken different/new class as parameter for action method.
but due to custom model binders loosing posted data.

A: I don't think you can disable custom model binding for an action, but you can do it by (model) class type.
I'm guessing you've got something like this:
ModelBinders.Binders.DefaultBinder = new CustomModelBinderClass();

The Binders Property is a dictionary mapping (model) types to model binder classes, so if you can use a unique model type in this one scenario, you should be able to change back to the default binder for that model type like this:
var defaultBinder = new DefaultModelBinder();
ModelBinders.Binders.Add(typeof(ModelThatNeedsDefaultBinding), defaultBinder);


text:
Q: Is there a quick way to ready up, besides pressing the crystal After running all around the level, it is annoying to have to have each player run all the way back to the crystal.  Is there any quick "ready up" button?
I'm looking for a solution specific to the Xbox 360 version of the game - not using an Xbox 360 controller on the PC.

A: At the moment, there is no quick way to ready up when playing on the Xbox 360.


text:
Q: Writing plugin : IDA Pro crashes when I launch a thread IDA pro craches when I try to start thread into the run method, any idea ??
Is there some restriction for running thread in ida ? because I found nothing in documentation, writing plugin ida.
import idaapi
from threading import Thread
import time

class Listener(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        time.sleep(3)

class myplugin_t(idaapi.plugin_t):
    flags = idaapi.PLUGIN_UNL

    def init(self):
        return idaapi.PLUGIN_OK

    def run(self, arg):
        t1 = Listener();
        t1.start();
        t1.join();

    def term(self):
        pass

def PLUGIN_ENTRY():
    return myplugin_t()

PS: The same problem is found when I write the plugin in c++

A: In python, you can use
thread.start_new_thread(functionname, ()) # the second arguments is for args

which works in ida pro.
For c++, Any ida ?


text:
Q: Whatsapp Cloud API uploading media files error currently I am trying to make a thin wrapper around Whatsapp Cloud API. One of the problem I am currently facing is that the uploading media files isn't working.
Looking through the documentation for uploading files, it seems that it expects a multipart/form-data payload to the endpoint.
Here is my current implementation
import FormData from 'form-data';
import fs from 'fs';
import axios from 'axios';

const formData = new FormData();

formData.append('file', fs.createReadStream('path/to/my/file.jpg'));
formData.append('messaging_product', 'whatsapp');
formData.append('type', 'image/jpeg');

await axios.post('https://graph.facebook.com/v14.0/PHONE_NO_ID/media', formData, {
  headers: { 'Authorization': ACCESS_TOKEN }
});

Looking at the error that it returns, it seems that I am somehow missing the messaging_product field even though I have properly add it in the formData.
{
  "error": {
    "message": "(#100) The parameter messaging_product is required.",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "FBTRACE_ID"
  }
}

The Postman collection works for uploading media file, so I am thinking that the file field of the formData is the problem. Is fs.createReadStream on a file equivalent to how Postman handle file uploading
EDIT:
The question has been solved, the problems was not adding in the headers generated by the formData, Thanks Phil below!

A: Love the documentation... they say type is a required parameter then go on to show a curl example without it .
Also, file is not the...

Path to the file stored in your local directory

but instead a mime-encoded binary.
In any case, the type needs to be part of the mime-encoding by way of the content-type meta data and you then need to forward the content-type header generated by FormData.
You also may be missing the Bearer authentication token scheme.
const PHONE_NO_ID = "something";
const ACCESS_TOKEN = "something";

const formData = new FormData();

formData.append("file", fs.createReadStream("path/to/my/file.jpg"), {
  contentType: "image/jpeg",
});
formData.append("messaging_product", "whatsapp");

try {
  const {
    data: { id: mediaId },
  } = await axios.post(
    `https://graph.facebook.com/v14.0/${PHONE_NO_ID}/media`,
    formData,
    {
      headers: {
        Authorization: `Bearer ${ACCESS_TOKEN}`, // "Bearer" prefix
        ...formData.getHeaders(), // merge in FormData headers
      },
    }
  );
  console.log("media ID", mediaId);
} catch (err) {
  console.error("upload", err.toJSON());
}

A: Try this, it worked for me:
    var axios = require('axios');
    var FormData = require('form-data');
    var fs = require('fs');
    var data = new FormData();

    data.append('messaging_product', 'whatsapp');
    data.append('file', fs.createReadStream('./images/fly.jpg'));
    data.append('type', 'image/jpeg');

    var config = {
      method: 'post',
      url: 'https://graph.facebook.com/v13.0/phone_number_id/media',
      headers: {
        'Authorization': 'Bearer access_token',
        ...data.getHeaders()
      },
      data : data
    };

    axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });


text:
Q: Replace part of filename with javascript I want to load different images based on screensize, and thought replacing text in a filename with javascript would do the trick elegantly, as long as I've got corresponding images properly named. I'm close with this, but close won't cut it.
http://jsfiddle.net/B7QhZ/2/
Javascript:
if ($(window).width() > 960) {
    $("div:contains(_small.jpg)").html(function (i, currentVal) {
        return currentVal.replace("_small.jpg", "_large.jpg");
    });
}

HTML:
<img src="...test-image_small.jpg" />

As you can see in my fiddle, i've got it working on text, but not the filename.
ps - I specifically don't want to load images as background-image in media-queried classes.

A: Complete function:
if ($(window).width() > 960) {
    $("img[src$='_small.jpg']").each(function() {
        var new_src = $(this).attr("src").replace('_small', '_large');
        $(this).attr("src", new_src);
    });

} else {
    alert('Less than 960');
}

A:
I want to load images based on screensize

Set the width and height of CSS for div to 100%
CSS
div {
    width: 100%;
    height: 100%;
}

JSFiddle


text:
Q: Python user defined function written for ArcGIS Pro returns None when it should return an address? I am rewriting a 2.7 Python script for compatibility with ArcGIS Pro and organizing it with user defined functions so that I can debug portions of the script as I go. I am new to the process, but I thought it would be a good idea to pull the function out and test it alone. It's supposed to search a database and find an address location based on a SQL query. Right now the location is hardcoded for testing. When I run the script and print the selection variable, I get "None". Any suggestions or advice for debugging this?
import pdb
import arcpy
import os
import string
from io import StringIO
from io import BytesIO
import getpass

def select_address():
    workspace = "G:\\Code Enforcement\\ACD Admin Operations\\GIS\\Operations\\BSC_Maps\\AutoLayerFiles.gdb"
    arcpy.env.workspace = workspace
    arcpy.env.overwritOutput = True
    location = '1900 McCall Rd'#arcpy.GetParameterAsText(0)
    expression = "FULL_STREET_NAME LIKE '" + location + "%'" #this is an SQL expression and can be modified as necessary
    aprx = arcpy.mp.ArcGISProject("G:\\Code Enforcement\\ACD Admin Operations\\GIS\\Operations\\BSC Maps\\BSC_Template_Auto_Generate_PRO_v1.aprx")
    for m in aprx.listMaps():
        #print(m)
        for lyr in m.listLayers():
            #print(lyr)
            if lyr.name == "LOCATION.addresspoint":
                CoaAddresses = lyr
                #print(CoaAddresses)
                selection = arcpy.SelectLayerByAttribute_management(CoaAddresses,"NEW_SELECTION", expression)
                print(selection)
                for row in arcpy.SearchCursor(selection): #retrieve address of selected feature
                    selectedAddress = row.FULL_STREET_NAME
                    return(selectedAddress)

selection = select_address()
print(selection)

EDIT: I have tried applying the suggestions made in the comments and tried the following, but I still get None.
import pdb
import arcpy
import os
import string
from io import StringIO
from io import BytesIO
import getpass
workspace = "G:\\Code Enforcement\\ACD Admin Operations\\GIS\\Operations\\BSC_Maps\\AutoLayerFiles.gdb"
arcpy.env.workspace = workspace
arcpy.env.overwritOutput = True
location = '7808 HART LN'#arcpy.GetParameterAsText(0)
aprx = arcpy.mp.ArcGISProject("G:\\Code Enforcement\\ACD Admin Operations\\GIS\\Operations\\BSC Maps\\BSC_Template_Auto_Generate_PRO_v1.aprx")

def select_address(address):

    expression = "FULL_STREET_NAME LIKE '" + address + "%'" #this is an SQL expression and can be modified as necessary
    for m in aprx.listMaps():
        #print(m)
        for lyr in m.listLayers():
            if lyr.name == "LOCATION.addresspoint":
                CoaAddresses = lyr
            #print(lyr)
                with arcpy.da.SearchCursor(CoaAddresses, ['FULL_STREET_NAME'], where_clause=expression) as cursor:
                for row in cursor:
                    print(row[1])

selection = select_address(location)
print(selection)

A: This chunk of code would produce an exception since your row index is out of range.
            with arcpy.da.SearchCursor(CoaAddresses, ['FULL_STREET_NAME'], where_clause=expression) as cursor:
            for row in cursor:
                print(row[1])

row [1] would produce the exception. You want row [0]. You also will want to return it.
return (row [0])
However since an exception isn't thrown the cursor is never initiated with records.
In your first code selection is a Results object.
>>> selection = arcpy.SelectLayerByAttribute_management ("mains", "", "OBJECTID = 1")
>>> selection
<Result 'mains'>

Results objects can't be used as the input feature class in a cursor.
>>> with arcpy.SearchCursor (selection) as cursor:
...     for row in cursor:
...         print row.OBJECTID
...
Runtime error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: __exit__
>>>

Since you're never receiving an exception I suspect your layer isn't being found. With either instance make sure the following code returns True (a layer name is matched) at some point:
if lyr.name == "LOCATION.addresspoint":


text:
Q: Importing es6 module, some named exports are undefined I'm writing code in notification_actions.js like:
# notification_actions.js
export const NOTIFICATIONS_RECEIVED = 'NOTIFICATIONS_RECEIVED';
export const notificationsReceived = (notifications, unreadCount) => ({
  type: NOTIFICATIONS_RECEIVED,
  notifications,
  unreadCount,
});

(see the whole file)
Then bundling that into all_actions.js like:
# all_actions.js
export * from 'navigation_actions';
export * from 'filter_type_actions';
export * from 'notification_actions';

And finally using it in notifications_model.js as:
import {
  notificationsReceived,
} from './all_actions.js';

...

const handleData = (dispatch) => ({ notifications, unreadCount }) => {
  dispatch(notificationsReceived(notifications, unreadCount));
};

But I get TypeError: notificationsReceived is undefined!
Unsure how to debug this further.
My webpack.config.js: here
My package.json deps:
"autobind-decorator": "^1.3.3",
"autoprefixer": "^6.3.6",
"babel-cli": "^6.10.1",
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4",
"babel-plugin-export-default-module-exports": "^0.0.4",
"babel-plugin-lodash": "^3.2.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-es2015-modules-commonjs-simple": "^6.7.4",
"babel-polyfill": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"classnames": "^2.2.5",
"colorguard": "^1.2.0",
"composer": "^0.3.0",
"css-loader": "^0.23.1",
"eslint": "^2.11.1",
"eslint-config-airbnb": "^9.0.1",
"eslint-import-resolver-webpack": "^0.3.0",
"eslint-loader": "^1.3.0",
"eslint-plugin-import": "^1.8.1",
"eslint-plugin-jsx-a11y": "^1.3.0",
"eslint-plugin-react": "^5.1.1",
"formsy-react": "^0.18.0",
"glob": "^7.0.3",
"image-webpack-loader": "^1.8.0",
"lodash": "^4.13.1",
"lodash-webpack-plugin": "^0.9.1",
"moment": "^2.13.0",
"node-sass": "^3.7.0",
"postcss": "^5.0.21",
"postcss-filter-stream": "0.0.6",
"postcss-loader": "^0.9.1",
"radium": "^0.17.1",
"react": "^15.1.0",
"react-bootstrap-sweetalert": "^1.1.11",
"react-click-outside": "^2.1.0",
"react-datepicker": "^0.27.0",
"react-dom": "^15.1.0",
"react-mixin": "^2.0.2",
"react-multidecorator": "^0.1.0",
"react-onclick-outside": "^0.1.0",
"react-redux": "^4.4.5",
"react-select": "^1.0.0-beta13",
"react-toggle-display": "^2.0.2",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.1.0",
"resolve-url-loader": "^1.4.3",
"sass-loader": "^3.2.0",
"style-loader": "^0.13.1",
"stylelint": "^6.5.1",
"underscore": "^1.8.3",
"url-loader": "^0.5.7",
"webpack": "^1.13.1",
"webpack-plugin-manifest": "^1.0.1"

A: The issue was circular dependencies, specifically the use of export default and import DependencyName from 'dependency' higher up in the script.
Instead of:
// action.js
import SomeModal from './some_modal.js';
export const doAction = () => console.log(SomeModal.modalId);
export default module.exports;

// some_modal.js
import { doAction } from './action.js';
export const close = () => doAction();
export default module.exports;

This works:
// action.js
import { modalId as SomeModalId } from './some_modal.js';
export const doAction = () => console.log(SomeModalId);
export default module.exports;

// some_modal.js
import { doAction } from './action.js';
export const close = () => doAction();
export default module.exports;

Note the import { modalId as SomeModalId } in action.js;

A: since you bundling actions in all_actions.js
   # all_actions.js
    export * from './navigation_actions';
    export * from './filter_type_actions';
    export * from './notification_actions';

you should import from all_actions.js
import { notificationsReceived } from './your-path/all_actions';

or directly from notification_actions.js
import { notificationsReceived } from './your-path/notification_actions';

or
import * as actions from './your-path/all_actions';
///then
actions.notificationsReceived;
///or
const {notificationsReceived} = actions;


text:
Q: Java:confused about CMS garbage collector I know the CMS garbage collector uses the mark sweep algorithm,I am curious about how it marks the object.
CMS initial mark: why does it mark the reachable objects rather than mark unreachable objects?

A: The garbage collector's task is to find objects that your program can no longer reach by following whatever chain of accessor steps, and to reclaim the memory occupied by them.
The Mark-Sweep GC does that the other way round: it first finds all objects that can still be reached, and then reclaim the memory of all the other objects.
Simplified Mark-Sweep algorithm (of course the real one is far more complex):

*

*Start with all directly-reachable references, e.g. local variables on the stack (arguments and locals from all not-yet-finished method calls), static fields etc.

*Mark the objects they point to.

*Recursively inspect the newly-marked objects. Mark the objects referenced by their fields.

*Repeat until you get no more new marks.

*Loop over your memory object-by-object and reclaim the memory of every object without a mark.

*Finally remove all marks.


text:
Q: Is there a more efficient way to update the order of a collection of objects in Rails 3? Suppose I have a collection of Pages that are ordered by a column called :sibling_order. Is there a more efficient way to update the ordering of the collection than what I'm doing below:
class Page < ActiveRecord::Base

...

def update_order(order)
  if (order < self.sibling_order)
    siblings = Page.where("parent_id = ? AND sibling_order < ? AND sibling_order >= ?",new_parent_id,self.sibling_order,order)
    siblings.collect{|s|s.update_attribute(:sibling_order,s.sibling_order + 1)}
  elsif (order > self.sibling_order)
    siblings = Page.where("parent_id = ? AND sibling_order > ? AND sibling_order <= ?",new_parent_id,self.sibling_order,order)
    siblings.collect{|s|s.update_attribute(:sibling_order,s.sibling_order - 1)}
  end
  self.update_attribute(:sibling_order, order) if self.sibling_order != order
end

...

end

A: Try this:
def update_order(order)
  k = (order < self.sibling_order) ? 1 : -1
  sql = "parent_id = ? AND " + ( k == 1 ?
          "sibling_order < ? AND sibling_order >= ?" :
          "sibling_order > ? AND sibling_order <= ?")
  sql = Page.send(:sanitize_sql_array, [sql, new_parent_id, sibling_order,order])
  Page.update_all("sibling_order = sibling_order + (#{k})", sql)
  self.update_attribute(:sibling_order, order) if self.sibling_order != order
end


text:
Q: Retrieving email addresses with special characters using MySQL query I am fairly new to PHP and Mysql. The question I am going to ask will be begging for someone to tell me to use prepared statements so first of all let me say I am learning this, but not quite there yet. I have a query that looks to see if an email address is in the database. The email addresses may contain unusual characters like - , / | "" etc etc. I can't seem to retrieve them - here is my code (the repeatemail is coming from a form). Works perfectly with email addresses without this characters.
            $checkemail = $_POST['repeatemail'];
    $checkemail = mysqli_real_escape_string($con, $checkemail);

    //Perform database to see if email exists
        $query  = "SELECT email FROM scorers WHERE email = '{$checkemail}'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_row($result);
        if ($row[0] == $checkemail){
                         echo "found";
                         } else {
                         echo "not found";
                         }

As it stands I have wondered if the escape string is stripping the unusual characters and therefore once its queried it been altered but that doesn't seem to be the case. Also, I have no problem entering addresses like simon.o'malley@nhs.uk but just can't check them with the above code. Looked up many explanations regarding UTF etc but its a bit above my head at this point. Could someone give me a solution to this....how do I alter the code above so it will pick out these funky email addresses? Many thanks

A: Got it...this works fine but if any of you have major concerns let me know. Its the magic quotes issue that seemed to be the only problem. All other characters seem fine
    $checkemail = $_POST['repeatemail'];
    $check_email_no_slashes = $checkemail;
    $checkemail = mysqli_real_escape_string($con, $checkemail);
    echo $check_email_no_slashes . "</br>";

    //Perform database to see if email exists
        $query  = "SELECT email FROM scorers WHERE email = '{$checkemail}'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_row($result);
        if ($row[0] == $check_email_no_slashes){ etc etc etc .......}

Thanks for your input Tim.

A: You really need to use prepared statements.  If you don't, you're asking for SQL injection issues (see http://en.wikipedia.org/wiki/SQL_injection).  For example, I could send you an email address that would delete all the rows in your table.
Prepared statements aren't hard; here's an example:
$stmt = $mysqli->prepare("SELECT email FROM scorers WHERE email = ?")
// use the string in $checkemail in place of the ?
$stmt->bind_param("s", $checkemail);
// run the query
$stmt->execute();
// put the result into $email
$stmt->bind_result($email);
if ($stmt->fetch()) {
   // found a matching email; do something about it
}
$stmt->close();

You can read more about prepared statements in the PHP docs: http://php.net/manual/en/mysqli.prepare.php


text:
Q: Refine Probability Distribution Script I have this python script that helps me with generating random combinations based upon odds, it could be used for harness racing when we have to pick the winning horse in 7 consecutive races.
Now I would like to refine this script a bit more to my wishes if possible. As already said the script now spits out random numbers based upon odds. Now I would like that to be done in a bit more distinguished manner. I don't want combinations with too many numbers corresponding with low odds. In other words, I want the script to select randomly 4 of the 7 races and come back with a random number with higher odds (+20%) for each of the 4 races. For the 3 remaining races it must give me numbers each with less than a 10% probability.
This all goes way beyond my own python knowledge so I was hoping to receive some help here.
Thx in advance for all useful input.
import bpy
import random

scene = bpy.context.scene

def get_random_value(race):
    """
    Function which returns a String containing random values based on the given probability distribution
    """

    # Generates an Array [1,2,3,...,amount_of_race_participants]
    numberList = [x+1 for x in range(len(race))]

    temp = ' '
    for x in random.choices(numberList, weights=race, k=1):
        temp = temp + str(x) + ","
    temp1 = temp[0:-1] + ''

    return temp1

def generate_text(iteration, race):
    """
    Creates a Text Object with random content and a location based on the input value
    Also gives race odds to the get_random_value function, which is used for the probability distribution
    """

    # Create Curve with text content
    font_curve = bpy.data.curves.new(type="FONT",name="Font Curve")
    font_curve.body = get_random_value(race)
    # Put Curve into Object and link it to the scene
    font_obj = bpy.data.objects.new(name="Font Object", object_data=font_curve)
    scene.collection.objects.link(font_obj)

    # Set location of Object
    font_obj.location = (0,-iteration,0)

    return font_obj

def generate_n_texts():
    """
    Creates a variable amount of Texts objects and returns them
    """

    races = [
    [5, 58, 4, 4, 8, 3, 3, 2, 5, 1, 6, 1 ],
    [3, 4, 6, 5, 19, 4, 4, 2, 2, 21, 11, 19 ],
    [12, 3, 6, 14, 6, 8, 4, 3, 18, 2, 1, 23 ],
    [15, 4, 23, 4, 29, 4, 3, 5, 8, 5 ],
    [9, 2, 12, 3, 4, 43, 5, 4, 3, 7, 1, 7 ],
    [3, 3, 2, 4, 3, 61, 3, 2, 7, 11, 1 ],
    [10, 3, 13, 31, 6, 14, 6, 9, 4, 2, 2 ]
    ]

    font_objs = []

    # enumerate goes through the array race and gives us an element and its index
    for iteration, race in enumerate(races):
        font_objs.append((generate_text(iteration, race), race))

    # Font Objects includes tuples of font objects and their respective probability distribution
    # like this [(obj, race), (obj, race), ...]
    return font_objs

# Generate font_objs list before definint recalculate_text() so the function can use the list
font_objs = generate_n_texts()

def recalculate_text(scene):
    """
    Sets the bodies of the font_objs list to a random number
    """

    #Remove seed to get a different number for every frame, even when revisiting a frame
    random.seed(scene.frame_current)

    for obj, race in font_objs:
        obj.data.body = get_random_value(race)

def register():
    bpy.app.handlers.frame_change_post.append(recalculate_text)

def unregister():
    bpy.app.handlers.frame_change_post.remove(recalculate_text)

register()


text:
Q: VB.NET BindingSource in Module not Updating I have a module in my project that I'm using as a sort of print Queue. I have an error list in it. I want the error list to be bindable so that when you open up the error console, new errors will flow through automagically.
I tried using a List(Of String) but you can't bind a DataGrid to a string... So stupid... Anyways, now I'm using a DataTable with a DataView and BindingSource. Problem is, when I first open the Error form, the data is there but new errors don't appear in the form.
I made a very simple test form where I put a timer on it that would generate random numbers and add it to a DataTable with a DataView and BindingSource and it works if all of those members are on the Form, but as soon as any piece of it is in a module, it doesn't auto update, just like my project.
Why won't a BindingSource auto-update from a Module?
Update
Ok, so in my test project, if I add a Timer and a Label and on the Timer's Tick event set the Label's text to the BindingSource's Count property, it shows that item's are being added to BindingSource, but the DataGrid isn't updating to show the changes. If I minimize and restore the window, it refreshes but won't continue to update. It looks like the BindingSource's ListChanged event only fires if the DataSource i.e. the underlying DataTable is actually on the same form as the BindingSource... When I put any piece of it in another Module or Form it won't fire the event. But if I add rows to the underlying DataTable from the Form the BindingSource is on to the DataTable on the other Form, it fires the ListChanged event, usually...


text:
Q: How to separate sync and async methods in C# type? Lets say I design a generic read only repository IReadOnlyRepository.
public interface IReadOnlyRepository
{
    ...
    TEntity Find<TEntity>(object id) where TEntity : IEntity;
    IEnumerable<TEntity> Filter<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    int Count<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    ...
}

I already have a code base with several synchronous implementations of IReadOnlyRepository and want to extend my type (interface and it's implementations) with asynchronous versions of the same methods since today it is cool to async all the way.
public interface IReadOnlyRepository
{
    ...
    Task<TEntity> FindAsync<TEntity>(object id) where TEntity : IEntity;
    Task<IEnumerable<TEntity>> FilterAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    Task<int> CountAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

This may sound subjective, but ...
Should I add async methods to the same file in a #region Async?
public interface IReadOnlyRepository
{
    ...
    #region Sync

    TEntity Find<TEntity>(object id) where TEntity : IEntity;
    IEnumerable<TEntity> Filter<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    int Count<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;

    #endregion

    #region Async

    Task<TEntity> FindAsync<TEntity>(object id) where TEntity : IEntity;
    Task<IEnumerable<TEntity>> FilterAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    Task<int> CountAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;

    #endregion
    ...
}

... or should I make my repository partial and add async methods to partial files of the same type?
public partial interface IReadOnlyRepository
{
    TEntity Find<TEntity>(object id) where TEntity : IEntity;
    IEnumerable<TEntity> Filter<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    int Count<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

public partial interface IReadOnlyRepository
{
    Task<TEntity> FindAsync<TEntity>(object id) where TEntity : IEntity;
    Task<IEnumerable<TEntity>> FilterAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    Task<int> CountAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

... or should I add my async methods to a separate IRepositoryAsync interface?
public interface IReadOnlyRepository
{
    TEntity Find<TEntity>(object id) where TEntity : IEntity;
    IEnumerable<TEntity> Filter<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    int Count<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

public interface IReadOnlyRepositoryAsync
{
    Task<TEntity> FindAsync<TEntity>(object id) where TEntity : IEntity;
    Task<IEnumerable<TEntity>> FilterAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    Task<int> CountAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

public class EfRepository : IReadOnlyRepository, IReadOnlyRepositoryAsync

... or should I get rid of sync methods at all and go async only?
public interface IReadOnlyRepository
{
    Task<TEntity> FindAsync<TEntity>(object id) where TEntity : IEntity;
    Task<IEnumerable<TEntity>> FilterAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
    Task<int> CountAsync<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity : IEntity;
}

What are the best practices of composing large types with both sync and async methods in a matter of file structure, code readability and reusability?

A: If you're going the async route, you want consumers of your interface to use the async version in order to realize any benefit. So it makes most sense to just get rid of the sync methods from the interface (the only reason not to would be to maintain backward compatibility).
If some of your implementations are synchronous, you can just use Task.FromResult to wrap the return value in a Task without any async code.

A:
Should I add async methods to the same file in a #region Async?

Never. #region is a bandaid. You're better off taking the time and refactoring things well, or splitting them off into components. Even if you add it to the existing class, don't use #region - it hides the problem and prevents others (or future-you) from dealing with it.

... or should I make my repository partial and add async methods to partial files of the same type?

No, for similar reasons to #region unless you're going to use code generation to make the async implementations (or sync versions). I don't recommend that, but I can at least imagine scenarios where it's plausible.

... or should I add my async methods to a separate IRepositoryAsync interface?

Maybe. Depending on your end goal, having this can allow gradual consumption by different parties, allow old/weird platforms to not get the async version of things, and make it easier to identify those people who're still using the old stuff. But it also makes refactoring a tad bit harder, and in very large codebases people will still use the other interface while you're trying to kill it.

... or should I get rid of sync methods at all and go async only?

If you can. The performance benefits are significant and the pollution that occurs if people use the "wrong" thing can be fairly widespread.

What are the best practices of composing large types with both sync and async methods in a matter of file structure, code readability and reusability?

They vary significantly, because the technical challenges aren't the deciding factor usually. If your org has little appetite for giant refactoring work, you probably will need to take a more gradual approach. If you have a lot of consumers who can't effectively coordinate breaking changes, you probably will need to have some versioning approach. If you have a userbase that isn't very familiar with async/await, then you'll want to design things so it's easy to do the right thing. If you have a bunch of microservices or a SteamingPileOfGarbageRepository then it may be better to prototype out a parallel version that is async heavy...
Since those non-technical aspects are key to significant changes like adding async/await everywhere, consider those first and tailor the technical design to accommodate them.

A: I would go a pure async route because this is what you usually want and provide sync methods via extensions since they are only wrappers/decorators.
I would not use #regions for this purpose. Too much work and you have to provide all sync wrappers right away to have a complete API. Using partials has the same disadvantage.
But, I you have large types then having everything only async is much easier to maintain so I wouldn't even care about sync APIs because anyone needing them, can very quickly write sync extensions on their own. Providing sync APIs might just be a huge waste of time as there are very few scenarios when one would require them.

A: Suffix is all you need
If you've chosen to expose both async and non-async methods, the way to distinguish between them is with the async suffix. For example, Find() and FindAsync() provides sufficient distinction. And you're already doing that.
There is no reason to put them in regions or separate interfaces. Indeed, Find and FindAsync probably have much have more in common than they don't, so it makes sense to have them adjacent in intellisense (which is accomplished by using a suffix instead of a prefix) and in close proximity in the code base (which means no #region or partial classes are needed) as they are likely to share private utility functions and other dependencies and really belong together logically. The sync/async aspect of their execution is just an implementation detail. I would avoid organizing the code around that. There are probably better ways you could use regions or interfaces for this problem, e.g. to separate types of repositories by area of business.


text:
Q: ipython script.py --matplotlib not working I recently reinstalled Anaconda to get Python 3.6 and now figure generating code that always worked before fails. The plot window remains empty and the circle spins forever.  Example command:
ipython plot_eg.py --matplotlib

Script content:
import pandas as pd
s = pd.Series([10.1, 9.2, 7.6, 5.4], [1, 2, 3, 4])
s.plot()
input('Enter to end:')

Or:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10.1, 9.2, 7.6, 5.4])
input('Enter to end:')

Both snippets work fine in the IPython console but not when run as scripts. I have tried restarting, reinstalling, installing from Continuum (instead of miniconda) and using the Anaconda prompt. I am running Windows 10 on an somewhat old ASUS. The only other big change I have made recently was installing bash on Windows. Has something changed with how IPython works? Or maybe I have screwed up my system somehow?

A: Because the question is not very accurate at describing the system in use, I don't know what exactly did work previously. I can just tell you one way of how it will work now.

*

*Your script should use pyplot.show() to show the plot.

*You should not use --matplotlib when running the script with IPython from the command promt.

Script (script.py):
import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series([10.1, 9.2, 7.6, 5.4], [1, 2, 3, 4])
s.plot()
plt.show()

Command call:
> ipython script.py

or simply use python
> python script.py


text:
Q: Can Django save the data into TXT and possible edit it in Django Admin? I've been using PHP .
Now I am using Django, and I have recently created a APP as my first Django/python project.
Who can understand and help me please?
class Record(models.Model):
    title = models.CharField('Title',max_length=100)
    #here......what should i do? Read_File_text
    filename = models.CharField('Filename',max_length=100)#while only save the file name and path,but django admin can edit text
                create_time = models.DateTimeField(u'Time',auto_now_add=True)

    class Meta:
        verbose_name_plural = verbose_name = 'Save to TXT'

    def __str__(self):
        return self.title

    def save(self,*args,**kwargs):
        txt_hash = hashlib.new("md5", self.title.encode("utf8")).hexdigest()
        self.txt_path = 'txtfiles/%s.txt' % txt_hash
        txt_record = ContentFile(self.content)
        if default_storage.exists(self.txt_path):
            default_storage.delete(self.txt_path)
        default_storage.save(self.txt_path , txt_record)
        super(Record,self).save(*args,**kwargs)

PHP CMS Admin function:
function Read_File_text($filepath){
    $filepath=trim($filepath);
    $htmlfp=@fopen($filepath,"r");
    //Remote
    if(strstr($filepath,"://"))
    {
        while($data=@fread($htmlfp,500000))
        {
            $string.=$data;
        }
    }
    //Local
    else
    {
        $string=@fread($htmlfp,@filesize($filepath));
    }
    @fclose($htmlfp);
    return $string;
}

PHP CMS ADMIN html:
<textarea>
    echo Read_File_text('/static/txtfiles/qrw423asdfasdfasdfghjuo87.txt'
</textarea>


text:
Q: Pulling objects of different type from MongoDB I am new to c# and mongodb. Is it possible to use linq to pull an object of a specified type from a mongodb? Basically I want to do something similar to this: LINQ: From a list of type T, retrieve only objects of a certain subclass S but in mongodb and not be limited to inheriting from anything other than object. I need to pull from a prespecified collection which can be assumed to have an object of the relevant type in it.
EDIT
The objects were originally stored as json


text:
Q: How to make a splash screen with loaded percentage I have to do a lot of operations when I start my application.
I have to show a splash screen with loaded percentage.
The idea is the first time to record the time necessary to load, then serialize it with other data. The following times I have all what's necessary to show the percentage on the splash screen.
At the beginning therefore I create a splashscreen window with some info
var bmpSplash = new BitmapImage(new Uri(@"pack://application:,,,/Resources/Images/splashScreen.png", UriKind.RelativeOrAbsolute));
splashScreen = new EmptyWindow.EmptyWindow(bmpSplash) { SizeToContent = SizeToContent.Manual, Width = 612, Height = 378, Background = Brushes.Transparent, WindowStyle = WindowStyle.None, AllowsTransparency = true, Topmost = true };
...
var tbPercetage = new TextBlock() { Text="AAAA", FontSize = 16, Width = splashScreen.Width, TextAlignment = TextAlignment.Left, Height = 50, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(150, 0, 0, 50) };
...
splashScreen.grdMain.Children.Add(otbVersion4);
splashScreen.Show();

then I create a Dispatcher timer which has to update the percentage:
DispatcherTimer tmrSplashPercentage = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(125) };
tmrSplashPercentage.Tick += (sender2, args) =>
{
((TextBlock)splashScreen.grdMain.Children[3]).Dispatcher.Invoke(() => ((TextBlock)splashScreen.grdMain.Children[3]).Text= DateTime.Now.Ticks.ToString(), DispatcherPriority.Background);
};<---- it is the 4th children

Dispatcher.CurrentDispatcher.Invoke(new Action(() => { tmrSplashPercentage.Start(); }));

I use the Invoke because I have seen that by doing this I can force update.
But if I put a breakpoint in the timer tick I have seen that it is not fired until all the load procedure is done.
So either it doesn't start or the tick event is not fired.
Thank you for any help!
Patrick
---ADD---
Sorry forgot to say that the events take place in the  MainView()  and then continues in the WindowViewBase_Loaded event.
I know that I might now use a timer but put several updates after each step but that wouldn't make it precise....


text:
Q: Android: TabHost is not visible at runtime I've seen two questions like this, but they don't have answers.
One says : you should build TabHost at Runtime.
I believe that is not the answer. Then what is the purpose of XML design if it should be initialized from code.
So, my question is still the same:
This is the XML design of some TabHost
<?xml version="1.0" encoding="utf-8"?>
<TabHost
    android:id="@+id/tabHost"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:id="@+id/tab0"
                android:orientation="vertical"
                android:background="@color/controlDarkDark"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent"
                android:layout_gravity="center"
                android:visibility="visible">
                <Button
                    android:id="@+id/button1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Button on Tab0" />
            </LinearLayout>>

            <LinearLayout
                android:id="@+id/tab1"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <Button
                    android:id="@+id/button2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Button on Tab1" />
            </LinearLayout>

        </FrameLayout>
    </LinearLayout>
</TabHost>

I am simplified the structure, and still at runtime I get the screen (see the image). And the query of

TabHost tabHost = (TabHost)findViewById(R.id.tabHost);

returns null.

A: Try this.
In the root of the xml.
Add the LinearLayout.
Then add in your code.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_host);

    TabHost mTabHost = (TabHost) findViewById(R.id.tabs);
    mTabHost.setup();
    mTabHost.addTab(mTabHost.newTabSpec("tab0").setIndicator("title1", null).setContent(R.id.button1));
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("title2", null).setContent(R.id.button2));

}

Note
If your xml code worked well,you edited the right xml code.
Android Studio is based solely on the rough rendering of the XML you wrote.
The Android Studio preview interface is not exactly equivalent to the actual interface, and the difference comes from the Android Studio's replication bias for actual interface effects.
And different Theme showed differemt view.
But in the activity,you must write the correct code and be showed in it.


text:
Q: How to read large text files - java I am making a game, but to install it, it requires 7zip to unpack the files, so I have included the 7zip installer. I have created a JFrame with a JTextArea in it to input the 7zip icense, but I cant get BufferedReader to read the whole txt file (its 57 lines, and I think its mainly because Bufferedreader wasnt designed to read that many lines.) Can you please help me read the file so I can add the license into the game.
Thanks,
Jackson
EDIT
I feel so loved when you guys pay out a newb for not knowing things -_-

A: Just read complete text from the file. store it into a String variable and then put that value into the JTextArea, because 57 lines is not that much huge to store in memory of JVM.

A: I recently write a program which read 1.1 billion lines from gzipped files with BufferedReader.
The simplest way to read a whole files as small as 57 lines is to use
String text = FileUtils.readFileToString(new File("uncompressedfile.txt"));

or
String text = FileUtils.readFileToString(new File("uncompressedfile.txt"), "UTF-8");

or if compressed with gzip (similarly with 7zip)
String text = IOUtils.toString(new GZipInputStream("compressedfile.txt.gz"));

A: You can do it in two ways :-
1>Using Scanner
void read() throws IOException {
    StringBuilder text = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
      while (scanner.hasNextLine()){
        text.append(scanner.nextLine() + NL);
      }
    }
    finally{
      scanner.close();
    }
    log("Text read in: " + text);
  }

2>The BufferredReader
static public String getContents(File aFile) {

    StringBuilder contents = new StringBuilder();

    try {

      BufferedReader input =  new BufferedReader(new FileReader(aFile));
      try {

        while (( line = input.readLine()) != null){
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }

    return contents.toString();
  }

57 lines is not that huge , bufferedreader has been used to read files in gb's:)


text:
Q: magento2 join query I want to join the main table code with the product_options value giftcard_created_codes
My query till now
$this->getSelect()->joinLeft(['secondTable' => $this->getTable('sales_order_item')], "secondTable.product_options = main_table.code ", ['secondTable.product_options as product_options']);

product_options value
{"info_buyRequest":{"uenc":"aHR0cDovLzE5Mi4xNjguMS4xODQvZGcvZHJ1bW1vbmQtZ29sZi1lLWdpZnQtY2FyZC5odG1s","product":"76450","selected_configurable_option":"","related_product":"","giftcard_amount":"5","giftcard_sender_name":"test","giftcard_sender_email":"testmscgoriteeps@gmail.com","giftcard_recipient_name":"test22","giftcard_recipient_email":"arjun.cmarix@gmail.com","giftcard_message":"test test gift","qty":"1"},"giftcard_sender_name":"test","giftcard_sender_email":"testmscgoriteeps@gmail.com","giftcard_recipient_name":"test22","giftcard_recipient_email":"arjun.cmarix@gmail.com","giftcard_message":"test test gift","giftcard_lifetime":null,"giftcard_is_redeemable":0,"giftcard_email_template":null,"giftcard_type":"0","email_sent":0,"giftcard_created_codes":["HQE9EMUNTA6N"]}

A: Try something like below.
$this->getSelect()->joinLeft(
    ['secondTable' => $this->getTable('sales_order_item')],
    new \Zend_Db_Expr("JSON_UNQUOTE(json_extract(secondTable.product_options, '$.giftcard_created_codes[0]')) = main_table.code"),
    ['secondTable.product_options as product_options']);

A: $subquery = new \Zend_Db_Expr("select json_extract(product_options, '$.giftcard_created_codes') from sales_order_item");
$this->getSelect()->join(['sq' => $subquery], "main_table.code = sq.value", []);


text:
Q: Most efficient way to get a tree object's root node I am interested in some design pattern that will give me very fast access from any tree node to the tree root with as little CPU and memory overhead as possible.
Now, to iterate the obvious solutions, and explain why they are inapplicable:

*

*go down the tree until the root is found - which is what I am currently doing, but as the tree can get quite deep and root access is pretty frequent, that is not an ideal solution, even if mitigating the overhead by caching and reusing the root as much as possible

*store the root node pointer in every node - very fast, but adds a significant memory overhead, as the tree is quite big
Now, if there was only one tree, I could use a singleton, a static class member or any similar approach, however the application has more than one tree, each representing an open project.
Before resorting to searching the root, my design involved only one single active project at a time, so I could presume that if any user activity is occurring, it would be targeting the active project, which was a very efficient way to get the particular object's root item.
But now I have a multiple windows application, where each window can have a different active project, and also inter-project communication that can trigger activity inside a project that is not currently active in any editor window. So it is no longer possible to use the "active project pointer" approach.
It seems that I have exhausted all options, but there might be some fancy design pattern which could give me a good compromise?

A: I went for a solution based on segregating the purpose of different tree nodes.
Most nodes are simply content, but there are also container nodes, which are fairly evenly distributed across the tree.
Container nodes store the tree root, and since they are few and far in between, the memory overhead is minimized. So is the lookup time, as I no longer have to traverse the entire tree until I get to the root, but only down to the nearest container node.
So in a typical usage scenario, this reduces lookup time by 2-3 orders of magnitude, by adding about 1-2% of memory overhead. A more than fair compromise.


text:
Q: Converting Unix Timestamp into a time code? I'm writing a query using Athena Redshift SQL
I've got two different tables where I need to join two columns: unix_timestamp and timestamp_code
unix_timestamp is stored as string that looks as such: 2018-04-01T10:05:52.047Z
timestamp_code is string thas looks as such: 1514564885
I want unix_timestamp to be converted into the format that `timestamp_code currently is in.
How would I go about doing that?

A: Convert to epoch:
SELECT EXTRACT(EPOCH FROM '2018-04-01T10:05:52.047Z'::TIMESTAMP);
-- date_part
--------------
-- 1522577152

Convert from epoch to timestamp:
SELECT '1970-01-01'::TIMESTAMP + 1522577152 * INTERVAL '1 sec';
--      ?column?
-----------------------
-- 2018-04-01 10:05:52

https://docs.aws.amazon.com/redshift/latest/dg/r_EXTRACT_function.html
https://docs.aws.amazon.com/redshift/latest/dg/r_Dateparts_for_datetime_functions.html


text:
Q: How to work with two lists as round robin python I have two lists like
num = [1,2,3,4]
names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']

I want to print the two lists parallel and if one list(num) ends i want to repeat the first list(num) till second(names) list ends.
now i want the output as
1 for shiva
2 for naga
3 for sarath
4 for krishna
1 for pavan
2 for adi
3 for mulagala

A: Using itertools.cycle and zip:
>>> num = [1,2,3,4]
>>> names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']
>>> import itertools
>>> for i, name in zip(itertools.cycle(num), names):
...     print('{} for {}'.format(i, name))
...
1 for shiva
2 for naga
3 for sharath
4 for krishna
1 for pavan
2 for adi
3 for mulagala

A: You'll want to use a combination of itertools.cycle and itertools.izip. For example:
>>> num = [1,2,3,4]
>>> names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']
>>> import itertools
>>> list(itertools.izip(itertools.cycle(num), names))
[(1, 'shiva'), (2, 'naga'), (3, 'sharath'), (4, 'krishna'), (1, 'pavan'), (2, 'adi'), (3, 'mulagala')]

A: list(roundrobin('ABC', 'D', 'EF'))
output : ['A', 'D', 'E', 'B', 'F', 'C']
from itertools import chain, izip_longest
def roundrobin(*iterables):
    sentinel = object()
    return (x for x in chain(*izip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)


text:
Q: Find which instruction caused a trap on Cortex M3 I am currently debugging a hard fault trap which turned out to be a precise data bus error on a STM32F205 Cortex-M3 processor, using Keil uVision. Due to a lengthy debugging and googling process I found the assembly instruction that caused the trap. Now I am looking for a way to avoid this lengthy process next time a trap occurs.
In the application note 209 by Keil it says:

PRECISEERR: Precise data bus error:
  0 = no precise data bus error
  1 = a data bus error has occurred, and the PC value stacked for the exception return points to the instruction that caused the fault. When the processor sets this bit it writes the faulting address to SCB->BFAR

and also this:

An exception saves the state of registers R0-R3, R12, PC & LR either the Main Stack or the Process Stack (depends on the stack in use when the exception occurred).

The last quote I am interpreting as such that there should be 7 registers plus the respective stack. When I look up my SP address in the memory I see the address that caused the error at an address 10 words higher than the stack pointer address.
My questions are:

*

*Is the address of the instruction that caused the trap always saved 10 words higher than the current stack pointer? And could you please point out a document where I can read up on how and why this is?

*Is there another register that would contain this address as well?

A: As you said, exceptions (or interrupts) on ARM Cortex-M3 will automatically stack some registers, namely :

*

*Program Counter (PC)

*Processor Status Register (xPSR)

*r0-r3

*r12

*Link Register (LR).

For a total of 8 registers (reference : Cortex™-M3 Technical Reference Manual, Chapter 5.5.1).
Now, if you write your exception handler in a language other than assembly, the compiler may stack additional registers, and you can't be sure how many.
One simple solution is to add a small code before the real handler, to pass the address of the auto-stacked registers :
void myRealHandler( void * stack );

void handler(void) {
    asm volatile("mov r0, sp");
    asm volatile("b myRealHandler");
}

The register BFAR is specific to bus faults. It will contain the faulty address, not the address of the faulty instruction. For example, if there was an error reading an integer at address 0x30005632, BFAR will be set to 0x30005632.

A: The precise stack location of the return address depends on how much stack the interrupt handler requires. If you look at the disassembly of your HardFault_Handler, you should be able to see how much data is stored on the stack / how many registers are pushed in addition to the registers pushed by the hardware interrupt machinery (R0-R3, R12, PC, LR & PSR)
I found this to be a pretty good idea on how to debug Hard Faults, though it requires a bit of inline assembly.


text:
Q: Excel counting the number of unique occurrences after matching the name with corresponding category Need help with matching Teacher with students and counting only a single occurrence of students from the column. Output to include the number of occurrences and the corresponding country of residence.
Expected output:
               Teacher Place   No
               Iwin    London  3
                       Newyork 1
               Rice    Newyork 1
                       Germany 1
                       Britan  1
                       Brazil  2

Input:
                Name  students  Place
                Iwin    John    London
                Iwin    John    London
                Iwin    Ron     London
                Iwin    Emil    Newyork
                Rice    Jacob   Newyork
                Rice    Rui     Germany
                Rice    erin    Britan
                Rice    erin    Britan
                Rice    erin    Britan
                Rice    josh    Brazil
                Iwin    Gary    London
                Rice    Meca    Brazil

A: You could make a unique list, take it to a table and then make a pivot table.

A: To get the counts you can textjoin the name, students and place columns for each row. Let say the input data you've provided starts in column A row 1, the formula would look like this:
=TEXTJOIN("_",, A2:C2)

You should get this Iwin_John_London in cell where you put the function. Lets say we put it in column D row 2. Now, you autofill for the rest of the rows and then use unique on the recently created output:
=UNIQUE(D2:D13)

Now we can extract the teacher's name and the place from the unique column we created. Lets say it the unique data starts in column E row 2. The formula would look like this:
=TEXTJOIN("_",, LEFT(E2, SEARCH("_", E2,1)-1), RIGHT(E2, LEN(E2) - SEARCH("_", E2, SEARCH("_", E2)+1)))

You should get this for the first cell Iwin_London. We now have to do another autofill. Then a unique in the data we just outputted in column F.
=UNIQUE(F2:F10)

Finally, we can do a countif + autofill to find the desired counts with the data on column G and F:
=COUNTIF(F2:F10,G2)

This is what all the data should look like:

A: A16 =UNIQUE(CHOOSECOLS(UNIQUE(A2:C13);1;3))
C16 =SUM((A16&B16=($F$3:$F$11&$H$3:$H$11))*1)

To get the outcome exact as you want you can hide the Names which occure more than one with conditional formating. Make the text color white or to change the numberformat of the cell to something like this:
;;;

This picture shows the conditional formatting.


text:
Q: SSRS Data does not display when run remotely I have a Report Server in which I can run the report on the remote server and display correctly. (I apologize for the color scheme. I am troubleshooting)

When I try to run the same report from my local machine by connecting to the remote server.  The report runs but no data is displayed.  No errors are reported.  I have the Report Server switch set to display errors.

This report has 2 pages and you can use the arrows without error.  So I think the query is running and returning data.  But there is something wrong with the display that the data is not showing.
On the remote server I use IE.  On my local machine I use Chrome.
I have all of the permissions checked for folder, site and report.
Any suggestions?
UPDATE
I was able to get the report to display in Chrome by adding the extension "SSRS Report Fix" to Google Chrome.
https://chrome.google.com/webstore/detail/ssrs-report-fix/fjbdfjiheheafbioiejbdpalmojkeobk
However, the report will still not display in my angular application when trying to view it.  There are no errors.  The data will not display.

A: This what worked for me...
To view the report using Google Chrome I added the extension, SSRS Reports Fix.  The link is in my updated post.
This did NOT fix the problem when I tried to display the report in an AngularJS application.
To fix this problem, I had to add this:
div {
    overflow: visible !important;
}

to the css file, ReportingServices.css on my Report Server.
This file was located here on my server:

C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting
  Services\ReportManager\Styles


text:
Q: Looking for a 1st person children's fantasy book from my youth where boy enters a dream world after falling Ahh, that's better...
Bamboozled from the latest leg of my zig-zagging Google search, fruitlessly probing the so-far barren boundaries of boolean logic, I stumbled here, what appears as a welcome rest-stop in a comfy chair, to take a break for 10 minutes and ask a real question, to real folks, and I hope you'll be able to help me in my quest :-)
I'm searching for a children's short fantasy paperback I read at school that I'd like to read again (the usual situation), and for which I only have a few scant details my memory is (fairly) certain of.
The general story was told in the first person, through the eyes of a young boy who went exploring away from his family for some reason, and slipped and fell (I think) in a cave next to a stream or some other body of water. What followed was a fantastic episode in another world inhabited by what appeared to be other children, who were all engaged in exciting adventures that the main character was invited to join in.
Certain points I remember:
A lot of time appeared to pass in the world,  days were interspersed with periods of sleep; sleeping was necessary, but only for a few minutes - you take a pill or lay on a special pillow, and you'd wake up completely refreshed in about 5 minutes.
They were able to fly using a contraption that I think they hung onto and steered by shifting their weight, I imagined a giant paper plane at this point, but I could be wrong.
Either way, the leading child in the new land showing the main character about is called Dindo, and he explains all the rules and keeps the boy safe and entertained. Dindo is a great pilot, and shows the boy his first lessons by throwing himself off a high ledge where the boy is compelled to follow...
All was well until the boy was injured when he had an accident, and Dindo told him he'd have to go back to his own world as they couldn't fix him in this world.
The only problem would be that he'd have to be given something to make sure he didn't remember where he'd been or how he'd gotten there - and whilst the boy started to protest, he found that he was starting to forget the names of those in front of him.
Back in the real world, the boy is found and taken home: he'd been missing for several hours (or was it even a couple of days?), was found unconscious and soaked, can't remember anything of when he was missing.
Trying to help, a doctor suggests to his parents that he keeps a dream journal to try and recall any details he might be suppressing, though as the boy remembers certain things he decides for some reason to keep two journals, one to give to his parents that would contain innocuous dreams, and one for himself in which he writes his actual recollections.
One of the passages he scrawls in his journal after a particularly vivid dream is 'Window goes over the edge...', but when he reads it in the morning it makes  little sense to him.
The nights continue in the same way for some time, until at some point he recognized the initial W looks more like a D, and the dammed up memories flood back into his wakeful mind.
The story ends with the boy returning to the spot where he fell, calling Dindo to take him back but getting no answer from the water.
Strange story, I'd really like to read it again. I've probably built it up so much in my mind that it feels like an epic novel for the impression it left on me but the reality is likely to be somewhat diminutive - though the gratitude I'd have for any help in finding it would be more the former than the latter!
Thank you for your time once again.

A: I know this book! A birthday present about 36 years ago and still a favourite.. it is Under Plum Lake by Lionel Davidson, who also wrote as David Line.  Looks like it was reissued a few years ago by Reinkarnation.  The character from the undersea world is called Dido and the book does somehow have a strange and slightly eerie tone.

A young boy, Barry, explores a cave on the Cornwall coast and discovers a highly advanced subterranean civilization called Egon. Located somewhere deep beneath Earth's oceans, Egon is unknown and inaccessible to humans unless an Egonian chooses to bring them there. On all such occasions, the human being's memories of Egon are erased and replaced with false memories before being returned to the surface.


text:
Q: NSMutableArray isn't adding my NSString Im trying to add a NSString to an NSMutableArray and then make the array into NSData and save it with NSUserDefaults. But the array is always nil.
Here is my code:
- (void)viewDidLoad {
    [super viewDidLoad];
    library = [[ALAssetsLibrary alloc] init];
    groups = [[NSMutableArray alloc] init];
    userDefaults = [[NSUserDefaults alloc] init];

    NSData *data = [userDefaults objectForKey:@"GroupArray"];

    groups = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSLog(@"%i", [groups count]);
}

-(IBAction)newFolder {
    if (textField.text != nil) {
        NSString *string = textField.text.capitalizedString;
        [library addAssetsGroupAlbumWithName:string
                    resultBlock:^(ALAssetsGroup *group) {
                        NSLog(@"Created a folder named: %@", group);
                    }
                    failureBlock:^(NSError *error) {
                        NSLog(@"An error occured! - %@", error);
                    }
         ];
        [groups addObject:string];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:groups];
        [userDefaults setObject:data forKey:@"GroupArray"];

        NSLog(@"%i", [groups count]);
    }
    [self.view sendSubviewToBack:subView];
}

When the app starts i get a message in the console that the array is NULL. When I try to add the string the NSLog(@"%i", [groups count]); always return 0.
Why does this happen?

A: userDefaults = [[NSUserDefaults alloc] init];
NSData *data = [userDefaults objectForKey:@"GroupArray"];

In this case, data will be nil when the code is executed for the first time, since there is yet no "GroupArray" property present.
groups = [NSKeyedUnarchiver unarchiveObjectWithData:data];

This causes groups be become nil as well, because calling unarchiveObjectWithData: with nil as an argument will return nil as well.
And because of all that, in -newFolder, [groups addObject:string] becomes [nil addObject:string]
Calling a method on nil is allowed in Objective-C, so you get no exception there. The return value of any method called on nil is, again, nil or 0.
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:groups];

This causes data to be nil because groups is nil.
So you are always calling:
[userDefaults setObject:data forKey:@"GroupArray"];

with data = nil
Quick fix:
Add if (groups == nil) groups = [NSMutableArray array]; to the beginning of -newFolder

A: In view didLoad method every time you are initialising new instance of NSUserDefaults and calling

NSData *data = [userDefaults objectForKey:@"GroupArray"]; on the newly created object

which will return nil all the time because in the new instance there wont be any object for key @"GroupArray". Instead replace userDefaults with singleton object [NSUserDefaults standardUserDefaults]
Modify your code as shown below
- (void)viewDidLoad
{
     [super viewDidLoad];
     library = [[ALAssetsLibrary alloc] init];
     NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"GroupArray"];

     groups = [NSKeyedUnarchiver unarchiveObjectWithData:data];
     if (!groups)
     {
         groups = [[NSMutableArray alloc] init];
     }
     NSLog(@"group %@", groups);
     NSLog(@"%i", [groups count]);
}

Your newFolder method
  -(IBAction)newFolder
  {
     if (textField.text != nil)
     {
          NSString *string = textField.text.capitalizedString;
         [library addAssetsGroupAlbumWithName:string
                     resultBlock:^(ALAssetsGroup *group) {
                         NSLog(@"Created a folder named: %@", group);
                     }
                     failureBlock:^(NSError *error) {
                         NSLog(@"An error occured! - %@", error);
                     }
          ];
        [groups addObject:string];
         NSData *data = [NSKeyedArchiver archivedDataWithRootObject:groups];

        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"GroupArray"];
        [[NSUserDefaults standardUserDefaults] synchronize];

         NSLog(@"%i", [groups count]);
     }
     [self.view sendSubviewToBack:subView];
 }

This should work. As it worked for me.


text:
Q: What is best way to find first half of True's in boolean numpy array? Here is the problem:
Take a numpy boolean array:
a = np.array([False, False, True, True, True, False, True, False])

Which I am using as indexes to panda dataframe.  But I need to create 2 new arrays where they each have half the True's as the original array.  Note the example arrays are much shorter than actual set.
So like:
1st_half = array([False, False,  True,  True,  False, False,  False, False])
2nd_half = array([False, False,  False,  False,  True, False,  True, False])

Does anyone have a good way to do this?  Thanks.

A: First find true indices
inds = np.where(a)[0]
cutoff  = inds[inds.shape[0]//2]

Set values equivalent before and after cutoff:
b = np.zeros(a.shape,dtype=bool)
c = np.zeros(a.shape,dtype=bool)
c[cutoff:] = a[cutoff:]
b[:cutoff] = a[:cutoff]

Results:
b
Out[65]: array([False, False,  True,  True, False, False, False, False], dtype=bool)

c
Out[64]: array([False, False, False, False,  True, False,  True, False], dtype=bool)

There are numerous ways to handle the indexing.


text:
Q: Handling 404 error that occurs on request to external websites, using plain Javascript or Jquery I have an anchor tag in my application which points to an external website.
say;
"<http://www.google.com'>>General Search<>" . User on clicking this link will be taken to google home page. I have links of these types in several pages of my application. All points to external websites. User is the one who actually inputs the href and we dynamically creates the link with that , And we are not providing any validation to check whether the url is a valid one.
Say ;
if the user enters "somebadtextnotavalidurl" application will generate a link which looks like "<>somebadtextnotavalidurl<>" , Which on clicking will gives a 404 error.
My requirement is that i need to handle this link click in my page using javascript; If it is a valid url a new tab should be open for the url page and display the content, Else if it is a 404 then also a new tab should be open but instead of the default 404 error page that browser displays i need my own styled and formatted page should be displayed.

A: Short answer: This really is not possible.
Long answer: You basically have two options, both bad.
1)  Instead of using the actual URL your users enter, you need to prefix that URL with a server-side "handler" or "proxy" which runs on your domain, which takes the destination URL as a parameter.   Let's say that it's called UrlForwarder.aspx.  Then your links would point to /UrlForwarder.aspx?url=<actual url>.  When clicked, the UrlForwarder.aspx reads the URL from the query-string, and tries to open it using an HttpClient of some sort.  Based on the response headers (404, 200) then redirects the user to either the actual URL or your customized 404 page.
2)  A client side only solution would be to attach an event handler to all links when the document loads.  This event handler would then do an ajax request to the URL, check the response headers and if everything is OK, redirect the user to the url.  Otherwise, redirect to your custom 404 page.  There's a big caveat to this method which is the same origin policy (javascript cannot load documents from other domains, basically), which means that your javascript would not be allowed to load external websites.  See more here: AJAX cross domain call
This can be circumvented with a configuration setting in most browers though.


text:
Q: Flat to hierarchical XML transformation Here is the source XML:
<CellData>
  <Cell CellOrdinal="0">
    <Value>actual</Value>
    <FmtValue>actual</FmtValue>
  </Cell>
  <Cell CellOrdinal="1">
    <Value>630961942</Value>
    <FmtValue>630961942</FmtValue>
  </Cell>
  <Cell CellOrdinal="2">
    <Value>2.045711422E7</Value>
    <FmtValue>20457114.2200</FmtValue>
  </Cell>
  <Cell CellOrdinal="3">
    <Value>9.997105219639378E1</Value>
    <FmtValue>99.9711</FmtValue>
  </Cell>
  <Cell CellOrdinal="4">
    <Value>3.33E1</Value>
    <FmtValue>33.0000</FmtValue>
  </Cell>
  <Cell CellOrdinal="5">
    <Value>2.046303782E7</Value>
    <FmtValue>20463037.8200</FmtValue>
  </Cell>
  <Cell CellOrdinal="6">
    <Value>deposit</Value>
    <FmtValue>deposit</FmtValue>
  </Cell>
  <Cell CellOrdinal="7">
    <Value>144783359</Value>
    <FmtValue>144783359</FmtValue>
  </Cell>
  <Cell CellOrdinal="8">
    <Value>2.1388E2</Value>
    <FmtValue>213.8800</FmtValue>
  </Cell>
  <Cell CellOrdinal="9">
    <Value>1.0452016063370595E-3</Value>
    <FmtValue>0.0010</FmtValue>
  </Cell>
  <Cell CellOrdinal="10">
    <Value>6.67E1</Value>
    <FmtValue>67.0000</FmtValue>
  </Cell>
  <Cell CellOrdinal="11">
    <Value>2.046303782E7</Value>
    <FmtValue>20463037.8200</FmtValue>
  </Cell>
  <Cell CellOrdinal="12">
    <Value>deposit</Value>
    <FmtValue>deposit</FmtValue>
  </Cell>
  <Cell CellOrdinal="13">
    <Value>304011203</Value>
    <FmtValue>304011203</FmtValue>
  </Cell>
  <Cell CellOrdinal="14">
    <Value>5.70972E3</Value>
    <FmtValue>5709.7200</FmtValue>
  </Cell>
  <Cell CellOrdinal="15">
    <Value>2.7902601999882342E-2</Value>
    <FmtValue>0.0279</FmtValue>
  </Cell>
  <Cell CellOrdinal="16">
    <Value>6.67E1</Value>
    <FmtValue>67.0000</FmtValue>
  </Cell>
  <Cell CellOrdinal="17">
    <Value>2.046303782E7</Value>
    <FmtValue>20463037.8200</FmtValue>
  </Cell>
</CellData>

This list contains 6-column table data.
Data is ordered by 1-st column and contain 'type', which will come in order: actual, accumulation, deposit but some can be absent at all (accumulation in example).
i.e. it's actually contain this data:
contract_type   contract_id sum             percentage  contract_type_percentage    balance_total
actual          630961942   20457114.2200   99.9711     33.0000                     20463037.8200
deposit         144783359   213.8800        0.0010      67.0000                     20463037.8200
deposit         304011203   5709.7200       0.0279      67.0000                     20463037.8200

Here is desired XML output (based on example):
<body>
  <actual_accounts>
    <actual_account>
      <contract_id>630961942</contract_id>
      <sum>20457114.2200</sum>
      <percentage>99.9711</percentage>
    </actual_account>
    <actual_percentage>33.0000</actual_percentage>
  </actual_accounts>
  <accumulation_accounts>
    <accumulation_percentage>0</accumulation_percentage>
  </accumulation_accounts>
  <deposits>
    <deposit>
      <contract_id>144783359</contract_id>
      <sum>213.8800</sum>
      <percentage>0.0010</percentage>
    </deposit>
    <deposit>
      <contract_id>304011203</contract_id>
      <sum>5709.7200</sum>
      <percentage>0.0279</percentage>
    </deposit>
    <deposit_percentage>67.0000</deposit_percentage>
  </deposits>
  <balance_total>20463037.8200</balance_total>
</body>

Where *_percentage tags should contain value of 5th column from any row from associated * set.
Here is that I got so far:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" omit-xml-declaration="yes" method="xml" version="1.0"/>
    <xsl:template match="/">
        <body>
            <actual_accounts>
                <xsl:apply-templates select="//Cell">
                    <xsl:with-param name="cellType" select="'actual_accounts'"/>
                </xsl:apply-templates>
                <actual_percentage>0</actual_percentage>
            </actual_accounts>
            <accumulation_accounts>
                <xsl:apply-templates select="//Cell">
                    <xsl:with-param name="cellType" select="'accumulation_accounts'"/>
                </xsl:apply-templates>
                <accumulation_percentage>0</accumulation_percentage>
            </accumulation_accounts>
            <deposits>
                <xsl:apply-templates select="//Cell">
                    <xsl:with-param name="cellType" select="'deposits'"/>
                </xsl:apply-templates>
                <deposit_percentage>0</deposit_percentage>
            </deposits>
            <xsl:choose>
                <xsl:when test="count(CellData/Cell) >= 6">
                    <balance_total>
                        <xsl:value-of select="CellData/Cell[6]/FmtValue"/>
                    </balance_total>
                </xsl:when>
                <xsl:otherwise>
                    <balance_total>0</balance_total>
                </xsl:otherwise>
            </xsl:choose>
        </body>
    </xsl:template>

    <xsl:template match="//Cell">
        <xsl:param name="cellType"/>

        <xsl:if test="@CellOrdinal mod 6 = 0">
            <xsl:variable name="contract_type" select="FmtValue"/>
            <xsl:variable name="contract_id" select="@CellOrdinal + 2"/>
            <xsl:variable name="sum" select="@CellOrdinal + 3"/>
            <xsl:variable name="percentage" select="@CellOrdinal + 4"/>
            <xsl:variable name="type_percentage" select="@CellOrdinal + 5"/>
            <xsl:variable name="balance_total" select="@CellOrdinal + 6"/>

            <xsl:if test="$contract_type = 'actual' and $cellType = ('actual_accounts')">
                <actual_account>
                    <contract_id>
                        <xsl:value-of select="parent::CellData/Cell[$contract_id]/FmtValue"/>
                    </contract_id>
                    <sum>
                        <xsl:value-of select="parent::CellData/Cell[$sum]/FmtValue"/>
                    </sum>
                    <percentage>
                        <xsl:value-of select="parent::CellData/Cell[$percentage]/FmtValue"/>
                    </percentage>
                </actual_account>
            </xsl:if>

            <xsl:if test="$contract_type = 'accumulation' and $cellType = ('accumulation_accounts')">
                <accumulation_account>
                    <contract_id>
                        <xsl:value-of select="parent::CellData/Cell[$contract_id]/FmtValue"/>
                    </contract_id>
                    <sum>
                        <xsl:value-of select="parent::CellData/Cell[$sum]/FmtValue"/>
                    </sum>
                    <percentage>
                        <xsl:value-of select="parent::CellData/Cell[$percentage]/FmtValue"/>
                    </percentage>
                </accumulation_account>
            </xsl:if>

            <xsl:if test="$contract_type = 'deposit' and $cellType = 'deposits'">
                <deposit>
                    <contract_id>
                        <xsl:value-of select="parent::CellData/Cell[$contract_id]/FmtValue"/>
                    </contract_id>
                    <sum>
                        <xsl:value-of select="parent::CellData/Cell[$sum]/FmtValue"/>
                    </sum>
                    <percentage>
                        <xsl:value-of select="parent::CellData/Cell[$percentage]/FmtValue"/>
                    </percentage>
                </deposit>
            </xsl:if>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

which do everything except whose *_percentage tags..
I'm limited to XSLT 1.0.
UPDATE WITH FINAL ANSWER: with small fixes to Maesto13 solution, and only works on MSXML4.0+, .NET1.0+
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxml="urn:schemas-microsoft-com:xslt" extension-element-prefixes="msxml">

    <xsl:output indent="yes" omit-xml-declaration="yes" method="xml" version="1.0"/>

    <xsl:key name="CellGroup" use="@CellOrdinal - (@CellOrdinal mod 6)" match="CellData/Cell"/>

    <xsl:template match="CellData">
        <xsl:variable name="Cells">
            <xsl:apply-templates select="Cell[generate-id() = generate-id(key('CellGroup', @CellOrdinal - (@CellOrdinal mod 6))[1])]" mode="group"/>
        </xsl:variable>
        <body>
            <actual_accounts>
                <xsl:for-each select="msxml:node-set($Cells)/Cell[contract-type='actual']">
                    <actual_account>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </actual_account>
                </xsl:for-each>
                <xsl:variable name="type_percentage" select="msxml:node-set($Cells)/Cell[contract-type='actual'][1]/contract-type-percentage[1]"></xsl:variable>
                <xsl:choose>
                    <xsl:when test="boolean($type_percentage)">
                        <actual_percentage><xsl:value-of select="$type_percentage"/></actual_percentage>
                    </xsl:when>
                    <xsl:otherwise>
                        <actual_percentage>0</actual_percentage>
                    </xsl:otherwise>
                </xsl:choose>
            </actual_accounts>
            <accumulation_accounts>
                <xsl:for-each select="msxml:node-set($Cells)/Cell[contract-type='accumulation']">
                    <accumulation_account>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </accumulation_account>
                </xsl:for-each>
                <xsl:variable name="type_percentage" select="msxml:node-set($Cells)/Cell[contract-type='accumulation'][1]/contract-type-percentage[1]"></xsl:variable>
                <xsl:choose>
                    <xsl:when test="boolean($type_percentage)">
                        <accumulation_percentage><xsl:value-of select="$type_percentage"/></accumulation_percentage>
                    </xsl:when>
                    <xsl:otherwise>
                        <accumulation_percentage>0</accumulation_percentage>
                    </xsl:otherwise>
                </xsl:choose>
            </accumulation_accounts>
            <deposits>
                <xsl:for-each select="msxml:node-set($Cells)/Cell[contract-type='deposit']">
                    <deposit>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </deposit>
                </xsl:for-each>
                <xsl:variable name="type_percentage" select="msxml:node-set($Cells)/Cell[contract-type='deposit'][1]/contract-type-percentage[1]"></xsl:variable>
                <xsl:choose>
                    <xsl:when test="boolean($type_percentage)">
                        <deposit_percentage><xsl:value-of select="$type_percentage"/></deposit_percentage>
                    </xsl:when>
                    <xsl:otherwise>
                        <deposit_percentage>0</deposit_percentage>
                    </xsl:otherwise>
                </xsl:choose>
            </deposits>
            <xsl:variable name="total" select="msxml:node-set($Cells)/Cell[1]/balance-total"></xsl:variable>
            <xsl:choose>
                <xsl:when test="boolean($total)">
                    <balance_total>
                        <xsl:value-of select="$total"/>
                    </balance_total>
                </xsl:when>
                <xsl:otherwise><balance_total>0</balance_total></xsl:otherwise>
            </xsl:choose>
        </body>
    </xsl:template>

    <xsl:template match="Cell" mode="group">
        <Cell>
            <xsl:variable name="Cells" select="key('CellGroup', @CellOrdinal - (@CellOrdinal mod 6))"/>
            <contract-type><xsl:value-of select="$Cells[1]/FmtValue"/></contract-type>
            <contract-id><xsl:value-of select="$Cells[2]/FmtValue"/></contract-id>
            <sum><xsl:value-of select="$Cells[3]/FmtValue"/></sum>
            <percentage><xsl:value-of select="$Cells[4]/FmtValue"/></percentage>
            <contract-type-percentage><xsl:value-of select="$Cells[5]/FmtValue"/></contract-type-percentage>
            <balance-total><xsl:value-of select="$Cells[6]/FmtValue"/></balance-total>
        </Cell>
    </xsl:template>

</xsl:stylesheet>

A: I would prefer a two step transformation, collecting the data into a variable first. When vast data size is involved, this may have to be reconsidered. Below is an xslt which does the trick.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" omit-xml-declaration="yes" method="xml" version="1.0"/>

    <xsl:key name="CellGroup" use="@CellOrdinal - (@CellOrdinal mod 6)" match="CellData/Cell"/>

    <xsl:template match="CellData">
        <xsl:variable name="Cells">
            <xsl:apply-templates select="Cell[generate-id() = generate-id(key('CellGroup', @CellOrdinal - (@CellOrdinal mod 6))[1])]" mode="group"/>
        </xsl:variable>
        <body>
            <actual_accounts>
                <xsl:for-each select="$Cells/Cell[contract-type='actual']">
                    <actual_account>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </actual_account>
                </xsl:for-each>
                <actual_percentage><xsl:value-of select="$Cells/Cell[contract-type='actual'][1]/contract-type-percentage"/></actual_percentage>
            </actual_accounts>
            <accumulation_accounts>
                <xsl:for-each select="$Cells/Cell[contract-type='accumulation']">
                    <accumulation_account>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </accumulation_account>
                </xsl:for-each>
                <accumulation_percentage><xsl:value-of select="$Cells/Cell[contract-type='accumulation'][1]/contract-type-percentage[1]"/></accumulation_percentage>
            </accumulation_accounts>
            <deposits>
                <xsl:for-each select="$Cells/Cell[contract-type='deposit']">
                    <deposit>
                        <xsl:copy-of select="contract-type"/>
                        <xsl:copy-of select="sum"/>
                        <xsl:copy-of select="percentage"/>
                    </deposit>
                </xsl:for-each>
                <deposit_percentage><xsl:value-of select="$Cells/Cell[contract-type='deposit'][1]/contract-type-percentage[1]"/></deposit_percentage>
            </deposits>
            <balance_total><xsl:value-of select="$Cells/Cell[1]/balance-total"/></balance_total>
        </body>
    </xsl:template>

    <xsl:template match="Cell" mode="group">
        <Cell>
            <xsl:variable name="Cells" select="key('CellGroup', @CellOrdinal - (@CellOrdinal mod 6))"/>
            <contract-type><xsl:value-of select="$Cells[1]/FmtValue"/></contract-type>
            <contract-id><xsl:value-of select="$Cells[2]/FmtValue"/></contract-id>
            <sum><xsl:value-of select="$Cells[3]/FmtValue"/></sum>
            <percentage><xsl:value-of select="$Cells[4]/FmtValue"/></percentage>
            <contract-type-percentage><xsl:value-of select="$Cells[5]/FmtValue"/></contract-type-percentage>
            <balance-total><xsl:value-of select="$Cells[6]/FmtValue"/></balance-total>
        </Cell>
    </xsl:template>

</xsl:stylesheet>

The output I get is as follows:
<body>
    <actual_accounts>
        <actual_account>
            <contract-type>actual</contract-type>
            <sum>20457114.2200</sum>
            <percentage>99.9711</percentage>
        </actual_account>
        <actual_percentage>33.0000</actual_percentage>
    </actual_accounts>
    <accumulation_accounts>
        <accumulation_percentage></accumulation_percentage>
    </accumulation_accounts>
    <deposits>
        <deposit>
            <contract-type>deposit</contract-type>
            <sum>213.8800</sum>
            <percentage>0.0010</percentage>
        </deposit>
        <deposit>
            <contract-type>deposit</contract-type>
            <sum>5709.7200</sum>
            <percentage>0.0279</percentage>
        </deposit>
        <deposit_percentage>67.0000</deposit_percentage>
    </deposits>
    <balance_total>20463037.8200</balance_total>
</body>


text:
Q: Change video name in Powerpoint using regex in vba I'm trying to search all the videos on my presentation and change the extension of each video; changing from XXXX.mp4 to XXXX.wmv and vice versa but whenever I get to the regex part I get an error on the "pptShape.LinkFormat.SourceFullName"
Sub Test()

    Dim pptSlide As Slide
    Dim pptShape As Shape
    Dim Regx As Object
    Dim regX_matches As Object

    Set Regx = CreateObject("vbscript.regexp")
    With Regx
        .Global = True
        .Pattern = ".*"
    End With

    For Each pptSlide In ActivePresentation.Slides
        For Each pptShape In pptSlide.Shapes
            If pptShape.Type = msoMedia Then
                If pptShape.MediaType = ppMediaTypeMovie Then
                    Set regX_matches = Regx.Execute(pptShape.LinkFormat.SourceFullName)
                    Debug.Print "TEST '" + regX_matches + "'"
                    If regX_matches <> "" Then
                        pptShape.LinkFormat.SourceFullName = regX_matches(0) + ".mp4"
                    End If
                End If
            End If
        Next pptShape
    Next pptSlide

End Sub

Any tips?
Thanks in advance
Edit1: My videos are embedded so as JamieG said pptShape.LinkFormat.SourceFullName won't work...  Any idea how to modify embedded videos?

A: What is the error? I managed to generate the following error by trying to return the SourceFullName property for an embedded (not linked) video so are your videos linked or embedded?
LinkFormat (unknown member) : Invalid request. This operation requires a linked object.

You can add a test for this by using the following property of the shape:
pptShape.MediaFormat.IsLinked

So:
Sub Test()
Dim pptSlide As Slide
Dim pptShape As Shape
Dim Regx As Object
Dim regX_matches As Object

Set Regx = CreateObject("vbscript.regexp")
With Regx
    .Global = True
    .Pattern = ".*"
End With

For Each pptSlide In ActivePresentation.Slides
    For Each pptShape In pptSlide.Shapes

        If pptShape.Type = msoMedia Then
            If pptShape.MediaType = ppMediaTypeMovie And pptShape.MediaFormat.IsLinked Then
                Set regX_matches = Regx.Execute(pptShape.LinkFormat.SourceFullName)
                Debug.Print "TEST '" + regX_matches + "'"
                If regX_matches <> "" Then
                    pptShape.LinkFormat.SourceFullName = regX_matches(0) + ".mp4"
                End If
            End If
        End If
    Next pptShape
Next pptSlide

End Sub