text:
Q: Locale error with DatePicker of Vuetify in nuxt I have a problem with the Datepicker of Vuetify. I'm using it in a nuxt environment.
I used the following code:
<v-template>
    <v-menu
        ref="datePicker"
        :close-on-content-click="false"
        v-model="dateDialog"
        :nudge-right="40"
        :return-value.sync="date"
        lazy
        offset-y
        full-width
        min-width="290px"
    >
        <v-text-field
            slot="activator"
            v-model="date"
            label="Datepicker"
            prepend-icon="event"
            readonly
        ></v-text-field>
        <v-date-picker
            v-model="date"
            no-title
            color="secondary"
            :first-day-of-week="1"
            :reactive="true"
        >
            <v-spacer></v-spacer>
            <v-btn flat color="black" v-on:click="dateDialog = false">Close</v-btn>
        </v-date-picker>
    </v-menu>
</v-template>

<script>
    export default {
        name: 'TimePicker',
        data() {
            return {
                date: '2019-01-15',
                dateDialog: false,
            };
        }
    }
</script>

Everything is working. But everytime I open the Dialog I get the following warning in the console:
[Vue warn]: The computed property "locale" is already defined as a prop.

found in

---> <VDatePickerDateTable>
       <VPicker>
         <VDatePicker>
           <ThemeProvider>
             <VMenu>
...

Does anyone know the reason for this warning? I'm using
"nuxt": "^2.1.0"
"vue": "^2.5.21"
"vuetify": "^1.3.14"


text:
Q: I want to make live weather conditions page as shown in the below image

window.onload = function () {
    var out_location = document.getElementById("location");
    var out_temp = document.getElementById("temperature");
    var out_conditions = document.getElementById("conditions");
    var out_icon = document.getElementById("icon")

    // Created a variable for my API key
    const myAPIkey = "6c43fa34e8e41d24ba6839420e3f649a";

    // Created a variable for the desired URL, Concatenate in API KEY var
    const url = "https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=" + myAPIkey + "&units=metric";

    let xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {

            if (xhr.status === 200) {
                // Get data from our API & assign it to a variable
                const data = xhr.response;
                console.log(data);
                // output API Data to HTML through DOM
                out_location.innerHTML = data.name;
                out_temp.innerHTML = data.main.temp + " °C";
                out_conditions.innerHTML = data.weather[0].main;

            } else {
                out_location.innerHTML = "API call was unsuccessful";
                console.log(xhr.status);
            }
        }
    }

    // Provide url and specify response type
    xhr.open('GET', url, true);
    xhr.responseType = "json"
    xhr.send(null);

}
/* IMPORT FONTS */
@import url('https://fonts.googleapis.com/css2?family=Merriweather:wght@900&family=Oswald&display=swap');

/* RESET */
*{margin: 0;padding:0;}

/* ELEMENT STYLING */
h1,h2,h3,h4 {font-family: 'Oswald', sans-serif;}
h1{text-align: center;}
h2{margin-left:20px;margin-bottom: 10px;}
h3{margin-bottom: 20px;}
p {
    font-family: 'Merriweather', serif;
    margin: 10px ;
}
button{
    margin-left:50px;
    font-size: 1.25em;
    padding: 2px 7px;
}

/* IDs */
#choose_box{margin-bottom: 30px;}
#buttons{margin-left:50px;}

#output {
    display:none;
    width: 90%;
    margin: 0 auto;
    padding: 0px 20px;
    background-color: #f4f2c9;
    border: 5px solid #265999;
    border-radius: 10px;

}

#icon {
    position: relative;
    top: 15px;
}

/* CLASSES */
.displayText {
    font-family: monospace;
    font-size: 2em;
    padding-left: 5px;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Assignment 5</title>
        <link rel="stylesheet" type="text/css" href="a5-apis.css"/>

Humber Weather Station

Choose Your City:

                <button id="Toronto">Toronto</button>
                <button id="Yourtown">YOURTOWN</button>

                Local Weather:

Current temperature:

Current conditions:

I have tried the following code but I am not able to get that how to do this: Click on one of the buttons will reveal the hidden output section and this section will provide the current weather data for the selected city by using
AJAX to fetch the OpenWeatherMap Current Weather Data API. Output to the
appropriate areas of the webpage will be:
a. the name of the selected city
b. the current temperature (in Celsius, with text to indicate °C)
c. the current weather conditions
d. the API icon that represents the current weather conditions
e. A fifth property of your choosing. Add contextual text or adjust the raw
data to make it user friendly. E.g. in step (b) above, we added °C to the text
Here is the Image

redpajama_set_name: RedPajamaStackExchange


text:
Q: Base class has incomplete type error
Base class has incomplete type

What exactly does this error mean and how can I fix it? I have tried forward declaring the class by doing class Entity in my EntityPhysics header but it did not work.
Here is my Entity.h
#ifndef __Game__Entity__
#define __Game__Entity__

#include <iostream>
#include <string>

#include "OGRE/Ogre.h"

#include "OgreInit.h"

class Entity{
public:
    Entity(std::string entityId, std::string mesh, Ogre::Vector3 position = Ogre::Vector3::ZERO, Ogre::Vector3 rotation = Ogre::Vector3::ZERO);
    virtual ~Entity() = 0;

    void setPosition(Ogre::Vector3 position);
    Ogre::Vector3 getPosition();
    void setRotation(Ogre::Vector3 rotationIncrease);
    Ogre::Vector3 getRotation();
    void setMesh(std::string meshName);
    std::string getMesh();
    virtual void tick() = 0;
    void removeEntity();

    Ogre::Entity getEntity();
    Ogre::SceneNode getSceneNode();

    std::string entityId;
protected:
    Ogre::Entity *ent;
    Ogre::SceneNode *nod;
};

#endif /* defined(__Game__Entity__) */

And my EntityPhysics.h
#ifndef __Game__EntityPhysics__
#define __Game__EntityPhysics__

#include <iostream>
#include <string>
#include "OGRE/Ogre.h"
#include "OgreBulletCollisionsBoxShape.h"
#include "OgreBulletDynamicsRigidBody.h"

#include "Entity.h"
#include "OgreInit.h"

class EntityPhysics: public Entity //error occurs here: "Base class has incomplete type"
{
public:
    EntityPhysics(std::string pentityId, std::string mesh, Ogre::Vector3 position, Ogre::Vector3 rotation, /*Physics Specific "stuff"*/std::string shapeForm = "BoxShape", float friction = 1.0, float restitution = 0.0, float mass = 1.0);
    virtual ~EntityPhysics() = 0;
    virtual void tick() = 0;
private:
    float friction, restitution, mass;

    OgreBulletCollisions::CollisionShape *collisionShape;
    OgreBulletDynamics::RigidBody *rigidBody;
};

#endif /* defined(__Game__EntityPhysics__) */

I think it may have to do with me including Entity.h in the child class, but if I do that I get the same error.

A: This is most likely due to a circular include, and the way to fix this is to remove includes where you don't need them.
In Entity.h you don't need:
#include "OGRE/Ogre.h"
#include "OgreInit.h"

You can, and should, instead forward-declare the types. Same for EntityPhysics.h and:
#include "OGRE/Ogre.h"
#include "OgreBulletCollisionsBoxShape.h"
#include "OgreBulletDynamicsRigidBody.h"

#include "OgreInit.h"

the only one you actually need is Entity.h.

A: I had a similar error message which i resolved by moving the #includes lower down the header file so that the class definition and method definition that the other #includes desire come earlier than the other header includes.

A: It occurs when we want to use as based class but it has not been completed(some thing wrong in based class). just check the based class whether everything is fine or not


text:
Q: How to Select different column based on the row value Here are my DB column:
sort(1 or 2), head_entry (D or H), vendor_id,invoice_num, line_cost, total_cost
Data will be sorted by invoice_num,sort first. After sorting, for each row in order,
if head_entry is 'D', select head_entry,vendor_id,invoice_num,total_cost
if head_entry is 'H', select head_entry,line_cost
The output will be written into a txt format file. So the output will be
D vendor_id,invoice_num,total_cost
H line_cost
H line_cost
H line_cost
D vendor_id,invoice_num,total_cost
H line_cost

Any help, much appreciate.


text:
Q: Coupon for Subscriptions PHP I found this snippet that adds a coupon to an order programatically:
// Create the coupon
global $woocommerce;
$coupon = new WC_Coupon($coupon_code);

// Get the coupon discount amount (My coupon is a fixed value off)
$discount_total = $coupon->get_amount();

// Loop through products and apply the coupon discount
foreach($order->get_items() as $order_item){
    $product_id = $order_item->get_product_id();

    if($this->coupon_applies_to_product($coupon, $product_id)){
        $total = $order_item->get_total();
        $order_item->set_subtotal($total);
        $order_item->set_total($total - $discount_total);
        $order_item->save();
    }
}
$order->save();

It works well. However, I would like to apply a coupon to an existing subscription so that when it renews, the coupon will be applied to the order that will be created automatically.
Is there a way to do this?
Thanks!

A: Sounds like you perhaps want to setup a script to be run at given intervals, check subscriptions, create orders and applies coupons. Depending on what system you are running you probably want to look into cron on Linux or Windows Task Scheduler on Windows in order to execute your script at regular intervals.


text:
Q: Go - Passing an array to a function receiving argument list How can I pass an array as interface{} argument list in go?
func Yalla(i...interface{}) {
    fmt.Println(i...)
}

func main() {
    Yalla(1,2,3)
    Yalla([]int{1,2,3})
}

Will output:
1 2 3 //good
[1 2 3] //bad

This:
Yalla([]int{1,2,3}...)

Will generate an error.
I know I can make a new interface array and assign the values one by one to solve this, but is there an elegant way to do it?

A: There is no elegant shortcut for converting from an array of integers to a slice of interface{}. You need to write the for loop.
The call
Yalla([...]int{1,2,3}...)

does not compile because an array of integers and a slice of interface{} are different types. You can easily create a slice over the array using [:]:
Yalla([...]int{1,2,3}[:]...)

but this does not solve the problem because a slice of integers and a slice of interface{} are different types as explained in the FAQ.
You either need to copy the values as shown in the FAQ, start with a slice of interface{}
Yalla([]interface{}{1,2,3}...)

or change the variadic argument type to int
func Yalla(i ...int) {

}

if that's what you are always passing.


text:
Q: Bootable drive option not showing while dual booting Ubuntu I am trying to dual boot Ubuntu 14.04 along with Windows 8.1 but I am unable to do so. I created a bootable flash drive and whenever I restart my system to initiate the installation process, I don't get the bootable drive option in the boot manager.
I had already installed Ubuntu 14.04 on my laptop once but due to some issues I had to remove it. So I deleted the corresponding partition but wasn't able to perform bot repair. Even now when I start my system I get a GRUB windows. Does this have anything to do with the problem I am having? I tried boot repair but I don't know for some reasons it always failed.
So what is the problem here and what can I do to fix it? My system is using UEFI.


text:
Q: accessing boost multi index container context with multiple keys like pair/tuple of arguments #include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <iostream>
//#include <boost/multi_index/identity.hpp>

using namespace boost::multi_index;

//tags
struct NR_PCI {};
struct NR_FREQ_REF {};
struct NR_MOID {};

struct nr_cell_relation
{
    uint16_t id;
    uint16_t nr_freq_ref;
    uint16_t pci;
    uint64_t nrCellIdentity;
};

typedef multi_index_container<
nr_cell_relation,
    indexed_by<
    sequenced<>,
    //    ordered_unique<identity<nr_cell_relation> >,
    ordered_unique< tag<NR_PCI>, member< nr_cell_relation, uint16_t, &nr_cell_relation::pci > >,
    ordered_unique< tag<NR_MOID>, member< nr_cell_relation, uint16_t, &nr_cell_relation::id > > > > nr_anr_nrt_t;

nr_anr_nrt_t nr_anr_nrt;

bool pci_entry_exits(uint16_t pci)
{
    auto &pci_index = nr_anr_nrt.get<NR_PCI>();
    auto itr = pci_index.find(pci);
    if (itr != pci_index.end())
    {
        std::cout<<"PCI MAP Entry Exist: PCI"<<itr->pci<<std::endl;
        return true;
    }
    std::cout<<"PCI MAP Entry Not Exist: PCI"<<pci<<std::endl;
    return false;
}

bool mo_id_entry_exits(uint16_t id)
{
    auto &pci_index = nr_anr_nrt.get<NR_MOID>();
    auto itr = pci_index.find(id);
    if (itr != pci_index.end())
    {
        std::cout<<"MOID Entry Exist: MOID:"<<itr->id<<":PCI:"<<itr->pci<<std::endl;
        return true;
    }
    std::cout<<"MOID Entry Not Exist: MOID"<<id<<std::endl;
    return false;
}

int main()
{

    if (!pci_entry_exits(304))
    {
        nr_anr_nrt.push_back({1, 2, 304, 1234566});
    }
    if (!pci_entry_exits(301))
    {
        nr_anr_nrt.push_back({4, 1, 301, 1234567});
    }
    if (!pci_entry_exits(303))
    {
        nr_anr_nrt.push_back({2, 2, 303, 1234569});
    }
    if (!pci_entry_exits(302))
    {
        nr_anr_nrt.push_back({3, 1, 302, 1234568});
    }

    if (!pci_entry_exits(302))
    {
        nr_anr_nrt.push_back({5, 1, 302, 1234568});
    }

    if (mo_id_entry_exits(4))
    {
        nr_anr_nrt.push_back({4, 1, 302, 1234568});
    }

    std::cout<<"NRT DUMP with PCI KEY:"<<std::endl;
    auto it = nr_anr_nrt.get<NR_PCI>().begin();
    for (; it != nr_anr_nrt.get<NR_PCI>().end(); ++it)
    {
        std::cout << "MOID:"<<it->id<<"\tFreq_Ref:"<<it->nr_freq_ref<<"\tNR_PCI:"<<it->pci<<std::endl;
    }

    std::cout<<"NRT DUMP with MOID KEY:"<<std::endl;
    auto itr = nr_anr_nrt.get<NR_MOID>().begin();
    for (; itr != nr_anr_nrt.get<NR_MOID>().end(); ++itr)
    {
        std::cout << "MOID:"<<itr->id<<"\tFreq_Ref:"<<itr->nr_freq_ref<<"\tNR_PCI:"<<itr->pci<<std::endl;
    }

    std::cout<<"NRT DUMP ORDER OF INSERTION:"<<std::endl;
    auto it_r = nr_anr_nrt.begin();
    for (; it_r != nr_anr_nrt.end(); ++it_r)
    {
        std::cout << "MOID:"<<it_r->id<<"\tFreq_Ref:"<<it_r->nr_freq_ref<<"\tNR_PCI:"<<it_r->pci<<std::endl;
    }
}

Description:
The program is implemented for accessing multi index container using single unique key.
Problem statement: how to implement, whenever situation arises to access multi_index container using multiple keys like std::pair<key1, key2> or even tuple like std::tuple<key1, key2, key3> using composite_key.

A: Yes. You're looking for composite keys. In your example, e.g.
bmi::ordered_unique<bmi::composite_key<
    bmi::key<&nr_cell_relation::id>, bmi::key<&nr_cell_relation::nr_freq_ref>,
    bmi::key<&nr_cell_relation::pci>,
    bmi::key<&nr_cell_relation::nrCellIdentity>>>,

In the case of ordered indexes you can even query with partial keys (most significant left-to-right, so lexicographically).
Here's a rather contrived demo:
Live On Coliru
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/key.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>

namespace Lib {
    struct Relation {
        uint16_t id;
        uint16_t nr_freq_ref;
        uint16_t pci;
        uint64_t nrCellIdentity;
    };

    struct NR_PCI;
    struct NR_MOID;

    namespace detail {
        using namespace boost::multi_index;

        using nr_anr_nrt_t = multi_index_container<                 //
            Relation,                                               //
            indexed_by<                                             //
                sequenced<>,                                        //
                ordered_unique<composite_key<                       //
                    Relation,                                       //
                    key<&Relation::nr_freq_ref>,                    //
                    key<&Relation::id>,                             //
                    key<&Relation::pci>,                            //
                    key<&Relation::nrCellIdentity>                  //
                    >>,                                             //
                ordered_unique<tag<NR_PCI>, key<&Relation::pci>>,   //
                ordered_unique<tag<NR_MOID>, key<&Relation::id>>>>; //
    } // namespace detail

    using detail::nr_anr_nrt_t;
} // namespace Lib

#include <boost/pfr.hpp> // only for debug output
#include <boost/range/iterator_range.hpp>
#include <iostream>
BOOST_PFR_FUNCTIONS_FOR(Lib::Relation)

void dump(auto& os, auto const& table) {
    for (auto& rec : boost::make_iterator_range(table))
        os << " * " << rec << "\n";
}

int main() {
    using namespace Lib;

    std::cout << "(id, freqref, pci, nrcellid)\n";

    nr_anr_nrt_t nr_anr_nrt{
        {4, 9990, 11, 33},
        {1, 3330, 44, 99},
        {3, 5550, 22, 77},
        {2, 5550, 33, 55},
    };

    dump(std::cout << "sequenced:\n", nr_anr_nrt);
    dump(std::cout << "pci:\n", nr_anr_nrt.get<NR_PCI>());
    dump(std::cout << "moid:\n", nr_anr_nrt.get<NR_MOID>());

    auto& composite = nr_anr_nrt.get<1>(); // untagged index by integer id

    using boost::make_tuple;
    dump(std::cout << "composite freqref 3330:\n",
         composite.equal_range(3330));
    dump(std::cout << "composite freqref 5550:\n",
         composite.equal_range(5550));
    dump(std::cout << "composite (5550, 2):\n",
         composite.equal_range(make_tuple(5550, 2)));
    dump(std::cout << "composite (5550, 3):\n",
         composite.equal_range(make_tuple(5550, 3)));

    auto f = composite.lower_bound(1);
    auto l = composite.upper_bound(make_tuple(5550, 2));
    dump(std::cout << "composite range:\n", std::pair(f, l));
}

Prints
(id, freqref, pci, nrcellid)
sequenced:
 * {4, 9990, 11, 33}
 * {1, 3330, 44, 99}
 * {3, 5550, 22, 77}
 * {2, 5550, 33, 55}
pci:
 * {4, 9990, 11, 33}
 * {3, 5550, 22, 77}
 * {2, 5550, 33, 55}
 * {1, 3330, 44, 99}
moid:
 * {1, 3330, 44, 99}
 * {2, 5550, 33, 55}
 * {3, 5550, 22, 77}
 * {4, 9990, 11, 33}
composite freqref 3330:
 * {1, 3330, 44, 99}
composite freqref 5550:
 * {2, 5550, 33, 55}
 * {3, 5550, 22, 77}
composite (5550, 2):
 * {2, 5550, 33, 55}
composite (5550, 3):
 * {3, 5550, 22, 77}
composite range:
 * {1, 3330, 44, 99}
 * {2, 5550, 33, 55}


text:
Q: I am having trouble getting the correct results using XML EXPLICIT in T-SQL (SQL Server 2008) I am getting strange results from a query using XML EXPLICIT mode in T-SQL (SQL Server 2008).
Can someone explain what I am doing wrong?
Here is my example:
declare @parents table(id int, connection int, title nvarchar(255));
declare @children table(id int, connection int, title nvarchar(255));

insert into @parents(id, connection, title)
values(1, 21, '1');
insert into @parents(id, connection, title)
values(2, 22, '2');
insert into @parents(id, connection, title)
values(3, 23, '3');
insert into @parents(id, connection, title)
values(4, 24, '4');
insert into @parents(id, connection, title)
values(5, 25, '5');
insert into @parents(id, connection, title)
values(6, 26, '6');

insert into @children(id, connection, title)
values(1, 21, '1a');
insert into @children(id, connection, title)
values(2, 22, '2a');
insert into @children(id, connection, title)
values(3, 23, '3a');
insert into @children(id, connection, title)
values(4, 24, '4a');
insert into @children(id, connection, title)
values(5, 25, '5a');
insert into @children(id, connection, title)
values(6, 26, '6a');
insert into @children(id, connection, title)
values(7, 21, '1b');
insert into @children(id, connection, title)
values(8, 22, '2b');
insert into @children(id, connection, title)
values(9, 23, '3b');
insert into @children(id, connection, title)
values(10, 24, '4b');
insert into @children(id, connection, title)
values(11, 25, '5b');
insert into @children(id, connection, title)
values(12, 26, '6b');

select 1 as tag, null as parent,
 id as [p!1!id],
 title as [p!1!title],
 null as [c!2!id],
 null as [c!2!title]
from @parents p
union
 select 2 as tag, 1 as parent,
 p.id,
 p.title,
 c.id,
 c.title
from @parents p, @children c
where p.connection = c.connection
for xml explicit

and here is the strange result I am getting:

  <c id="1" title="1a" />
  <c id="7" title="1b" />
  <c id="2" title="2a" />
  <c id="8" title="2b" />
  <c id="3" title="3a" />
  <c id="9" title="3b" />
  <c id="4" title="4a" />
  <c id="10" title="4b" />
  <c id="5" title="5a" />
  <c id="11" title="5b" />
  <c id="6" title="6a" />
  <c id="12" title="6b" />

OK - I think I need to be more specific, and include the "Sequence" portion of my problem as well as the original issue. Given the following data set:
declare @parents table(id int, connection int, title nvarchar(255), sequence int);
declare @children table(id int, connection int, title nvarchar(255), sequence int);

insert into @parents(id, connection, title, sequence)
values(1, 21, '1', 6), (2, 22, '2', 2), (3, 23, '3', 4), (4, 24, '4', 3), (5, 25, '5', 5), (6, 26, '6', 1);

insert into @children(id, connection, title, sequence)
values(1, 21, '1a', 2), (2, 22, '2a', 2), (3, 23, '3a', 2), (4, 24, '4a', 1), (5, 25, '5a', 2), (6, 26, '6a', 1), (7, 21, '1b', 1), (8, 22, '2b', 1), (9, 23, '3b', 1), (10, 24, '4b', 2), (11, 25, '5b', 1), (12, 26, '6b', 2);

How can I get the following result that has data like this:

  <c id="6" title="6a" />
  <c id="12" title="6b" />

 <c id="8" title="2b" sequence="1" />
 <c id="2" title="2a" sequence="2" />

with the  elements ordered by sequence and their child elements order by sequence within each?
Thanks for your help...I hope this more fully explains what I need, and why I am trying to use explicit mode.

A: With SQL Server 2005 and up, forget about FOR XML EXPLICIT - use FOR XML PATH instead - it's much easier to use, more expressive, more intuitive.
Try this:
SELECT
    p.ID AS '@id',
    p.title AS '@title',
    p.sequence as '@sequence',
    (SELECT
         c.ID AS '@id',
         c.Title AS '@title',
         c.sequence as '@sequence'
     FROM @children c
     WHERE p.connection = c.connection
     ORDER BY c.sequence
     FOR XML PATH('c'), TYPE
    )
FROM
    @parents p
ORDER BY
    p.sequence
FOR XML PATH('p')

Output will be this: (order by p.sequence on the outer scope, and c.sequence in the inner scope)

  <c id="6" title="6a" sequence="1" />
  <c id="12" title="6b" sequence="2" />

  <c id="8" title="2b" sequence="1" />
  <c id="2" title="2a" sequence="2" />

  <c id="4" title="4a" sequence="1" />
  <c id="10" title="4b" sequence="2" />

  <c id="9" title="3b" sequence="1" />
  <c id="3" title="3a" sequence="2" />

  <c id="11" title="5b" sequence="1" />
  <c id="5" title="5a" sequence="2" />

  <c id="7" title="1b" sequence="1" />
  <c id="1" title="1a" sequence="2" />

See the MSDN documentation on what's new in SQL Server 2005 for more hints and tips how to use the FOR XML PATH to generate XML from your database contents...

A: Try this.
Given this data:
declare @parents table(id int, connection int, title nvarchar(255), sequence int);
declare @children table(id int, connection int, title nvarchar(255), sequence int);

insert into @parents(id, connection, title, sequence)
values(1, 21, '1', 6), (2, 22, '2', 2), (3, 23, '3', 4), (4, 24, '4', 3), (5, 25, '5', 5), (6, 26, '6', 1);

insert into @children(id, connection, title, sequence)
values(1, 21, '1a', 2), (2, 22, '2a', 2), (3, 23, '3a', 2), (4, 24, '4a', 1), (5, 25, '5a', 2), (6, 26, '6a', 1), (7, 21, '1b', 1), (8, 22, '2b', 1), (9, 23, '3b', 1), (10, 24, '4b', 2), (11, 25, '5b', 1), (12, 26, '6b', 2);

DO YOUR SELECT STATEMENT LIKE THIS:
select p.id [@id], p.title [@title], p.sequence [@sequence],
    (select c.id [@id], c.title [@title], c.sequence [@sequence]
     from @children c
     where c.connection = p.connection
     order by c.sequence
     for xml path('child'), type)
from @parents p
for xml path('parent'), type


text:
Q: Windows Forms Designer Code modifies user control collections and objects VS 2010, Windows 7: Windows Forms - I have a number of forms that contain user controls that reference domain model objects. Some of the controls reference single objects and some reference collections of domain model objects. When I open the project or individual forms, the IDE will check out the forms and add dummy domain model objects. In some cases, this has no serious side effects and in others this result in the app crashing. Why is this happening and how do I prevent this from happening in the future? I would like to get to the point where the designer doesn't add anything extraneous - I can crash the system on my thank you very much. Thanks.

A: The designer will create a default instance for each public property contained in child user-controls in the current control it is displaying. This can be changed using the DesignerSerializationVisibilityAttribute setting the visibility to DesignerSerializationVisibility.Hidden.
This tells the designer to leave those properties alone.
You will likely have to go through the designer file itself and remove the old allocations and assignments for the properties you marked.


text:
Q: comet and the timeout Hi am trying since a long time make a chat application using comet in tomcat. The problem is that i have deployed the application in cloud where there is a cap on 30 sec for a open connection.
So every time the server takes more than 30 sec to respond (like when there is no chat message left to push ) client receives a 504 exception.
So does this mean the comet technique does not work in the scenarios where we have a time cap ?
Attaching the code snippet
package com.cumulations.clique.ChatHandler;
public class AsynchronousGetChatHandler extends HttpServlet implements
    CometProcessor {

public static HashMap consumerConnectionQueue = new HashMap();
public static HashMap consumerPoolingQueue = new HashMap<String, String>();
public static HashMap consumerSessionQueue = new HashMap<String, Date>();

public static ConnectionFactory factory;
public static Connection connection;

public void event(CometEvent event) throws IOException, ServletException {

    HttpServletRequest request = event.getHttpServletRequest();
    HttpServletResponse response = event.getHttpServletResponse();

    String userName = request.getParameter("userName");
    String sessionId = request.getParameter("accesskey");

    AsynchronousGetChatHandler.consumerPoolingQueue.put(userName, "ON");

    try {

        if (event.getEventType() == CometEvent.EventType.BEGIN) {

            String str = fromRabitQ(userName);

            if (str != null) {

                    System.out.println("delivering a message: " + str);

                    PrintWriter writer = response.getWriter();
                    writer.println(str);
                    writer.flush();
                    writer.close();
                }

             else {
                PrintWriter writer = response.getWriter();
                writer.println("");
                writer.flush();
                writer.close();
            }
        }
    }

    catch (Exception e) {
        throw new ServletException("Recieving exception");

        // TODO: handle exception
    }

}

public static String fromRabitQ(String userName) throws Exception {
    try {

        Channel channel;
        QueueingConsumer consumer;

        String QUEUE_NAME = userName;
        String message = "";

        connection = RabbitMqConnection.getConnection();

        channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(QUEUE_NAME, true, consumer);

        QueueingConsumer.Delivery delivery;

        delivery = consumer.nextDelivery(27000);

        if (delivery != null) {
            message = new String(delivery.getBody());

        } else {
            message = null;
        }

        channel.basicCancel(consumer.getConsumerTag());
        channel.close();

        return message;
    }

    catch (Exception e) {
        System.out.println("Exception occured while receiveing " + e);
        throw e;
    }

}

}

A: I would say go ahead and modify the
delivery = consumer.nextDelivery(27000);

to:
 delivery = consumer.nextDelivery(20000);

Also if you can also provide your implementation of RabbitMqConnection that would be great.


text:
Q: Sequelize get pure array without objects Dears i have the below query from Sequelize
 models.ProviderZoneCity.findAll({

         attributes: ['zoneId'],
         raw : true
         ,
         where : {
          status : 1
          }
         })

the returned data shows as
"providerHasZones":[{"zoneId":1},{"zoneId":2},{"zoneId":3}]

what i need exactly is the following structure
"providerHasZones":[1,2,3]

So it will be an array of id not array of objects, i tried (raw : true) but nothing changed :(
any advice?

A: You can use array map to transform the results, e.g.
models.ProviderZoneCity.findAll({
     attributes: ['zoneId'],
     raw: true,
     where: {
       status: 1
     }
}).then(function(data) {
    return data.map(zone => zone.zoneId);
});


text:
Q: Intellisense in rehosted workflow designer Is it possible to enable intellisense in the rehosted workflow designer (as like in Visual studio)? if yes, how?
edit: the answer might be here, but I am afraid the posts' language are too technical and I don't truly understand what's being said

A: Basically you have to implement IExpressionEditorService and add that to your WorkflowDesigner. Check out this series of posts for a solution that is build on top of the VS2010 assemblies.

A: I came across a project with working IntelliSense enabled.
http://wfdesignerexpress.codeplex.com/
It is accomplished using custom ExpressionEditor and reflection. Unfortunately this project is written in VB.NET and its GUI and some of the comments are in japanese.

A: I have followed the many rabbit holes this line of enquiry leads to - eventually we went to the very helpful Actipro software who provide an Intelliprompt WPF control. They even wrote up the solution as a 'tip and trick' to guide us in how to use the control to achieve our goal.
http://blog.actiprosoftware.com/post/2013/08/26/Enhancing-the-Windows-Workflow-Designer.aspx


text:
Q: "Can't assign to function call" error in if statement I am trying to make a program that takes a passage then displays the word count, average length of the words and how many times each word occurs. However whilst trying to implement the part where it finds how many times each word occurs an error occurred: "can't assign to function call" I have looked at other question where this has been asked however I have not been able to fit it. The error occurs on the "word_amount(wordposition) += 1" line.
passage = "this is a test to test this program"
words = passage.split()
wordcount = len(words)
print(passage)
print("Number of words:",wordcount)
wordlength = list(map(len, words))
avwordlength = (sum(wordlength))/wordcount
print("Average word length:",avwordlength)
checked_words = []
word_amount = []
for x in range(wordcount):
        currentword = words(x)
        if currentword in checked_words:
                wordposition = checked_words.index(currentword)
                word_amount(wordposition) += 1
        else:
                checked_words.append(currentword)
                word_amount.append(1)
print(checked_words)
print(word_amount)

A: Round brackets is for functions, that is why the error tells you that it is trying to interpret word amount as a function. you need to use square brackets, also for the words list three lines above


text:
Q: How to create a user in SQLDeveloper with macOS? I currently have a mac and need to use Oracle SQLDeveloper for study purposes for university. Download SQLDeveloper on the official Oracle website, but unlike windows that have to install and enter a password for SYSTEM, when downloading SQLDeveloper it was an executable file that did not need a previous installation, the application works well, only I cannot use the user SYSTEM, since at no time enter a password, since I do not have a SYSTEM user, I cannot create a user and I cannot do my university work.
If any of you know how to find the SYSTEM password or how to create a user in any other way, I would be very grateful

A: As you'll be using Oracle for studying purposes, installing anything but its Express Edition (XE) is probably too much for you.
Unfortunately, you can't install XE directly on Mac OS. I don't have Mac so I can't speak from my own experience, but my colleague does and here's what he did: installed virtual machine under MS Windows and put Oracle XE onto it. He also has SQL Developer installed on the same virtual machine and uses everything in the same (Windows) environment.
I'd suggest you to do the same, unless there's a database available to you over the Internet (i.e. you can connect to a database DBA installed on a server that resides on the University); in that case, you'd need info about that database and establish connection once you're in the network (probably via VPN).
If you choose to use a virtual machine, there are walkthroughs available on the Internet; here's one of them: How to Install Oracle on a Mac, see if it helps.
Or, see which preinstalled virtual machines Oracle offers for download, here.


text:
Q: Kernel crash after idle in version 10.0 Bug introduced in 10.0.0 and fixed in 10.0.2

In version 10.0, when I leave the Mathematica section idle for some time (of order an hour), the kernel quit automatically. The syntax highlighting is gone and the variables that has defined before lost their values. There is no error message (tried to launch from terminal and still no error message).
This behavior has been noticed on my computer for many times. No operation is performed. Simply launch Mathematica 10 and wait (or define a variable and watch it gone). Mathematica 9 is installed side by side and has no such problem. I am using Linux (CentOS 7).
Anyone has the same problem, or any suggestions to further debug?
$Version

10.0 for Linux x86 (64-bit) (June 29, 2014)

uname -a

Linux localhost.localdomain 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

Update:
I unchecked Preference -> Internet Conectivity -> Allow the Wolfram System to access the Internet. The kernel hasn't crashed since this change is made.

A: To upgrade my comment to an answer, and perhaps give some more background information:
This bug has been fixed as of version 10.0.2. The crash happened in the libcurl library, which is being used in a separate thread via the HTTPClient package by the paclet manager at kernel startup to check for updates.  It had to do with thread safety in certain circumstances, namely a DNS resolver thread taking too long to complete its task. It is essentially the same problem described here or here.

A: Now that the workaround has worked for me for days without crash, let me put it as an answer myself. The crash (at least in my case) is because of the kernel tries to connect to internet and something wrong happened there. To solve the problem, uncheck
Preference -> Internet Conectivity -> Allow the Wolfram System to access the Internet


text:
Q: Design pattern for many asynchronous tasks in node I'm learning node and writing an API. One of my API calls takes a parameter called Tags, which will contain comma-delimited tags, each of which I want to save to disk (I'm using MongoDB + Mongoose). Typically when I save to DB in my API I pass a callback and carry on after the save inside of that callback, but here I have a variable number of objects to save to disk, and I don't know the cleanest way to save all of these tags to disk, then save the object which references them afterward. Can anyone suggest a clean async pattern to use? Thanks!

A: async is a good node library for these tasks..
run multiple async calls in parallel or in series and trigger one single callback after that:
async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);

A: This is common code pattern I often use when I don't want additional dependencies:
var tags = ['tag1', 'tag2', 'tag3'];
var wait = tags.length;
tags.forEach(function (tag) {
    doAsyncJob(tag, done);
});

function done() {
    if (--wait === 0) allDone();
}

This code will run doAsyncJob(tag, callback) in parallel for each item of array, and call allDone when each job completed. If you need to process data continuously (each after another), here's another pattern:
(function oneIteration() {
    var item = tags.shift();
    if (item) {
        doAsyncJob(item, oneIteration);
    } else {
        allDone();
    }
})();


text:
Q: How to get id of the anchor tag in angularjs? Hi I am developing Angularjs application. I have dynamically generated anchor tag. In anchor tag i am binding img only. So based on the img src clicked i want some computations.

This is my controller code.
 if ($scope.lang === 'ar-sa')
    {
        $translate.use('de_AR');
    }
    else
    {
        $translate.use('de_EN');
    }

Whenever i click on img i want to get that img name in controller. So that i can apply some computation like if use clicked on arabic.png then i can covert page to arabic. Any help would be appreciated. Thank you.

A: What you need to do is to add a function that change the language on the controller:
$scope.lang = null; // Default language
$scope.changeLanguage = function() {
    $scope.lang = $scope.lang == 'de_AR' ? 'de_EN' : 'de_AR'; // Change the language based on the current selected
    $translate.use($scope.lang);
}
$scope.changeLanguage(); // Set language when the controller loads

Next, in your view, you just need to call this function:

As an alternative, you can also pass the selected language:
$scope.changeLanguage = function( lang ) {
    $scope.lang = lang;
    $translate.use($scope.lang);
}
$scope.changeLanguage('de_AR');

And in the view:

Edit:
Since your default language is based on browser setting, you can do the following:
$scope.changeLanguage = function( lang ) {
    $scope.lang = lang === 'ar-sa' ? 'de_AR' : 'de_EN';
    $translate.use($scope.lang);
}
$scope.changeLanguage($window.navigator.language || $window.navigator.userLanguage);

View:

What I did in the above example is to check if the language (Which is the returned value of $window.navigator.language || $window.navigator.userLanguage) is equal to 'ar-sa' and if so, set the language to its matching i18n code.


text:
Q: Uninstall Vista update without being able to run Windows The PC of a friend will no longer boot into Windows (not even safe mode). I have recovered the crash dump file and run it through WinDbg. This indicates that the problem comes from WinInit.exe and the error is VISTA DRIVER FAULT
Also in my investigations I have found that 8 Windows upgrades were downloaded and installed the last time the PC booted OK, 5 of which were security updates. As the next step, I want to uninstall these updates but as I cannot boot into Windows I can't do it in the normal way.
I have tried using the restore points on the system, but there are non stored.
Is there any way I can revert or delete these updates only the drive in a seperate PC ?
Thanks
Paul

A: At this point it may well be quicker to do a repair install. Note you need a Vista DVD at the same or later service pack level to do this.

A: You need to use tools in DaRT (Diagnostic and Recovery Toolset), a part of Microsoft Desktop Optimization Pack.


text:
Q: PHP MS Access ODBC driver seems not to be able process Access DLookUp() Function in SQL statement The problem is this.  When I create an SQL statement in PHP to be processed by an MS-Access ODBC driver, the query will not process properly if I include a DLookUp() function in the Access SQL Statement. I have had this problem occur with JOIN clauses as well, but not all JOIN clauses.
I am running a query to process an order where I am retrieving preferences requested by the user.  These preferences are also used for statements.  e.g., I might ask, "what is the captain's name?" and the end-user will enter the name in the provided text box.  Yet in the preferences area, I will also make simple statements that don't need an answer like "Flagrant Fouls will not be tolerated".
The entry screen looks like this:

When I want to display these answers made by the user later, I run the following query in php,
$sqlPrefs = "SELECT pq.QText, wr.The_Answer, wr.webtmporders_detail_ID" .
  ", DLookUp('[IsStatement]','[tbl_Activities_Preference_Questions]','[PQ_ID]=' & [wr].[PQ_ID]) AS OnlyAStatement " .
  " FROM `tbl_Preference_Questions` pq" .
  " INNER JOIN `tblwebtmporders_detail_Requests` wr ON pq.PQ_ID = wr.PQ_ID" .
  " WHERE wr.webtmporders_detail_ID =" .  $detID .
  " ORDER BY wr.SortOrder";

$result_id_prefs = odbc_exec($connection_id, $sqlPrefs);
$numResults_prefs = odbc_record_count ($result_id_prefs, $connection_id, $sqlPrefs);
$results_prefs = all_odbc_rows($result_id_prefs);

if($numResults_prefs >0){
   $thePreferences = "
";
   foreach ($results_prefs as $result_pref)
   {
      $qtext = $result_pref['QText'];
      if($result_pref['OnlyAStatement'] == true){
         $thePreferences .= "

  $qtext

";
      }else{
         $thePreferences .= "

  $qtext
  " . $result_pref['The_Answer'] . "

";
      }
   }
}

I have left out some calls to a logging function I have written that will show me what the $sqlPrefs variable resolves to:
SELECT pq.QText, wr.The_Answer, wr.webtmporders_detail_ID,
 DLookUp('[IsStatement]','[tbl_Activities_Preference_Questions]','[PQ_ID]=' & [wr].[PQ_ID]) AS OnlyAStatement
FROM `tbl_Preference_Questions` pq
INNER JOIN `tblwebtmporders_detail_Requests` wr ON pq.PQ_ID = wr.PQ_ID
WHERE wr.webtmporders_detail_ID =76884
ORDER BY wr.SortOrder

When I run this SQL statement with the Query Design Tool in MS Access, the query returns 9 records:

however, when the same query is run via the ODBC call shown in the PHP code above, it only returns only 1 record all with null values.
If I take the DLookup Call out of the query, then the query via ODBC will return 9 records.
This is the review screen when the DLookup() function is included in the ODBC sql statement.

This is the screen when DLookup() is NOT included in the SQL statement run thru ODBC

What I am trying to do is fairly simple.  Notice the query results above.  the [OnlyAStatement] column is boolean.  If the item contains a statement only, and not a question and answer
if($result_pref['OnlyAStatement'] == true)

I want the statement to span across two columns, whereas if I am dealing with a Questions / Answer, I need two columns.  See the picture above with the yellow square.  I cannot determine if the sentence is a question / answer, or simply a statement, so i cannot manipulate the colspan attribute in the   tag.
Does anyone have any idea why the DLookup() is not successfully run in the ODBC call but it is run when run withing the MS-Access program itself?
Thank you.

A: DLookup() is part of the Access Application object model (docs), not the database engine.
Therefore you can't use it via ODBC.
In your case it is easily avoided by adding a second JOIN to tbl_Activities_Preference_Questions.
Note that you'll need parentheses around all JOINs except the first one in Access SQL.


text:
Q: Should I use docker with app services rather than app service direct? I am new to the world of docker and azure app services.
Proposed by a colleague:
ASP.net core app --> Create docker image --> Azure container registry --> Azure App service.
My experience:
ASP.net core app --> Deploy to Azure App service
We have been recommended to use a container with an app service layer on the top of this container.
I was wondering what are the main benefits of doing this rather than just deploying an app service direct?
With the app service we can scale out, scale up, add a load balancer use web api management etc, but not clear why I would add another layer but placing a container under it?
The app itself is a simple API asp.net core application - we have separated out the SQL server part into PaaS SQL.
Any guidance would be great as to the reasons.

A: If you are deploying as windows container, then I don't see benefit. In my opinion, it will actually lead to unnecessary complexity
If you are deploying as linux container, then there are couple of advantages

*

*You incur lower costs as no windows licensing cost needs to be given

*Performance increase as linux does not have lot of unwanted baggage


text:
Q: what is the linux equivalent of "lorder" solaris command? I'm trying to compile a sample code that should work both on Solaris and Linux. The make file on solaris run the command "lorder". There is a similar command for linux?
Thanks

A: lorder command was finding object files, I remember. I think you can use the updatedb and locate * .o command.
updatedb
locate *.o


text:
Q: Using Jquery and $(this).text() to replace th text I'm trying append a two digit year to a column header that is autogenerated for me. It seems like a simple problem.  I have this table

    Jan-
    Feb-

    January's data
    February's data

and this jquery
$(document).ready(

function () {
        var TwoDigitYear = '14';

    $('#DataTable1 th').each(function () {
        var curtext = $(this).text();
        if (curtext != "") {
            var newtext = curtext + TwoDigitYear;
            $(this).text(newtext);
        }
    });
}

);

For some reason, I can see the value changed if I put a console.log in the code, but the web page doesn't change.
Here's a jsfiddle:  http://jsfiddle.net/PasadenaJacket/Ztnvr/#base

A: Instead of DataTable1 you need to do Datatable1 then it should work.
See UPDATED FIDDLE HERE


text:
Q: UIView subclass (custom progress view) doesn't show up until it's too late I want to see progress while downloading some data (synchronously) but my UIView subclass (the custom progress view) doesn't show up until the download is finished. Here's some code:
self.progressView.hidden = NO;

// I would expect the progressView to show up now
// but it doesn't

int i = 0;
for (Something *something in someList) {
    if (something...) {
        i++;
        // do something

        // start downloading some data
        NSString *urlPath = [NSString stringWithFormat:@"somePath"];
        NSURL *aURL = [NSURL URLWithString:urlPath];

        NSData* responseData = [NSData aURL];

        // parse out the JSON data
        NSError* error = nil;
        NSArray* json = [NSJSONSerialization
                         JSONObjectWithData:responseData
                         options:kNilOptions
                         error:&error];

        for (NSDictionary *currentObject in json) {
            // do some stuff
        }
    }
}

// the progressView does show up here... why?

The progressView that I change to non-hidden BEFORE I download anything gets shown AFTER all download is done. Why is that so? And how can I show the progressView BEFORE all download stuff?

A: Because your download is blocking the main thread, using which the UI could otherwise update the contents of the screen. Solution: spawn a new thread for all the networking stuff.


text:
Q: number-of-matches-within-limits requesting CardDav server I recently tried to read alot of VCards from iCloud CardDav server. However I realized there is a limit on the 5000th vCard I request.
Here is my REPORT request:
<?xml version="1.0" encoding="utf-8" ?>
   <C:addressbook-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav">
   <C:filter>
      <C:prop-filter name="X-ADDRESSBOOKSERVER-KIND" test="anyof">
         <C:is-not-defined />
         <C:text-match collation="i;unicode-casemap" match-type="equals" negate-condition="yes">group</C:text-match>
      </C:prop-filter>
   </C:filter>
</C:addressbook-query>

And here is the end of the server answer:
<response>
   <href>/872816606/carddavhome/card/</href>
   <status>HTTP/1.1 507 OK</status>
   <error><number-of-matches-within-limits/></error>
</response>

Is there a way to query the next page?
Thanks in advance.

A: CardDAV all by itself does not offer a paging mechanism. WebDAV Sync (https://www.rfc-editor.org/rfc/rfc6578) on the other hand does provide paging, although not all server implementations do support paging.
Now, if understand your query, you are pretty much asking for all contacts in the collection, except for groups. Unless you have a very large number of groups, you probably want to filter them on the client side, in which case you can use a regular PROPFIND (or WebDAV Sync REPORT), followed by series of CarDAV multiget REPORTs, which is what most clients do.


text:
Q: How to block macro execution after a specific time (license end)? I'm a VBA beginner. An excel of the company has already been well edited with multiple macros long time ago and it will be used by our clients. The problem is we want to block their utilisation of macros in several months after the project is finished. Is there a simple way that all macros will be deactivated when coming to a specific date or a password of protection will be activated from a certain date?
Thank you in advance !

A: You could implement a Sub which does a RaiseError if the date is later than a certain value, then call this Sub from all your macros as their very first operation.
Now, when you provide these functionalities to the clients/users, you will only have to override the date you compare the current date with.
This is how you can get today's date in VBA: https://www.automateexcel.com/vba/todays-current-date/
This is how you can compare two dates in VBA: Compare Dates in VBA


text:
Q: Find and Replace for Named Ranges For some reason the Replace Function I have in this Macro doesn't if i change the value of the for YTD and YTG to ",9," and ",12," the Macro won't work. Here is what I have.
  Sub Rename()
   Dim YTG As String
   Dim YTD As String
   Dim Shiftold As String
   Dim Shitnew As String

i = 1

YTG = "<>YTG"
YTD = "YTD"
Shiftold = "0,0,1"
ShiftNew = "0,12,1"

For Each Name In ActiveWorkbook.Names
    If InStr(1, Names(i).RefersTo, YTG) > 0 Then
    Names(i).RefersTo = Replace(Names(i).RefersTo, YTG, YTD)
    End If

    If InStr(1, Names(i).RefersTo, Shiftold) > 0 Then
    Names(i).RefersTo = Replace(Names(i).RefersTo, Shiftold, ShiftNew)
    End If

    i = i + 1
Next Name
End Sub

Any thoughts on why the macro doesn't work anymore?

A: I strongly recommend using Option Explicit to force variable declarations, which will catch typos and (most) missing declarations.
Rename is a terrible choice of macro name (like Name is a bad choice of variable name) because it overlaps with common methods etc. and in this case gives little idea of what is actually going to be affected.
As observed in comments you weren't actually using the For Each loop variable. This makes it fairly pointless , but actually would be a much better way of accessing elements of the collection.
Below is my suggested improvements; notice that the comments are talking about how I've changed it, so you should actually add some comments describing real purpose rather than using these.
Sub UpdateNamedRanges() ' specific macro title

Dim YTG As String
Dim YTD As String
Dim ShiftOld As String
Dim ShiftNew As String ' corrected
Dim AName As Name   'declared

YTG = "<>YTG"
YTD = "YTD"
ShiftOld = "0,0,1"
ShiftNew = "0,12,1"

For Each AName In ActiveWorkbook.Names
    ' use loop variable
    If InStr(1, AName.RefersTo, YTG) > 0 Then
        AName.RefersTo = Replace(AName.RefersTo, YTG, YTD)
    End If

    If InStr(1, AName.RefersTo, ShiftOld) > 0 Then
        AName.RefersTo = Replace(AName.RefersTo, ShiftOld, ShiftNew)
    End If
Next AName

End Sub


text:
Q: C# Winforms - When are scrollbars for a Control initialized? Here is the situation:
I am trying to control flowLayoutControl's scroll bar from devexpress controls VerticalScroll.
Now - flowLayoutControl with autoscroll = true. I added a new verticalscroll control and dock it to Right. So now the Devexpress Vertical Scroll control is right on top of FlowLayout scrollbar.
Also the FlowLayoutPanel vertical scroll does not hide when following code is run:
    spotWinFlowLayout1.VerticalScroll.Visible = false

I have setup the following event handlers:
    private void spotWinFlowLayout1_Resize(object sender, EventArgs e)
    {
        SetupVerticalScrollBar();
    }

    private void SetupVerticalScrollBar()
    {
        vScrollBar1.Minimum = spotWinFlowLayout1.VerticalScroll.Minimum;
        vScrollBar1.Maximum = spotWinFlowLayout1.VerticalScroll.Maximum;
        vScrollBar1.LargeChange = spotWinFlowLayout1.VerticalScroll.LargeChange;
        vScrollBar1.SmallChange = spotWinFlowLayout1.VerticalScroll.SmallChange;
    }

    private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
    {
        spotWinFlowLayout1.VerticalScroll.Value = e.NewValue;
    }

Everything is working fine except when on form Load there is already a scrollbar on flowLayoutControl,
spotWinFlowLayout1.VerticalScroll.XXX properties not set yet. So both the scrollbars are out of Sync. But as soon as I resize the form both get Sync.
So when is scrollbar for the FlowLayoutPanel initialized?

A:
So when is scrollbar for the
  FlowLayoutPanel initialized?

This might sound like a smartalec answer: "When the control is drawn or placed on the form" which is the reason when you adjust the size of the form they are in sync.( they are being drawn again )
The solution is to manually add the scrollbars yourself.


text:
Q: Pyinstaller installation in DebIan Linux I am on Debian Linux and I am trying to install Pyinstaller, for making a standalone exe file from python script, into my debian linux. I downloaded from this link to get Pyinstaller. But can't find proper installation instruction and found one discussion here.
What I did was
(1) go to the pyinstaller folder and
    sudo python setup.py
    The error is
Traceback (most recent call last):
  File "setup.py", line 14, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

(2) I don't have source/linux folder in my Pyinstaller folder according to the discussion in the second link.
Where can I find proper instruction for the installation. Even in this manual, it is not clear how to install for Linux.
Thanks

A: you need to install python-setuptools
sudo apt-get install python-setuptools

Installation pyinstaller:
You can pip install the pyinstaller
pip install pyinstaller

if you do not have pip then you can install pip using
sudo apt-get install python-pip


text:
Q: Trait implementation with specific struct as parameter I have a trait for readable and writable streams (like TcpStream):
pub trait MyTraitPool<T: Read + Write> {
    fn acquire(&self, &String) -> T;
    fn free(&self, T);
}

I want to implement that trait with TcpStream as T, so I would like to write
struct MyPool;

impl<T> MyTraitPool<T> for MyPool
    where T: Read + Write {

    fn acquire(&self, addr: &String) -> T {
        TcpStream::connect(addr.as_str()).unwrap()
    }

    fn free(&self, con: T) {
        con.shutdown(Shutdown::Both);
    }
}

I get the error "expected type parameter, found struct std::net::TcpStream" in the acquire method. As for the free method, I know that shutdown is TcpStream-specific, but I would like to have an implementation specific for TcpStreams at that point and hence be able to call TcpStream-specific methods. So how do I go about doing so?
As a side note: the implementation is just an example for what kind of things I would like to do, not for how the code operates later!

A: Instead of making the MyTraitPool trait generic, you'd make your MyPool generic and you'd create an intermediate MyStream trait to offer you all methods you need:
trait MyStream: Read + Write {
    fn connect(&str) -> Self;
    fn shutdown(self);
}
impl MyStream for TcpStream {
    fn connect(addr: &str) -> Self { TcpStream::connect(addr) }
    fn shutdown(self) { TcpStream::shutdown(self, Shutdown::Both); }
}
impl<T: MyStream> MyTraitPool for MyPool<T> {
    fn acquire(&self, addr: &str) -> T {
        MyStream::connect(addr)
    }
    fn free(&self, con: T) {
        con.shutdown()
    }
}

Streams which do not actually need to shutdown, would simply leave the implementation empty.


text:
Q: How would I check the value in form before sending it to server using ajax I want to check the value enter in the form by user. i have applied validation and its working. The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
I want that validations is checked before passing it to server. One of my friends told me its possible with AJAX. Can anyone guide a beginner on how to do this?

A: You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server)
Jquery has a plugin called validation that will make your life easier though:
http://docs.jquery.com/Plugins/validation
There is a live demo in the link above
For example if you wanted to validate the username you could do this
  <script>
  $(document).ready(function(){
    $("#commentForm").validate();
  });
  </script>

<form  id="commentForm">
<input id="uname" name="name" class="required"  />
</form>

A: yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. with ajax you can show response from the server to show to the user.
    $.ajax({
         url: 'ajax_login.php',
         type:'post'.
         data:(/*data from form, like,*/ id: $('#username').val())
         success: function( data ) {
              if(data == 1) {
                   $('.feedback').html('data has been saved successfully');
                   //redirect to another page
              }
              else {
                    $('.feedback').html('data could not be saved');
                    $('.errors').html(data);
              }
         }
    });

    ajax_login.php would be something like
    <?php
            if(isset($_POST)) {
                 //do form validation if it is valid
                 if(form is valid) {
                      saveData();
                      echo 1;
                 }
                 else {
                      echo $errors;
                 }
            }
    ?>

A: Do not need ajax.
Just set the onsubmit attribute of your form to "return checkfun();" and define checkfun some way like this:
function checkfun()
{
    if ( all things were checked and no problem to submit)
       return true;
    else
    {
       alert('ERROR!');
       return false;
    }
}


text:
Q: How to get user info after successful authentication with django-rest-framework-jwt in angularjs I'm working on a project with django and angularjs where I need to use djangorestframework-jwt for authentication. I'm new to djangorestframework-jwt. I use '/api-token-auth/' for login, but I don't get any user information.
My authentication services is:
function login (username, password, callback) {
        return $http.post('/api-token-auth/', {
            username: username, password: password
        }).then(loginSuccessFn(callback), loginErrorFn);

        function loginSuccessFn (callback) {
            return function (data, status, headers, config, response) {
                localStorage.setItem('empee.token',data.data.token);
                $http.defaults.headers.common['Authorization'] = 'Bearer ' + data.data.token;
                if (typeof callback !== 'undefined') {
                    callback();
                }
            }

        }

        function loginErrorFn (data, status, headers, config) {
            console.error('Epic failure!');
        }
    }

Login controller:
function login() {
        Authentication.login(vm.username, vm.password, function() {
            $state.go('dashboard');
        });
    }

A: Considering you have User URL exposed in Django-rest-framework, you can do a $http.get.
$http.get('/user-url/'+userid).then(function(response){
    if(response.status === 200){
        user_obj = response.data;
    }
});

To get the userId, All you would need to user angular-jwt
userid = jwtHelper.decodeToken(token).user_id;


text:
Q: Firebase onMessage() not receiving messages I'm developing a Firebase real-time messaging app. I've successfully managed to upload the browser/device token into the collection in the Firestore, but when I'm trying to test if the messages are being received in the app, I'm not getting any.
Here are some parts of my code.
  <!-- The core Firebase JS SDK is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-messaging.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-functions.js"></script>

  <script>
    var firebaseConfig = {
        ---- PRIVATE ----
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>

  <script src="firebase-messaging-sw.js?v=2156"></script>

Already tried writing the necessary code for the firebase-messaging-sw (https://stackoverflow.com/a/50078103/3881610) but I'm getting an error saying:

Uncaught FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).

I also have the code to receive messages in the page:
var messaging = firebase.messaging();
messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
});

Also made sure that messages are being SENT to the device token using Postman and works just fine.
Any thoughts? Thanks!

A: At first, firebase-messaging-sw.js is service worker JavaScript file.
See Firebase messaging importScripts is not defined
And could you try samples?
See:

*

*https://github.com/firebase/quickstart-js/tree/master/messaging

*https://github.com/firebase/functions-samples/tree/master/fcm-notifications


text:
Q: Calling a method within a method? How does this work in this scenario? (Java) This is a program that using merge sort - sorts a list of 1000 numbers from 1 - 1000.
It displays the original list, then calls a recursive method to sort it, then displays it.
What I do not understand within the code are these two lines:

MergeSort (numbers, low, middle);  // within method it will say "HERE"
MergeSort (numbers, middle + 1, high);

I am a beginner in java and this goes against everything I learned as I cant comprehend how you can call a method within a method. Unless its a object whcih I doubt. Could someone explain me what these two lines of code do?
import java.io.*;
import java.util.*;
import java.text.*;

public class MergeSortExample
{
    static final int Max = 1000;

    static void MergeSort (int[] numbers, int lo, int n) // recursive method
    {

        int low = lo; // 0
        int high = n; // 999

        if (low >= high) // return case;
        {
            return;
        }

        int middle = (low + high) / 2;
        MergeSort (numbers, low, middle); // HERE
        MergeSort (numbers, middle + 1, high); // HERE

        int end_low = middle;
        int start_high = middle + 1;

        while ((lo <= end_low) && (start_high <= high))
        {
            if (numbers [low] < numbers [start_high])
            {
                low++;
            }
            else
            {
                int Temp = numbers [start_high];

                for (int k = start_high - 1 ; k >= low ; k--)
                {
                    numbers [k + 1] = numbers [k];
                }
                numbers [low] = Temp;
                low++;
                end_low++;
                start_high++;
            }
        }

    }

    public static void main (String str[]) throws IOException
    {
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
        DecimalFormat df = new DecimalFormat ("#");
        BufferedReader reader = new BufferedReader (new FileReader ("unsorted.txt"));
        //BufferedWriter writer = new BufferedWriter (new FileWriter ("test.txt", true)); // text to write

        int[] numbers = new int [Max];  // if its int the 0's in the beginiing would be cut off
        String line = null;
        int[] count = {0};

        int low = 0;
        int high = count [0] - 1;

        while ((line = reader.readLine ()) != null)
        {
            numbers [count [0]] = Integer.parseInt (line);
            System.out.println (numbers [count [0]]);

            count [0]++;
        }
        reader.close ();
        System.out.println ();
        System.out.println ("There are " + count [0] + " numbers.");
        System.out.println ();

        ///////////////////////////////////////////////////////////////////////////////

        MergeSort (numbers, 0, count [0] - 1);

        for (int i = 0 ; i < count [0] ; i++)
        {
            System.out.println (numbers [i]);
        }

    }
}

A: It's basic recursion.  A merge sort works by splitting the list into two parts, merge sorting each one, and then merging the two lists together.  The part you are asking about is the part that merge sorts each of the two parts.

A: It is a recursive call of static method MergeSort(). Bad convention is used here. Names of methods should start with a lower case

A: Of course a method may invoke another method. The only confusing part here is that this method is static, which means it is invoked on a class instead of an object. Since it is called inside of the class it is defined in, you do not need to write MergeSortExample.MergeSort(). If you want to understand the differences between static and instance methods and fields, I suggest you look at the tutorials on the Java website.


text:
Q: Connecting new BizTalk node to cluster fails with EntSSO I've been tasked with setting up a new, third, node in our BizTalk 2013 R2 cluster. The server is up and connected to the windows cluster. BizTalk is installed and patched to CU8, the same patch level as the other nodes.
When I try to configure the BizTalk installation everything works fine with the Enterprise SSO part, However as soon as I try joining the BizTalk installation to the group I get the error:

You have specified to join a BizTalk group that is pointing to a
  different Enterprise Single Sign-On (SSO)  Master Secret Server.  You
  will need to re-configure the local Enterprise Single Sign-On to join
  to the  same SSO system.

I've tried the following:

*

*Changed the SSO database with ssomanage to point to the exact location as the other, secondary, node we have.

*Delete the BizTalk config and started from scratch

*Change the MSDTC settings to correspond with the ones seen on the secondary node

*Restarted the server

I've tried googling the issue but can't find anything, everything LOOKS like it's in order, but obviously not. If I look in the Event Log I find this:
The SSO service is starting.
Computer Name: Server3
SQL Server Name: DbCluster1
SSO Database Name: SSODB
Not using SSL. See documentation for details on how to secure the SQL Server connection.

Followed by:
Got the current secret from the master secret server.
Secret Server Name: DbCluster1MSDTC
MSID: 8b3af315-d9e6-46b0-a5d4-ab354d43644c

And followed by:
Got the previous secret from the master secret server.
Secret Server Name: DbCluster1MSDTC
MSID: 8b3af315-d9e6-46b0-a5d4-ab354d43644c

Which seems, to me, like EntSSO gets all data needed. However after this I find this in the EventLog:
The run-time environment was unable to initialize for transactions required to
support transactional components. Make sure that MS-DTC is running.
(DtcGetTransactionManagerEx(): hr = 0x8004d01c)

Not sure if this is connected in any way, but I do know that I'm all but out of ideas on how to solve this. Google is usually my friend, not today though.
Any ideas?

A: Unconfigure anything on the new server.
Run BizTalk Setup again and remove the Enterprise Single Sign-On Master Secret Server option under Additional Software.
That's actually the Master Secret Server which you already have.  The SSO client comes with the BizTalk Runtime option.
Then reconfigure the new server joining the new server to SSO and Group.


text:
Q: API doesn't register all the requests I have a website with a php page that communicate with a Jira witch is an Atlassian product, jira sends an API post request the Jira.php page registers the API payload in MyNewFile.txt file in jira2.php I proceed with getting the Json payload from the MyNewFile.txt and compare it with the MyNewFile2.txt and when the page dashboard.php Javascipt detects a new post request it values THE  global variable json to true  so jira2.php can populate the database with the json content. BUT this doesn't always work, sometimes is doesnt populate the DB with the new json content, I think its my ajax call
  jira2.php
 function compareFiles($file_a, $file_b){
        if (filesize($file_a) != filesize($file_b))
            return false;

        $chunksize = 4096;
        $fp_a = fopen($file_a, 'rb');
        $fp_b = fopen($file_b, 'rb');

        while (!feof($fp_a) && !feof($fp_b))
        {
            $d_a = fread($fp_a, $chunksize);
            $d_b = fread($fp_b, $chunksize);
            if ($d_a === false || $d_b === false || $d_a !== $d_b)
            {
                fclose($fp_a);
                fclose($fp_b);
                return false;
            }
        }

        fclose($fp_a);
        fclose($fp_b);

        return true;
    }

if($_POST['json']=="true")
          {
             //  json payload
            $json = file_get_contents('myNewFile.txt');
            $data = json_decode($json,true);

if(!compareFiles("myNewFile.txt","myNewFile2.txt")){
            // populate db
             code....
     }

jira.php
<?php
$_POST['js']=file_get_contents("php://input");
file_put_contents('myNewFile.txt',$_POST['js']);

$arr = json_decode($_POST['js'],true);

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

?>

dashboard.php
<script>
var update = function() {
           $.ajax({
         type : 'POST',
         url : 'jira2.php',
         data:{json:"true"},
         success : function(){
            //  var refInterval = window.setInterval('update()', 3000); // 1 seconds
         },
     });

 };
 var previous = "";

setInterval(function() {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            if (ajax.responseText != previous) {
                update();
                var refInterval = window.setInterval('update()', 1000); // 1 seconds
                previous = ajax.responseText;
            }
        }
    };
    ajax.open("POST", "myNewFile.txt", true); //Use POST to avoid caching
    ajax.send();
}, 1000);

 </script>


text:
Q: Input type number doesn't work on Window Surface Tablet i've noticed that if we try to open https://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_number
in Chrome on Windows Surface Tablet it will behave as in desktop browser.
I mean on Tablet(mobile) device if i tap on <input type="number"> than Chrome will show number keyboard. But on Surface Chrome will show text keyboard.

In addition, mobile browsers further help with the user experience by
  showing a special keyboard more suited for entering numbers when the
  user tries to enter a value.
   developer.mozilla.org

Is there a way how to force Chrome on Windows Surface to behave as mobile browser? At least for number field?

A: I don't have a Windows Surface with Chrome to test on, but try
 <input inputmode="numeric" pattern="[0-9]*" type="text" name="something">

This should still force the browser to open the number keypad


text:
Q: Turtle Key Bindings So, I've written a program in turtle that draws using mouse-click binds, and I've created a bind to change the colour of the pen, but it only works once and I was wondering if there was a way so that the key-bind will call the function assigned to it every-time the key is pressed, rather than just once.
Here's my code currently:
from turtle import*

def Penoff(x,y):
    penup()

def Penon(x,y):
    pendown()

def colour():
    Colour = "white"
    Colour = textinput("Colour", "What Colour do you want to change to: ")
    color(Colour)

pensize(3)

setup (1000,600)
speed (8)

onscreenclick(goto)
onscreenclick(Penoff, btn = 2)
onscreenclick(Penon, btn = 3)

onkeypress(colour, "space")
listen()

mainloop()

A: When you invoke textinput(), turtle makes its text input dialog the key event listener, so after the call you need to invoke listen() again to make your main window listen for key events:
def colour():
    Colour = textinput("Colour", "What Colour do you want to change to:")
    listen()
    if Colour:
        color(Colour)


text:
Q: I want to generate the hyperlink for all figure callout in the text and id should be same as figure id Please check and suggest,
what should be the right code and idref value should be same as figure id. I am trying with analyze-string but unable to do.
Please check and suggest,
what should be the right code and idref value should be same as figure id. I am trying with analyze-string but unable to do.
input
<book>

        Figure 01

xxx

This is a Figure 01 and this is figure 02

This is a Figure 01 and this is figure 02

        Figure 02

xxx

</book>

output
    <book>

        Figure 01

xxx

This is a <internal idref="ch01fig01">Figure 01</internal> and this is <internal idref="ch01fig02">Figure 02</internal>

This is a <internal idref="ch01fig01">Figure 01</internal> and this is <internal idref="ch01fig02">Figure 02</internal>

        Figure 02

xxx

</book>

xslt
        <xsl:output indent="yes"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//text()[not(parent::label)]">
        <xsl:analyze-string select="." regex="figure\s+\d+" flags="i">
            <xsl:matching-substring>
                <internal>
                    <xsl:attribute name="idref">
                        <xsl:call-template name="mk">
                            <xsl:with-param name="mk11" select="."/>
                        </xsl:call-template>
                    </xsl:attribute>
                    <xsl:value-of select="."/>
                </internal>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
</xsl:template>

    <xsl:template name="mk">
        <xsl:param name="mk11"/>
        <xsl:for-each select="//figure">
            <xsl:if test="child::label eq $mk11">
                <xsl:value-of select="@id"/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

A: First consider using a key to look up the figures...
<xsl:key name="figures" match="figure" use="lower-case(label)" />

(I am using lower-case here, because you have a "figure 02" in the text, but "Figure 02" in the label).
Your main problem is that within xsl:matching-substring you are no longer within the context of the original node you are matching, so you are probably getting an error along the lines of "the context item is not a node"
To get around this, define a variable to allow you to reference the original document...
<xsl:variable name="doc" select="/" />

Then to get the figure value using the key, you can do this...
<xsl:value-of select="key('figures', lower-case($mk11), $doc)/@id" />

So, this will look up the key in the context of the original document.
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output indent="yes"/>
   <xsl:key name="figures" match="figure" use="lower-case(label)" />
   <xsl:variable name="doc" select="/" />

   <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//text()[not(parent::label)]">
        <xsl:analyze-string select="." regex="figure\s+\d+" flags="i">
            <xsl:matching-substring>
                <internal>
                    <xsl:attribute name="idref">
                        <xsl:call-template name="mk">
                            <xsl:with-param name="mk11" select="."/>
                        </xsl:call-template>
                    </xsl:attribute>
                    <xsl:value-of select="."/>
                </internal>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>

    <xsl:template name="mk">
        <xsl:param name="mk11"/>
        <xsl:value-of select="key('figures', lower-case($mk11), $doc)/@id" />
    </xsl:template>
</xsl:stylesheet>

In fact, you can simplify this by doing away with the named template, and making use of Attribute Value Templates to create the idref attribute
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output indent="yes"/>
   <xsl:key name="figures" match="figure" use="lower-case(label)" />
   <xsl:variable name="doc" select="/" />

   <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="//text()[not(parent::label)]">
        <xsl:analyze-string select="." regex="figure\s+\d+" flags="i">
            <xsl:matching-substring>
                <internal idref="{key('figures', lower-case(.), $doc)/@id}">
                    <xsl:value-of select="."/>
                </internal>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>

A: I used another way instead of the key as well it is also working good. Below is code done some changes.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:variable name="figs" select="//figure" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()[not(parent::label)]">
        <xsl:choose>
            <xsl:when test="matches(., 'Figure', 'i')">
                <xsl:analyze-string select="." regex="(Figure ([0-9]+))" flags="i">
                    <xsl:matching-substring>
                        <xsl:variable name="ids" select="for $ss in $figs
                            return
                            if(matches($ss/label, regex-group(1), 'i'))
                            then $ss/@id
                            else ()"></xsl:variable>
                        <internal idref="{$ids[1]}">
                            <xsl:value-of select="."/>
                        </internal>
                    </xsl:matching-substring>
                    <xsl:non-matching-substring>
                        <xsl:value-of select="."/>
                    </xsl:non-matching-substring>
                </xsl:analyze-string>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

Below is the outcome after running XSLT.
<?xml version="1.0" encoding="UTF-8"?>
<book>

        Figure 01

xxx

This is a <internal idref="ch01fig01">Figure 01</internal> and this is <internal idref="ch01fig02">figure 02</internal>

This is a <internal idref="ch01fig01">Figure 01</internal> and this is <internal idref="ch01fig02">figure 02</internal>

        Figure 02

xxx

</book>


text:
Q: What are active constraints? I am asked why the constraint $x_1\leq 2$ would be active when maximizing
$$ 8(x-1)^2 +2(y-1)^2  $$
subject to
$$12x+12y=126$$
But I am not sure what it means for a constraint to be active.
We are using Lagrangians to do this.

A: This means the constraint is binding, i.e., the solution without the constraint is different from the solution with the constraint*. Just compute the lagrange solution without the constraint $x\le 2$. Then if you find that $x>2$, then you know the solution would have been different if you had imposed the constraint.
*This is not quite right if there is more than one constraint, see the comment from David below. In that case, you need to check if the solution is at the corner of the constraint to determine whether it is active.


text:
Q: What happens if I replace a *unique natural number* that form a commutative Monoid with *the set of integers* Z that form a commutative Ring?
In mathematical logic, a Gödel numbering is a function that assigns to each symbol and well-formed formula of some formal language a unique natural number, called its Gödel number. The concept was used by Kurt Gödel for the proof of his incompleteness theorems. (Gödel 1931)
The natural numbers, N, form a commutative monoid under addition (identity element zero), or multiplication (identity element one). A submonoid of N under addition is called a numerical monoid.
  The positive integers, N ∖ {0}, form a commutative monoid under multiplication (identity element one).
The set of integers Z forms a commutative ring under addition and multiplication

What happens if I replace a unique natural number that form a commutative Monoid with the set of integers Z that form a commutative Ring ?
The more specific question should be: What happens if I use (not if I replace) a unique natural number that form a commutative Monoid as (not with) the set of integers Z that form a commutative Ring ?
Monoid $\Rightarrow$ Ring
P.S: I don't want replace formally but I do not want to really change, but to make it believe that it is as if I had replaced.

A: The purpose of Gödel coding is the process of arithmetization, by which syntactic or other combinatorial ideas that are not directly expressible in arithmetic can be simulated by a process of faithful representation. The point is that in our arithmetic theories, we are entitled to refer to concepts such as formulas and proofs and so on, by means of the Gödel codes.
Meanwhile, the structure of the natural numbers $\langle\mathbb{N},+,\cdot,0,1\rangle$ is bi-interpretable with the structure of the integers $\langle\mathbb{Z},+,\cdot,0,1\rangle$, in the sense that each of these structures can define a copy of the other, in such a way that it can also definably see how it is translated into the others. Namely, the natural numbers $\mathbb{N}$ are the sums-of-four-squares in $\mathbb{Z}$, and there are diverse ways to define a copy of $\mathbb{Z}$ inside $\mathbb{N}$.
So although it is traditional to take the Peano axioms PA as an axiomatization of the natural numbers $\mathbb{N}$, one can translate the axioms to make a equivalent corresponding axiomatization of $\mathbb{Z}$.
In this sense, it doesn't matter whether you use natural numbers or integers in the Gödel coding; doing so will achiever the same ends in the end. There is essentially no fundamental difference in the ideas and methods.

A: Suppose you were trying a similar attempt of arithmetization, but you decided to do so for Presburger arithmetic. Well, there would be a couple of problems. The first is that you have only addition, so that your possibilities for encoding are limited, and it would be challenging to find a unique code for every statement, AND be able to refer to this code inside the theory. The second is that Presburger arithmetic is decidable, so you cannot get an incompleteness result like that of Goedel: you can tell which statements are true of the (additive) monoid of the natural numbers.
The reason Goedel chose (the semiring of) natural numbers is because the theory he was working with had as a model the natural numbers with multiplication and addition.  If you chose to axiomatize properties of another structure such as a commutative ring, you could try to use the language to code statements by members of the structure, but you could not necessarily get the results Goedel did; it depends on whether the theory of the structure is (inherently? I forget the technical adjective) undecidable.
Gerhard "The Other Hand Has Fingers" Paseman, 2019.01.02.


text:
Q: Proper and most efficient way to iterate through an NSMutableSet? Some Context: In my destructible terrain library for Cocos2D, one of the features is collapsable terrain. In order to collapse efficiently, I store the columns whose pixels have been altered in a NSMutableSet which contains NSNumbers which contain integers. I am using this data structure because I don't want to iterate over duplicate columns.
My first instinct for how to loop through the NSMutableSet was to use a 'for in' loop.
for (NSNumber * col in [alteredColumns allObjects]) { // Works
// for (NSNumber * col in alteredColumns) { // Crashes
    int x = col.intValue;
    bool shouldShift = false;
    bool alphaFound = false;
    for (int y = (size_.height -1); y >= 0; y--) {
        if (!shouldShift) {
            if ([self pixelAt:ccp(x,y)].a == 0) {
                // Need to shift all pixels above one down
                alphaFound = true;
            } else if (alphaFound) {
                didCollapse = shouldShift = true;
                // Ensure the top pixel is alpha'ed out if a collapse will occur
                [self setPixelAt:ccp(x,0) rgba:ccc4(0, 0, 0, 0)];
                [self setPixelAt:ccp(x,(y+1)) rgba:[self pixelAt:ccp(x,y)]];
            } // end inner if
        } else {
            // Need to shift pixels down one
            [self setPixelAt:ccp(x,(y+1)) rgba:[self pixelAt:ccp(x,y)]];
        } // end if
    } // end inner for
    // Remove column from cache if no pixels collapsed
    if (!shouldShift) [alteredColumns removeObject:col];
} // end outer for

However, this led to bad results. The program would crash with a Bad Access Memory error. If I alter the for loop to use [alteredColumns allObjects], then everything works just fine. So Questions... Can a 'for in' loop not be used on an unordered collection such as a NSMutableSet? If I must use a method such as allObjects, is this efficient?
Thanks in advance!

A: if (!shouldShift) [alteredColumns removeObject:col]; //1

In this line you modify alteredColumns. Modifying collections while enumerating is a bad, bad thing. If you are lucky, you'll get BAD_ACCESS, at the worst you won't even notice that something went wrong till you get totally unexpected behaviour.
for (NSNumber * col in [alteredColumns allObjects]) //2

Here you create an NSArray ([NSSet allObjects] returns an NSArray), and enumerate this array. When you modify alteredColumns in line //1, enumerated array is not mutated.
for (NSNumber * col in alteredColumns) { //3

And with this line you are enumerating alteredColumns, which is modified in line //1.

A: - (void)enumerateObjectsUsingBlock:(void (^)(id obj, BOOL *stop))block


text:
Q: Process of the max of a gaussian process I know how to calculate the distribution of the max of a Gaussian process.
I am now wondering what's its process. Are its properties known? (For instance I guess that the length of constant parts are distributed as the times of return to the origin for a Gaussian process).
I can hardly find literature by googling "Process of the max of a gaussian process" because I get "max of a gaussian process" results. Anyone knows the relevant equation/facts/literature?


text:
Q: Expand Word table VBA I am using a VBA macro to insert rows (two columns) in a word document. The problem is the inserted rows don't fill the entire page and all the columns don't have the same width:

My question is: how to give the same width to all the columns and to expand the table to fill the page width?
Here is my function:
Private Function CreateWordDoc(ByVal wrdApp As Word.Application, ByRef Objects() As OwnClass, ByVal sFilename As String, ByVal sPath As String)
    Dim i As Integer
    Dim wrdDoc As Word.Document
    Dim MyObj As OwnClass

    Dim wrdTppTable As Word.Table

    Set wrdDoc = wrdApp.Documents.Add(sFilename, Visible:=True)

    Set wrdTppTable = wrdDoc.Tables(2)

    For i = 0 To UBound(Objects) - 1
        Set MyObj = Objects(i)
        ' Add a row to the table and select it
        wrdTppTable.Rows.Add.Select
        ' Work with the selected row
        With wrdApp.Selection.Range
            ' Make sure the row is on two columns
            .Cells.Split 1, 2, True
            ' Set the text font parameters
            With .Font
                .ColorIndex = wdBlack
                .name = "Arial"
                .size = 11
                .Bold = False
            End With
            ' Write text in the cell
            .Text = MyObj.GetKey & ": " & MyObj.GetValue
            ' Then select the next cell in the row
            .Next.Select
        End With
        ' Work with the second column of the row
        wrdApp.Selection.Cells.SetWidth 54, RulerStyle:=wdAdjustFirstColumn
        With wrdApp.Selection.Range
            With .Font
                .ColorIndex = wdBlack
                .name = "Arial"
                .size = 11
                .Bold = False
            End With
            ' Write the cell
            .Text = MyObj.GetId
        End With
    Next
End Function

A: The best thing you can do to accomplish what you are after is setting up the dimensions of the columns at the start, before performing any modification. Sample code:
Dim availableWidth As Integer
availableWidth = wrdDoc.PageSetup.PageWidth - wrdDoc.PageSetup.LeftMargin - wrdDoc.PageSetup.RightMargin

With wrdTppTable
   .Columns.Add 'Adding the required column
    'Resizing both columns on account of the available space
   .Columns(1).Width = availableWidth / 2
   .Columns(2).Width = availableWidth / 2
   .Cell(1, 1).Merge .Cell(1, 2)
End With

Right after this code you can start iterating through the cells and performing the actions you want, just by adding rows. Use Cells.Split only in case of really needing it; for example: in the third row you want to have three columns, two of them fitting within the main second column.