text:
Q: Cambiar imágenes con JavaScript Estoy creando JS para imágenes rotatorias, es decir, tendremos varias fotos colocadas en una misma posición que cambiarán cada "x" segundos.
Ya hice los array de las imágenes. Creé la variable contador para ir recorriendo las posiciones de los arrays y otra variable para asignar el tiempo que permanecerán visibles los banners.
También ya hice la función que nos cambie la foto del banner cada "x" segundos.
Actualmente cambian las fotos pero el problema es que solamente cambia dos veces, es decir, "foto a" y "foto b" aun cuando en los array existan "foto a", "foto b", "foto c", "foto d", etc.
Esto es lo que tengo en código:

/* ARRAY DE IMAGENES 1 */
ads = new Array(4);
ads[0] = "http://diosmediante.com/img/imgx.png";
ads[1] = "http://diosmediante.com/img/imgx_a.png";
ads[2] = "http://diosmediante.com/img/imgx_b.png";
ads[3] = "http://diosmediante.com/img/imgx_c.png";

/* ARRAY DE IMAGENES 2 */
ads2 = new Array(5);
ads2[0] = "http://diosmediante.com/img/imgx2.png";
ads2[1] = "http://diosmediante.com/img/imgx2_a.png";
ads2[2] = "http://diosmediante.com/img/imgx2_b.png";
ads2[3] = "http://diosmediante.com/img/imgx2_c.png";
ads2[4] = "http://diosmediante.com/img/imgx2_d.png";

/* ARRAY DE IMAGENES 3 */
ads3 = new Array(3);
ads3[0] = "http://diosmediante.com/img/imgx3.png";
ads3[1] = "http://diosmediante.com/img/imgx3_a.png";
ads3[2] = "http://diosmediante.com/img/imgx3_b.png";

/* ARRAY DE IMAGENES 4 */
ads4 = new Array(4);
ads4[0] = "http://diosmediante.com/img/imgx4.png";
ads4[1] = "http://diosmediante.com/img/imgx4_a.png";
ads4[2] = "http://diosmediante.com/img/imgx4_b.png";
ads4[2] = "http://diosmediante.com/img/imgx4_c.png";

/* ARRAY DE IMAGENES 5 */
ads5 = new Array(2);
ads5[0] = "http://diosmediante.com/img/imgx5.png";
ads5[1] = "http://diosmediante.com/img/imgx5_a.png";

/* ARRAY DE IMAGENES 6 */
ads6 = new Array(4);
ads6[0] = "http://diosmediante.com/img/imgx6.png";
ads6[1] = "http://diosmediante.com/img/imgx6_a.png";
ads6[2] = "http://diosmediante.com/img/imgx6_b.png";
ads6[3] = "http://diosmediante.com/img/imgx6_c.png";

/* ARRAY DE IMAGENES 7 */
ads7 = new Array(2);
ads7[0] = "http://diosmediante.com/img/imgx7.png";
ads7[1] = "http://diosmediante.com/img/imgx7_a.png";

//variable para llevar la cuenta de las imagenes
var longuitudArray = ads.length;
var longuitudArray = ads2.length;
var longuitudArray = ads3.length;
var longuitudArray = ads4.length;
var longuitudArray = ads5.length;
var longuitudArray = ads6.length;
var longuitudArray = ads7.length;
var contador = 0

// Un numero aleatorio
contador = Math.floor((Math.random() * longuitudArray))

// Cambia la imagen cada segundo en este ejemplo
var tiempo = 2// En segundos
var timer = tiempo * 1000;

// Funcion Img 1
function banner() {

 contador++;
 contador = contador % longuitudArray
 document.banner.src = ads[contador];
 setTimeout("banner()", timer);

}

// Funcion Img 2
function banner2() {
 contador++;
 contador = contador % longuitudArray
 document.banner2.src = ads2[contador];
 setTimeout("banner2()", timer);
}

// Funcion Img 3
function banner3() {
 contador++;
 contador = contador % longuitudArray
 document.banner3.src = ads3[contador];
 setTimeout("banner3()", timer);
}

// Funcion Img 4
function banner4() {
 contador++;
 contador = contador % longuitudArray
 document.banner4.src = ads4[contador];
 setTimeout("banner4()", timer);
}

// Funcion Img 5
function banner5() {
 contador++;
 contador = contador % longuitudArray
 document.banner5.src = ads5[contador];
 setTimeout("banner5()", timer);
}

// Funcion Img 6
function banner6() {
 contador++;
 contador = contador % longuitudArray
 document.banner6.src = ads6[contador];
 setTimeout("banner6()", timer);
}

// Funcion Img 7
function banner7() {
 contador++;
 contador = contador % longuitudArray
 document.banner7.src = ads7[contador];
 setTimeout("banner7()", timer);
}
html,
body {
    height: 100%;
}
body {
@import url('https://fonts.googleapis.com/css?family=Arimo:400');

background: url(http://diosmediante.com/img/bg.png) !important;
    background-position: center;

    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    z-index: -1;
    background-size: cover;
}

.fa {font-weight: bold; color: #d2a979;}

A:link {text-decoration:none}

a {color: color: #d2a979;}
a:hover {color: #fff;}

.contenido {
font-family: 'Arimo', sans-serif;
font-weight: 400;
font-size: 20px !important;
color: #d2a979;
text-align : justify;
margin-right: 10%;
margin-left: 10%;
}

#inicio {
    width: 80%;
    background-color: #fff;
    margin-top: -115;
    margin-right: auto;
    margin-bottom: auto;
    margin-left: auto;
    box-shadow: 0 0 4px rgba(0,0,0,.3);
}

.logo{
display:block;
    margin-top: 20px;
    margin-right: 20%;
    margin-bottom: auto;
    margin-left: auto;
}

h1 {
color: #d2a979;
margin:auto;
font-family: 'Arimo', sans-serif;
font-weight: 400;
font-size: 60px;
text-align: center;
}

h2 {
color: #d2a979;
margin:auto;
font-family: 'Arimo', sans-serif;
font-weight: 300;
font-size: 30px;
margin-right: 10%;
margin-left: 10%;
}

#secundario {
    width: 80%;
    background-color: #fff;
    margin: auto;
    box-shadow: 0 0 4px rgba(0,0,0,.3);
}

.tabla {width: 100%;   display:table;}

.tablita {
width: 50% !important;
display:table-cell;
font-family: 'Arimo', sans-serif;
font-size: 15px;
color: #d2a979;
text-align : justify;
}

.social {
float: right !important;
margin-right: 10%;
    margin-top: 83px;
}

 @media screen and (max-width: 900px)
{
.tablita {width: 100% !important; display: inline !important; margin-left: 15px;
    margin-right: 15px;}

.no-movil {display: none !important;}

#inicio, #secundario {width: 90% !important;}

.social {
margin: auto !important;
}

}

.myButton {
 background-color:#d2a879;
 -moz-border-radius:28px;
 -webkit-border-radius:28px;
 border-radius:28px;
 display:inline-block;
 cursor:pointer;
 color:#ffffff;
 font-family: 'Quicksand', sans-serif;
        font-weight: 400;
        font-size: 32px;
 padding:16px 31px;
 text-decoration:none;
 text-shadow:-1px 3px 5px #141412;
}
.myButton:hover {
 background-color:#8f6434;
}
.myButton:active {
 position:relative;
 top:1px;
}

<meta charset="utf-8">

<title>
Dios Mediante
</title>
<base href="http://diosmediante.com">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/faw/css/font-awesome.min.css">

DIOS MEDIANTE es el resultado de una pasión y del trabajo hecho con toda dedicación y alegría. Diseñamos moda infantil urbana bordada y tejida a mano. Cada prenda hemos decidido que sea PIEZA ÚNICA, que no haya dos iguales.

Todo lo hacemos con nuestro equipo de trabajo que integran quince mujeres de la Ciudad de México y de Chepilme, Oaxaca,  que nos sentirnos muy bien porque todo es HECHO EN MÉXICO y confiamos  de manera total en la calidad.

Hace casi 10 años que comenzamos esta aventura y hoy trabajamos agradecidas por acompañar a las niñas y niños en sus días repletos de vida y travesuras.

 COMPRA

Boutique Muhna

Pasaje Polanco

Mazaryk 360

Abierta todos los días

Lunes a sábado de 10:00 a 8:00 pm

Domingos de 10:00 a 7:00 pm

Tenderete

Jalapa 130 esquina Guanajuato

Colonia Roma Norte

Abierta todos los días

Lunes a viernes de 2:00 pm a 8:00 pm

Sábados de 12:00 a 8:00 pm

Domingos de 11:00 a 7:00 pm

Agregué la URL no para hacer spam, sino para que puedan ver las fotos.
Saludos y de antemano gracias.

A: El problema es que la variable longuitudArray la estás reemplazando todo el tiempo. El ultimo valor que toma es 2, por se el largo del último array.
Tendrías que probar con la siguiente modificación (asi por cada una de las funciones, aunque yo buscaría hacer una función generica):
//Modificamos esta linea:
//contador = Math.floor((Math.random() * longuitudArray))
contadorAds = Math.floor((Math.random() * ads.length))

function banner() {
    //modificamos la siguiente linea:
    //contador++;
    contadorAds++;
    //modificamos la siguiente linea:
    //contador = contador % longuitudArray;
    contadorAds = contadorAds % ads.length;
    document.banner.src = ads[contadorAds];
    setTimeout("banner()", timer);
}

Como te dije antes, buscaria de hacer una función recursiva que reciba el array, obtenga un numero random segun el length de ese array y muestre una imagen almacenada en ese array.
Espero te sea de utilidad. Cualquier cosa, me puedes consultar.
Exitos!


text:
Q: Transforming deep nested hash into multidimensional array in ruby I want to transform nested hashes into multidimensional arrays recursivley.
This is my current code:
def deep_to_a(hash)
  return  hash.to_a.each {|k, v|
    if k.is_a?(Hash) then
      hash[k.to_a] = hash.delete(k)
      deep_to_a(k)
    elsif v.is_a?(Hash) then
      hash[k] = hash[k].to_a
      if hash[k].any?{|k, v| k.is_a?(Hash) || v.is_a?(Hash)}
        deep_to_a(v)
      end
    end
  }
end

I want to get:
h = {11=>{12=>13, 14=>15}, 16=>17}
p deep_to_a(h) # => [[11, [[12, 13], [14, 15]]], [16, 17]]

But I get
[[11, {12=>13, 14=>15}], [16, 17]]

How can I make it work?

A: A destructive function is hard to debug.
In this case, map is better than each + destructive assignment.
The result of hash.to_a is an array, so your iteration |k, v| is incorrect.
def deep_to_a(hash)
  hash.map do |v|
    if v.is_a?(Hash) or v.is_a?(Array) then
      deep_to_a(v)
    else
      v
    end
  end
end

h = {11=>{12=>13, 14=>15}, 16=>17}
p deep_to_a(h)
# [[11, [[12, 13], [14, 15]]], [16, 17]]

A: def deep_to_a(h)
  h.map { |k,v| [k, Hash === v ? deep_to_a(v) : v] }
end

deep_to_a({11=>{12=>13, 14=>15}, 16=>17})
  #=> [[11, [[12, 13], [14, 15]]], [16, 17]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confusion in the proof of essential spectrum of toeplitz operator $T_\phi$ is connected for $\phi\in H^\infty+C(\Bbb{T})$ I am reading this theorem from Banach Algebra Techniques in Operator Theory by Douglas (Corollary 7.37). The proof goes as follows-

Here essential spectrum of $T_\phi$ is the set $\sigma_e(T_\phi)=\{\lambda\in \Bbb{C}:\ T_{\phi-\lambda}\text{ is not fredholm}\}$.
It is proved that $T_{\phi-\lambda}$ is fredholm if and only if $\phi-\lambda$ is invertible in $H^\infty+C(\Bbb{T})$. I also know that $\psi\in H^\infty+C(\Bbb{T})$ is invertible in $H^\infty+C(\Bbb{T})$ if and only if $\exists \epsilon>0,\ \delta\in(0,1)$ such that $|\hat{\psi}(re^{it})|\ge\epsilon$ for all $r\in(1-\delta,1),\ e^{it}\in\Bbb{T}$ here $\hat{\psi}$
denotes the harmonic extension of $\psi$ defined as $\hat{\psi}(re^{it})=\sum\limits_{n\in\Bbb{Z}} \hat{\psi}(n)r^{|n|}e^{int}$.
Using these two results $\lambda\in\sigma_e(T_\phi)\iff\forall\epsilon>0,\ \delta\in(0,1)$ there exists $r\in (1-\delta,1),\ e^{it}\in\Bbb{T}$ such that $|\hat{\phi}(e^{it})-\lambda|<\epsilon\iff\forall\delta\in(0,1),\ \lambda\in\overline{\{\hat{\phi}(re^{it}):\ r\in(1-\delta,1),\ e^{it}\in\Bbb{T}\}}\iff\lambda\in \bigcap\limits_{\delta\in(0,1)}\overline{\{\hat{\phi}(re^{it}):\ r\in(1-\delta,1),\ e^{it}\in\Bbb{T}\}}$
Now since $\hat{\phi}$ is continuous, image of the annulus $\{re^{it}:\ r\in(1-\delta,1),e^{it}\in \Bbb{T}\}$ will be connected and hence the closure. Therefore, each of the above set is connected. But how to show that the intersection is connected, in general intersection is not connected. The book says, "Since each of these sets is connected, the result follows". I cannot understand how it follows.
Can anyone help me in this regard? Thanks for your help in advance.

A: What you have is a monotone family of connected compact sets, so the intersection is connected.
Suppose that $\{E_\delta\}_{\delta\in(0,1)}$ is a family of compact connected sets and $E_\delta\subset E_{\delta'}$ if $\delta'>\delta$. Let $E=\bigcap_\delta E_\delta$. The set $E$ is nonempty, being a decreasing union of compact.
Suppose that  $E=F\cup G$, with $F,G$ closed and disjoint. Because $F,G$ are compact, there exist disjoint open sets $V,W$ with $F\subset V$ and $G\subset W$.
Claim: there exists $\delta$ such that $E_{\delta}\subset V\cup W$.
Assuming the claim, $E_\delta=(E_\delta\cap V)\cup(E_\delta\cap W)$. As $E_\delta$ is connected, either $E_\delta\subset V$ or $E_\delta\subset W$. The former case implies $E\subset V$, which in turn implies $E=F$. The other case similarly implies $E=G$. Thus $E$ is connected.
Proof of the Claim. Suppose that $E_\delta\subset V\cup W$ fails for all $\delta$. This would mean that $E_\delta\cap (V\cup W)^c\ne\varnothing$ for all $\delta$. As our family is monotone and $(V\cup W)^c$ is closed, this implies that the family $\{E_\delta\cap(V\cup W)^c\}$ is a family of compact sets with the finite intersection property. This then implies that
$$
\varnothing\ne \bigcap_\delta E_\delta\cap(V\cup W)^c=E\cap(V\cup W)^c.
$$
But this contradicts $E\subset V\cup W$. In conclusion there has to exists $\delta$ such that $E_\delta\cap(V\cup W)^c=\varnothing$; that is, $E_\delta\subset V\cup W$.


text:
Q: Is there a web site that allows you to draw an ascii chart with boxes and arrows easily? Ascii drawings and charts are a useful way of documenting software and can be included directly in source files near the code they document.
I'm looking for an online tool to draw them and be able to move boxes around.
Does something like this exist or should I use my text editor?

A: Well, you can use JavE. Not exactly online, though.

A: http://www.asciiflow.com/ allows you to draw boxes and arrows.


text:
Q: Node + Express: does not invoke callback after posting data to database I'm new to node.js, and is using Express and Sequelize to build a restful api. For now I just need to create a user by the following code:
router.post('/preregister', function(req, res, next) {
    models.users.create(req.body, function(err, user) {
        console.log('req: ' + req.body);
        if (err) res.json(err);
        res.json(user);
    });
});

The system output the sql statement, and I can see that the data is created by querying database, but then the server hangs there and does not do anything any more, not even printing out the 'req' line right before the if statement, which looks like the function(err, user) part is never touched. Looks like something fundamental is wrong. But what is missing??
EDIT
The users model is defined as below:
"use restrict";

module.exports = function(sequelize, Sequelize) {
    var users = sequelize.define('users', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
            isUnique: true,
            field: 'id'
        },
        email: {
            type: Sequelize.STRING,
            isUnique: true,
            allowNull: false,
            validate: {
                isEmail: true
            },
            field: 'email'
        }
    }, {
        freezeTableName: true
    });

    return users;
};

A: Sequelize is Using Promises in it's latest versions
router.post('/preregister', function(req, res, next) {
    var user = models.users.build(req.body);
        user.save()
        .complete(function(err) {
            if (err) return next(err);
            res.json(user);
        });
});

A: Sequelize uses (a modified version of) the bluebird promises library, which means that this should work:
router.post('/preregister', function(req, res) {
  models.users.create(req.body).then(function(user) {
    res.json(user);
  }).catch(function(err) {
    console.error(err);
    res.sendStatus(500);
  });
});

A: router.post('/preregister', function(req, res, next) {
    models.users.create(req.body, function(err, user) {
        if (err) res.json(err);
        res.json(user);
    });
});


text:
Q: Jmeter>>> i found a error every time when i execute ./jmeter command(./jmeter: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java/bin/java: not found) I follow this link : https://linuxhint.com/install_apache_jmeter_ubuntu/ for Jmeter installation but i found a error when i execute this line ./jmeter. >>
jmeter.sh: 99: [: Illegal number:
./jmeter: 128: [: Illegal number:
./jmeter: 199: ./jmeter: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java/bin/java: not found

A: Then why you're asking questions here and not under that link?
Your JAVA_HOME and/or PATH environment variables are not correct, it's hard to say what's exactly wrong without seeing them so you need to double check their values and ensure that java executable is on your PATH
There are 5 simple steps to get JMeter up and running on Debian-based Linux distributions (including Ubuntu)

*

*Update packages list:
sudo apt-get update -qq

*Install JRE 8 from OpenJDK project and wget
apt-get install -y -qq openjdk-8-jre-headless wget > /dev/null

*Download the latest stable version of JMeter:
wget -q https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-5.3.tgz

*Unpack it
tar -xf apache-jmeter-5.3.tgz

*Go to the "bin" folder of unpacked JMeter and check its version:
cd apache-jmeter-5.3/bin/ && ./jmeter --version

Demo:

More information: How to Get Started With JMeter: Installation & Test Plans


text:
Q: Photon flux and the power to 2 LEDS I am trying to write a program where the user uses a dial to adjust the intesity of one LED at the frequency of Red light and another LED in the same circuit that is at the frequency of Far Red light is auto adjusted to keep the the overall photon flux at 20 mircomoles per meters squared per second. How do I relate this to the power going to each LED

A: \$20~ µmoles/m^2/s = 1080 ~lux = 4.38~ W/m^2 \$  for emitted power, not applied power.
\$1~ lux = 1~ lumen /m^2\$
Efficacy=lumens/W  for applied power
thus 1080 lumens/m^2 / ? lumens/W x ? m^2 = Watts input power.
So you need to find l/W , and W for each LED then effective area ( then factor * efficiency for luminaire efficiency since you dont utilize 100% of emitted light on outside edges. )  it is usually 160 deg for half power for a lambertion source.
This is one example.
High flux output Far Red 740nm LED
 12.8 umol/s output at 5.7W power dissipation
 Ultra-small foot print – 7.0mm x 7.0mm
 Surface mount ceramic package with integrated glass lens
 Low Thermal Resistance (2.8°C/W)
$18 http://www.ledengin.com/files/products/LZ4/LZ4-00R308.pdf
A CPU like heatsink is needed.

A: I think you have to work through the datasheet of the LED's. I found several which had no data. Two others had this:

I assume you have a biology background and would not know where to start  looking. So I'll make an exception and tell you how I found those: the digikey website, under optoelectronics, Infrared, UV, Visible Emitters. Then I filtered for wavelength between 765 and 810nm.

Does the light have to be continuous? You might control the amount of light much easier by using pulses of variable width. To reduce the light by 20% you  reduce the duty cycle by 20%. To compensate you can increase the duty cycle of the other, which does not have to be 20%. e.g. you can change it by 28% or 18%. The ratio may be calibrated on forehand with the above by Brian  Drummond mentioned photo diode. It does not even have to be linear relation: if you use a micro controller you can add a lookup-table and interpolation SW.


text:
Q: Unable to group notifications in fcm I am using node.js for cloud computing the notifications but the problem is that all the notifications are shown separately but I want them to be shown together like Instagram or WhatsApp. For example, A sends 3 messages to B then these three should be grouped together rather then showing three times.
They are shown like this:-

But I want them to be like this i.e one notification for all:-

My Code:-

async function sendNotification(chatItem)
        {
            let body;

            switch (chatItem.type)
            {
                case 0:
                    body = `${chatItem.senderUsername}: ${chatItem.message}`;
                    break;

                case 1:
                    body = `${chatItem.senderUsername}: shared a photo`;
                    break;

                case 2:
                    body = `${chatItem.senderUsername}: sent you a sticker`;
                    break;

                case 3:
                    body = `${chatItem.senderUsername}: sent you a post`;
                    break;

                case 4:
                    body = `${chatItem.senderUsername}: sent you a profile`;
                    break;

                default:
                break;
            }
            const message =
            {
                notification: {
                                title:'Message',
                                body: body,
                                imageUrl: url,
                              },
                token: androidNotificationToken,
                data: { recipient: senderUserId },
            };

            admin.messaging().send(message)
            .then(response =>
            {
                console.log("Successfully sent message", response);
            })
            .catch(error =>
            {
                console.log("Error sending message", error);
            })

        }


text:
Q: Стираются пробелы в конце строки при написании макроса VBA Писал на vba макросы в модуле к файлу. В один прекрасный момент на новой строке любое слово подсвечивается красным (предыдущий код ок работает, любое добавление кода в него мучительно).
Стираются пробелы - как только ставишь пробел и хочешь начать писать 2-е слово, пробел стирается. Гугл нашел только подобную проблему, которая осталась без решения. Все ок только при включенном design mode. Может здесь кто-нибудь сталкивался с такой же проблемой ?

A: Оказывается, такой проблемой уже задавались на enSO. Было предоставлено несколько решений проблем:
В окне написания кода VBA нажать на Tools -> Options -> снять галку с "Auto Syntax Check"

Второе решение - убрать один из Add-in'ов, которые пришли вместе с Visual Studio 2010 Beta 2.

*

*Нажать на иконку Excel, перейти в "Параметры" (или Файл -> Параметры)

*перейти во вкладку "Надстройки"

*Выбрать надстройки COM и перейти туда

*Найти надстройку 'Load Test Report AddIn' и снять галку с него

*Перезапустить Excel
Данное решение лучше тем, что остаётся автопроверка написанного кода.

Мне помогло собственное решение. Где-то говорили, что такой баг происходит при добавлении на лист MS WebBrowser компоненты, что, собственно, и было у меня. Поэтому я в режиме Конструктора удалил WebBrowser компоненту и, выйдя из режима Конструктора, вернуть браузер с помощью Ctrl+Z.


text:
Q: how to create different users using reactjs and firebase I am trying to create a web application with ReactJs and firebase. I want to know how to create three users with different roles like doctor, patient, pharmacist.
My Signup.js file
    if (pass.value != cpass.value) {
  alert("Password dont match")
}
else {
  try {
    var e = email.value
    const ref = db.collection("doctor")
    setLoading(true)
    await app
      .auth()
      .createUserWithEmailAndPassword(email.value, pass.value);
    ref.doc(e).set({
      "name": uname.value,
      "dob": dob.value,
      "email": email.value,
      "phno": phno.value,
      "regno": regno.value,
      "regyear": regyear.value,
      "gender": gender.value,
      "addr": addr.value,
      "pincode": pin.value,
      "city": city.value,
      "state": state.value,
      "bloodtype": bloodtype.value,
      "speciality": speciality.value,

    }).then(() => {
      console.log("Document successfully written!");
    });
    db.collection("users").doc(email.value).set({
      "email":email.value,
      "userType":"doctor"
    })

A: You have set the collection to doctors in the following code snippet:
const ref = db.collection("doctor")
If you want to add a different user to a different firebase collection you just need to replace the collection name:
const ref = db.collection("patient")


text:
Q: Domestic Parcel Postage Calculation API (Australian Post) I have a shopping website in Australia.I want to use Australian post shipping method in my website (asp.net with C# 4.0). I have no any SSL certificate for my website.Below code was running well before 3 month but now this code give an error.My website is hosted on Windows shared server.
This URL is the complete documentation of api.
https://auspost.com.au/devcentre/assets/pdfs/pac-pcs-technical-specification.pdf
I am following above URL(5.3 Domestic Parcel Postage Calculation API) but I don't know What is the real problem in my code.
I don't know much about JSON so I am using XML Pattern. If you can do this via json i have no problem .I want to required only output.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

 Australia Post Shipping Charges Calculator

                    <asp:Label ID="lblMessage" runat="server" EnableViewState="False"
                        Font-Bold="True"></asp:Label>

                    From postcode:

                   <asp:TextBox ID="txtFromPostCode" runat="server"  MaxLength="4"></asp:TextBox>Ex:3216

                    To postcode:

                     <asp:TextBox ID="txtToPostCode" runat="server"  MaxLength="4"></asp:TextBox>Ex:3217

                    Weight

                     <asp:TextBox ID="txtWeight" runat="server"  MaxLength="4"></asp:TextBox>Ex:5

                    Service Type

                    <asp:DropDownList ID="ddlServiceType" runat="server">
                        <asp:ListItem Value="0">--select service type--</asp:ListItem>
                        <asp:ListItem Value="AUS_PARCEL_REGULAR">Regular Parcel</asp:ListItem>
                        <asp:ListItem Value="AUS_PARCEL_EXPRESS">Express Post Parcel</asp:ListItem>
                        <asp:ListItem Value="AUS_PARCEL_PLATINUM">Express Post Platinum Parcel</asp:ListItem>
                    </asp:DropDownList>

                    <asp:Button ID="btnShippingCalculate" runat="server" Text="Shipping Calculate"
                        onclick="btnShippingCalculate_Click" ValidationGroup="vs" />

                    <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>

   <%#Eval("service")%>

             <%#Eval("delivery_time")%>

            Price :$<%#Eval("total_cost")%>

                    </ItemTemplate>
                    </asp:Repeater>

    </form>

Code Behind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO;
using System.Net;

public partial class parcelapiDemo : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected string calculateCost(string lngth, string wdth, string hgth, string fpcode, string tpcode, string weght, string service_code)
    {

        string url = "https://test.npe.auspost.com.au/api/postage/parcel/domestic/calculate.xml?";
        url = url + "length=" + HttpUtility.UrlEncode(lngth) + "&width=" + HttpUtility.UrlEncode(wdth) + "&height=" + HttpUtility.UrlEncode(hgth) + "&from_postcode=" + HttpUtility.UrlEncode(fpcode) + "&to_postcode=" + HttpUtility.UrlEncode(tpcode) + "&option_code=&weight=" + HttpUtility.UrlEncode(weght) + "&service_code=" + HttpUtility.UrlEncode(service_code) + "&extra_cover=";
        Uri objURI = new Uri(url);
        HttpWebRequest objwebreq = (HttpWebRequest)WebRequest.Create(objURI);
        objwebreq.ContentType = "text/xml;charset=utf-8;";
        objwebreq.Method = "Get";
        objwebreq.Timeout = 15000;

        objwebreq.Headers.Set("AUTH-KEY", "28744ed5982391881611cca6cf5c2409");//For Localhost

        HttpWebResponse objWebResponse = (HttpWebResponse)objwebreq.GetResponse();
        Stream objStream = objWebResponse.GetResponseStream();
        StreamReader objStreamReader = new StreamReader(objStream);
        return objStreamReader.ReadToEnd();

    }
    protected void btnShippingCalculate_Click(object sender, EventArgs e)
    {

            string xmlresult = calculateCost("10", "10", "10",txtFromPostCode.Text, txtToPostCode.Text,txtWeight.Text, ddlServiceType.SelectedValue);
            DataSet ds = new DataSet();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xmlresult);
            ds.ReadXml(new System.IO.StringReader(doc.OuterXml));
            Repeater1.DataSource = ds;
            Repeater1.DataBind();

    }
}


text:
Q: How to show $f(x)=\exp((|x|^2-1)^{-1})$ if $|x|<1$ and $f(x)=0$ if $|x|\geq 1$ is a test function? What would be the formal argument for showing the function $f:\mathbb R^n\longrightarrow \mathbb R$, $$f(x):=\left\{\begin{array}{ccc}
\exp\left(\displaystyle\frac{1}{|x|^2-1}\right)&\textrm{se}&|x|<1\\
0&\textrm{se}&|x|\geq 1
\end{array}\right.$$
is a test function?
Recall a function $f:\mathbb R^n\longrightarrow \mathbb R$ is a test function if $f\in C^\infty(\mathbb R^n)$ and $\textrm{supp}(f)$ is a compact set.
I have already done the continuity:
Proof of Continuity. It suffices verifying $f$ is continuous on $S^{n-1}$. We must show $\displaystyle\lim_{x\to y} f(x)=0$, $y\in S^{n-1}$. If $x\in\mathbb R^n\setminus S^{n-1}$ this is clear. Suppose $|x|<1$ and let $\varepsilon>0$ arbitrary. Taking $\delta=\ln(\varepsilon)/2$ then $|x-y|<\delta$implies:
$\displaystyle \frac{1}{|x|^2-1}\leq |x|^2-1=(|x|+1)(|x|-1)<2(|x|-1)\leq 2||x|-|y||\leq 2|x-y|<\ln(\varepsilon).$
Using $x\mapsto \exp(x)$ is increasing and positive we find: $$\left|\exp\left(\frac{1}{|x|^2-1}\right)\right|<\varepsilon,$$ what finishes the proof.
We have to show $f\in C^\infty(\mathbb R^n)$. We do this by induction showing $f\in C^{k-1}(\mathbb R^n)$ for every $k\in\mathbb N$. What I did above shows this holds for $k=1$. What about the general case?
Guideline: We suppose $f\in C^{k-1}(\mathbb R^n)$ for some $k\in\mathbb N$, that is, $\partial^\alpha f\in C^0(\mathbb R^n)$ for all $\alpha\in\mathbb N_0^n$ such that $|\alpha|\leq k-1$. Take $\alpha\in\mathbb N_0^n$ such that $|\alpha|=k$. Then we may write $\alpha=\beta+\delta_{j}$. So $\partial^\alpha f(x)=\partial_j\partial^\beta f(x)$. How to proceed?
Notation: $\mathbb N_0=\mathbb N\cup \{0\}$, $\delta_j=(0, \ldots, 1, \ldots, 0)$ where $1$ is in $j$-th position.


text:
Q: Will I earn bonuses by accomplishing a mission remaining unseen? If I go quiet, and I kill everyone without giving them the chance to see me, will I get a bonus of something, or it's the same thing?

A: Aside from the new rescue missions, there is no bonus for remaining undetected during a mission. In the new rescue missions, you are awarded a point for each of the following objectives:

Killing all of the 'Wardens' protecting the hostage
Rescuing the hostage before the Wardens can set off the Execution command (Similar to an alarm, triggering a 60 second countdown before the hostage is killed and the mission fails)
Escaping with the hostage

Depending on the specific mission you played, you will be awarded a Specter Blueprint depending on your total points earned during the mission. Aside from this specific case, no, Stealth does not award any bonus to a mission.


text:
Q: How can I use \patchcmd with commands with optional arguments?
This question led to a new package:
xpatch

This is likely a simple question, but I'm getting stuck on the small details.  I have an internal command, defined by a package as
\newcommand\foo@[3][]{...stuff...}

and somewhere in there I'd like to patch the command to include a call to \label{#1}.  I'm already using etoolbox, so I planned to use
\patchcmd{\foo@}{hook}{\label{#1}hook}{success}{failure}

Unfortunately this doesn't work, because \foo@ is defined as
> \foo@=macro:
->\@protected@testopt \foo@ \\foo@ {}.
l.359 \show\foo@

Which has no parameters and therefore the patching code fails.  So I tried to figure out how to get \\foo@  (note the doubled slash and the trailing space) as a csname, and I got snarled up.
So then I tried using the old-style approach of \let\my@foo@=\foo@\renewcommand\foo@[3][]{...\my@foo@[#1]{#2}{#3} -- I know the original idiom is to use \let and \def, but since \foo@ was defined with \newcommand I tried using \renewcommand.  But this doesn't work, and fails with a TeX capacity exceeded error, and the log file appears to show an endless cycle of macro expansion.
So.  What is the correct name for the internal macro defined by \newcommand when optional arguments are present, and how do I build the csname for that so I can patch it with \patchcmd?

A: To patch a command (with or without an optional argument) defined by means of \newcommand or \DeclareRobustCommand I use a wrapper \xpatchcmd around \patchcmd. \xpatchcmd has an additional optional argument in front of the first argument of \patchcmd that indicates the nature of the command to be patched:

*

*n --> \newcommand

*o --> \newcommand + optional argument

*N --> \DeclareRobustCommand

*O --> \DeclareRobustCommand + optional argument

Definition and application of \xpatchcmd:
\documentclass{article}

\usepackage{etoolbox}

\usepackage{xifthen}

\makeatletter

\newcommand*{\xpatchcmd}[1][]{%
  \bgroup%
  \let\@gobble@\@gobble\let\@space@\empty%
  \ifthenelse{\isempty{#1}\OR\equal{\unexpanded{#1}}{n}}{}{%
    \ifthenelse{\equal{\unexpanded{#1}}{o}}{\let\@gobble@\empty}{%
      \ifthenelse{\equal{\unexpanded{#1}}{N}}{\let\@space@\space}{%
        \ifthenelse{\equal{\unexpanded{#1}}{O}}{\let\@gobble@\empty\let\@space@\space}{%
          \typeout{%
            Command \protect\xpatchcmd\space Warning: Invalid command specifier "\unexpanded{#1}".%
          }%
        }%
      }%
    }%
  }%
  \catcode`\#=12%
  \@xpatchcmd%
}

\newcommand{\@xpatchcmd}[6][\undefined]{%
  \catcode`\#=6%
  \edef\undefined{\noexpand\undefined}%
  \def\@prefix{#1}%
  \letcs{\@command}{\expandafter\@gobble@\string#2\@space@}%
  \ifx\@prefix\undefined%
    \patchcmd{\@command}{#3}{#4}{#5}{#6}%
  \else%
    \patchcmd[\@prefix]{\@command}{#3}{#4}{#5}{#6}%
  \fi%
  \global\cslet{\expandafter\@gobble@\string#2\@space@}{\@command}%
  \egroup%
}

\makeatother

\begin{document}

\newcommand*{\test}[2]{#1me#2}
\show\test
\xpatchcmd[n][\protected]{\test}{me}{you}{}{}
\show\test

\renewcommand{\test}[2][]{#1me#2}
\expandafter\show\csname\string\test\endcsname
\xpatchcmd[o][]{\test}{me#2}{you#1}{}{}
\expandafter\show\csname\string\test\endcsname

\DeclareRobustCommand*{\test}[2]{#1me#2}
\expandafter\show\csname test \endcsname
\xpatchcmd[N][\long]{\test}{#1me}{#2you}{}{}
\expandafter\show\csname test \endcsname

\DeclareRobustCommand*{\test}[2][only]{#1me#2}
\expandafter\show\csname\string\test\space\endcsname
\xpatchcmd[O]{\test}{#2}{}{}{}
\expandafter\show\csname\string\test\space\endcsname

\end{document}

A: You can get \\foo@ using \csname\string\foo@\endcsname. The space shown behind it with \show is not part of the macro name (but could be added using a \space before \endcsname).
So you can use:
\expandafter\patchcmd\csname\string\foo@\endcsname{hook}{\label{#1}hook}{success}{failure}

Full example:
\documentclass{article}

\usepackage{etoolbox}

\begin{document}

\makeatletter
\newcommand\foo@[3][]{stuff (#1) more stuff :#2: hook even more stuff = *#3*}

\expandafter\patchcmd\csname\string\foo@\endcsname{hook}{\label{#1}hook}{success}{failure}

\texttt{\string\foo@ = \meaning\foo@}

\texttt{\expandafter\string\csname\string\foo@\endcsname = \expandafter\meaning\csname\string\foo@\endcsname}

\makeatother

\section{Test}
\makeatletter
\foo@[test]{One}{Two}
\makeatother

\section{Test2}
See section \ref{test}!

\end{document}

A: NOTE: There are some minor weaknesses in the code shown below, so it's best to use the corresponding package.

The following macros define the commands \xpatchcmd, \xpretocmd and \xapptocmd that recognize robust commands (defined by \DeclareRobustCommand or \newrobustcmd) and also if they have an optional argument.
\usepackage{etoolbox,xparse}

\ExplSyntaxOn
\makeatletter
% generate a variant of \tl_if_in:NnT
\cs_generate_variant:Nn \tl_if_in:NnT { Nx }
% a boolean for testing robust commands
\bool_new:N \l_xpatch_protect_bool
% a "bizarre" token list that's quite improbable to find in a replacement text
\tl_set:Nx \c_xpatch_bizarre_tl { \tl_to_str:n { **)-(**/**[-]** } }
% the main command; it takes as first argument one of \patchcmd, \pretocmd or
% \apptocmd; the second argument is the command we want to patch
\cs_new:Npn \xpatchcmd_main:NN #1 #2
  {
% first of all we gather the command-to-patch name
   \tl_set:Nx \l_xpatch_name_tl { \exp_after:wN \use_none:n \token_to_str:N #2  }
% now we get the replacement text of the command-to-patch, but adding the bizarre
% token list in front of it which consists of all category 12 characters
   \tl_set:Nx \l_xpatch_tmpa_tl { \c_xpatch_bizarre_tl \token_get_replacement_spec:N #2 }
% now we look whether the token list contains the bizarre list followed by \protect
% which happens if it's a control sequence defined by \DeclareRobustCommand, so
% we add a space to the command name
   \tl_if_in:NxT \l_xpatch_tmpa_tl { \c_xpatch_bizarre_tl \token_to_str:N \protect}
     {
      \bool_set_true:N \l_xpatch_protect_bool
      \xpatch_add_space:
     }
% now we look whether the token list contains the bizarre list followed by \x@protect
% which happens if it's a control symbol defined by \DeclareRobustCommand, so
% we add a space to the command name
   \tl_if_in:NxT \l_xpatch_tmpa_tl { \c_xpatch_bizarre_tl \token_to_str:N \x@protect}
     {
      \bool_set_true:N \l_xpatch_protect_bool
      \xpatch_add_space:
     }
% now we look whether the token list contains the bizarre list followed by \@protected@testopt
% which happens if it's a command with an optional argument (from \newcommand)
   \tl_if_in:NxT \l_xpatch_tmpa_tl { \c_xpatch_bizarre_tl \token_to_str:N \@protected@testopt}
     { \xpatch_add_backslash: }
% now we look whether the token list contains the bizarre list followed by \@testopt
% which happens if it's a command with an optional argument (from \newrobustcmd)
   \tl_if_in:NxT \l_xpatch_tmpa_tl { \c_xpatch_bizarre_tl \token_to_str:N \@testopt}
     { \xpatch_add_backslash: }
% if the command-to-patch was defined by \DeclareRobustCommand we look whether the
% command name with backslash in front and space at the end exists and we assume that
% it has an optional argument
   \bool_if:NT \l_xpatch_protect_bool
     {
      \cs_if_exist:cT { \c_backslash_tl \l_xpatch_name_tl }
        { \xpatch_add_backslash: }
     }
% now we pass the real command-to-patch name to the patching macro
   \exp_after:wN #1 \cs:w \l_xpatch_name_tl \cs_end:
  }
% how we add a space after the name
\cs_new:Npn \xpatch_add_space:
  { \tl_set:Nx \l_xpatch_name_tl { \l_xpatch_name_tl \c_space_tl } }
% how we add a backslash in front of the name
\cs_new:Npn \xpatch_add_backslash:
  { \tl_set:Nx \l_xpatch_name_tl { \c_backslash_tl \l_xpatch_name_tl } }
% a constant containing a backslash (category 12)
\tl_set:Nx \c_backslash_tl { \exp_after:wN \use_none:n \token_to_str:N \\ }
% the user level commands
\NewDocumentCommand{\xpatchcmd}{}{ \xpatchcmd_main:NN \patchcmd }
\NewDocumentCommand{\xpretocmd}{}{ \xpatchcmd_main:NN \pretocmd }
\NewDocumentCommand{\xapptocmd}{}{ \xpatchcmd_main:NN \apptocmd }
\NewDocumentCommand{\xshowcmd}{}{ \xpatchcmd_main:NN \show }

\NewDocumentCommand{\xpatchbibmacro} { m }
  { \exp_after:wN \xpatchcmd_main:NN \exp_after:wN \patchcmd \cs:w abx@macro@ \tl_to_str:n {#1} \cs_end: }
\NewDocumentCommand{\xpretobibmacro} { m }
  { \exp_after:wN \xpatchcmd_main:NN \exp_after:wN \pretocmd \cs:w abx@macro@ \tl_to_str:n {#1} \cs_end: }
\NewDocumentCommand{\xapptobibmacro} { m }
  { \exp_after:wN \xpatchcmd_main:NN \exp_after:wN \apptocmd \cs:w abx@macro@ \tl_to_str:n {#1} \cs_end: }
\NewDocumentCommand{\xshowbibmacro} { m }
  { \exp_after:wN \xpatchcmd_main:NN \exp_after:wN \show \cs:w abx@macro@ \tl_to_str:n {#1} \cs_end: }

\makeatother
\ExplSyntaxOff

Of course commands defined in a devious way can break these macros, but this is true of almost any set of macros.
Patching commands defined by \NewDocumentCommand or the others provided by xparse is not supported.
Usage
\newcommand\foo[3][]{...hook...}
\xpatchcmd{\foo}{hook}{\label{#1}hook}{success}{failure}

\xshowcmd\foo

The last one shows the "real" meaning of \foo. The commands
\xpatchbibmacro \xpretobibmacro \xapptobibmacro

can be used to patch commands defined via \newbibmacro of biblatex; with \xshowbibmacro one can see the "real" meaning of the macro.


text:
Q: Kendo grid pager issue after loading new data I have a problem with the Kendo grid pager misbehaving after loading new data into a grid. The grid is loaded when the page loads, configured as follows:
@(Html.Kendo().Grid<MyModel>()
            .Name("Grid")
            .Columns(columns =>
            {
                //snipped
            })
            .Scrollable()
            .Sortable(sort => sort.Enabled(true))
            .Pageable(pager => pager.PageSizes(new int[] {10, 25, 50, 100}))
            .Events(events => events.DetailExpand("detailExpand").DetailCollapse("detailCollapse").DataBinding("onDataBinding"))
            .ClientDetailTemplateId("template")
            .DataSource(dataSource => dataSource
                .Ajax()
                .ServerOperation(false)
                .Sort(sort => sort.Add(Model.sort).Order(Model.Direction))
                .PageSize(Model.PageSize)
                .Events(events=>events.Error("onError"))
                .Read(read => read.Action("Summary", "Summary").Data("getFilterModel")))
                .Events(events => events.DataBound("dataBound"))
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
              );

I have some controls on the page that serve as filters for the grid content. the getFilterModel function returns the values of those filters. When the user clicks the "Filter" button, I call read on the grid data source.
<button class="k-button" id="get" type="button" onclick="$('#Grid').data('kendoGrid').dataSource.read();return false;">Filter</button>

This works OK on initial page load, and if I reload the grid with a number of rows <= the original number of rows. If I reload with a larger number of rows, the pager shows the correct count. But, if I try to click to advance to the next page, the pager reverts to showing 1 page only, and the grid shows empty.
Example: initial load contains 3 records, page size 25. Pager shows 1 page. OK. Change filters so the grid loads 42 rows. Pager shows 2 pages, set to page 1, and "1-25 of 42 items". Click to advance to page 2; grid shows no rows, pager shows 1 page and "26-25 of 25 items"
Does the pager need to be explicitly reset somehow?
This is an older version of Kendo MVC...DLL shows version 2013.3.1119.340.

A: In this case, Kendo MVC and I outsmarted ourselves.
The getFilterModel function returned an object that contained both Page and PageSize properties, which get translated into query param names in the HTTP request. Those in turn become properties on the FilterModel object that is the model for the controller action. On the server side, the controller action calls the Kendo ToDataSourceResult extension method which apparently interpreted Page and PageSize and only returned the first page of the results.
Changing the names of those properties to GridPage and GridPageSize solved the problem. I had included them because I wanted to persist them as part of the grid state, but I may be better off finding another way to do that.


text:
Q: Convert unix time to local iso time format to set in htmk date time picker So, I have a unix time as
endingTime= 1669060881
and then I do this to convert it into ISO format
this.edate = new Date(endingTime*1000).toISOString() ===>  2022-11-21T20:01:21.000Z
slicing it so that it can fir html local date input
this.edate = this.edate.slice(0, -8) ===>  2022-11-21T20:01
and then patch this value in my date time picker of form
this.userForm['endingTime']['controls'].patchValue(this.edate);
html

---> shows result as 21-11-22 and 8:01 as the time
when I put the time 1669060881 in here https://www.epochconverter.com/
you can see two times
GMT: Monday, November 21, 2022 8:01:21 PM
Your time zone: Tuesday, November 22, 2022 1:31:21 AM GMT+05:30
I need the iso conversiton in "Your time zone" time but currentt edate val is the GMT timezone
pls help

A: You can use toLocaleString instead of toISOString
Date.toLocaleString

const ms = 1669060881 * 1000
const dateTime = new Date(ms).toLocaleString()
console.log(dateTime)

A: Don't re-invent the wheel and use some popular and well tested library when working with dates. Like zonedTimeToUtc from date-fns-tz.
 const dateTime = zonedTimeToUtc(ms, 'Your timezone')


text:
Q: BreezeJS - Is there any way to use old style 'One controller to rule them all' with OData Web API? I would like to expose the SQL Server Views via OData Web API but I don't want to create separate controllers for each views as there are too many of them and they will only accept GET verb for all the views.
I thought I can achieve this using BreezeController but it looks like I cannot as it is obsolete now (The package which has BreezeController attribute is marked as obsolete).
Is there any way to achieve this with OData Web API that works with BreezeJS?

A: The [BreezeController] attribute is not obsolete. In fact, it is central to the "happy path" Web API controllers you see in the Breeze samples. I wonder what lead you to think otherwise? What package are you using?
I'm referring to the ASP.NET Web API!
The ASP.NET Web API OData is a different matter. Despite "Web API" in the name, that is almost a completely different approach to server development with its own behaviors and wire format. It does not use the [BreezeController] attribute and never has.
I'm not sure what you meant by "view" in your phrase, "separate controllers for each view". I think you mean what I would call "type". For example, in OData you'd expect a "Product" endpoint for your Product entity type.
AFAIK, the Web API OData approach demands a separate controller per type. That's what Microsoft's Mike Wasson says in his tutorial. He writes ...

A controller is a class that handles HTTP requests. You create a separate controller for each entity set in your OData service.

BreezeJS supports Web API OData too ... although there are limitations imposed by the current Microsoft implementation that may give you pause.

We are working through these with the OData team and hope to have better news in the coming months.


text:
Q: casting const pointers between different types I have a C++ function where one of the input parameters is of type char const* buffer. The way I understand it is that the underlying values of this array can be changed but the pointer itself cannot be moved to point to something else.
Now what I want to do is reinterpret this array as unsigned short and do some manipulations. So, I do something like:
char const * current = &buffer[currentLine]; // Points to some location
unsigned short * const values = static_cast<unsigned short * const>(current);
// Change some of these values

This results in invalid cast from top char * const to type short unsigned int * const.
How should this casting be performed?

A:
The way I understand it is that the underlying values of this array
  can be changed but the pointer itself cannot be moved to point to
  something else.

Nope. It means that you cannot change the entity this pointer points too, but you are able to change a pointer itself. To forbid changing the pointer you have to make the pointer itself const:
const char* const buffer;
            ^^^^^

How should this casting be performed?

The casting should be performed with reinterpret_cast.

Only the following conversions can be done with reinterpret_cast, except when such conversions would cast away constness or volatility.
...
5) Any pointer to object of type T1 can be converted to pointer to object of another type cv T2.

So you have to write:
unsigned short * const values = reinterpret_cast<unsigned short * const>(current);

or even:
decltype(auto) values = reinterpret_cast<unsigned short * const>(current);

Finally, static_cast is not applicable here because you try to perform a cast between different unrelated pointer types.

A: To help you with type safety, each cast has a limited set of conversions that it will allow. This allows you to help communicate what you intend to do with the cast which lets the compiler warn you if you would accidentally preform a conversion that wasn't intended.
static_cast is a relatively safe casting operator. It allows the most common and safest conversions, including those that are already implicitly allowed. This does not include converting between unrelated pointers types, which is often dangerous. The correct cast operator to use is reinterpret_cast. The reinterpret_cast is used when you want to interpret some memory as a given type, regardless of how type of object that memory actually represents. Among other things, it's used when you convert between unrelated pointer types.
Remember that, when given the choice, it's always preferred to use the most restrictive cast operator that will preform the work you need done. This will give the compiler the most opportunities to notify you if you make a mistake.
Note that you are converting between pointer types. It's important not to confuse converting between two types and converting between two pointers to those types. The way to convert between char and unsigned short is not the same way you convert between pointer to char and pointer to unsigned short.


text:
Q: Why can't I GROUP BY 1 when it's OK to ORDER BY 1? Why are column ordinals legal for ORDER BY but not for GROUP BY? That is, can anyone tell me why this query
SELECT OrgUnitID, COUNT(*) FROM Employee AS e GROUP BY OrgUnitID

cannot be written as
SELECT OrgUnitID, COUNT(*) FROM Employee AS e GROUP BY 1

When it's perfectly legal to write a query like
SELECT OrgUnitID FROM Employee AS e ORDER BY 1

?
I'm really wondering if there's something subtle about the relational calculus, or something, that would prevent the grouping from working right.
The thing is, my example is pretty trivial. It's common that the column that I want to group by is actually a calculation, and having to repeat the exact same calculation in the GROUP BY is (a) annoying and (b) makes errors during maintenance much more likely. Here's a simple example:
SELECT DATEPART(YEAR,LastSeenOn), COUNT(*)
    FROM Employee AS e
    GROUP BY DATEPART(YEAR,LastSeenOn)

I would think that SQL's rule of normalize to only represent data once in the database ought to extend to code as well. I'd want to only right that calculation expression once (in the SELECT column list), and be able to refer to it by ordinal in the GROUP BY.
Clarification: I'm specifically working on SQL Server 2008, but I wonder about an overall answer nonetheless.

A: One of the reasons is because ORDER BY is the last thing that runs in a SQL Query, here is the order of operations

*

*FROM clause

*WHERE clause

*GROUP BY clause

*HAVING clause

*SELECT clause

*ORDER BY clause

so once you have the columns from the SELECT clause you can use ordinal positioning
EDIT, added this based on the comment
Take this for example
create table test (a int, b int)
insert test values(1,2)
go

The query below will parse without a problem, it won't run
select a as b, b as a
     from test
    order by 6

here is the error
Msg 108, Level 16, State 1, Line 3
The ORDER BY position number 6 is out of range of the number of items in the select list.
This also parses fine
select a as b, b as a
     from test
    group by 1

But it blows up with this error
Msg 164, Level 15, State 1, Line 3
Each GROUP BY expression must contain at least one column that is not an outer reference.

A: There is a lot of elementary inconsistencies in SQL, and use of scalars is one of them. For example, anyone might expect

    select * from countries
    order by 1

and

    select * from countries
    order by 1.00001

to be a similar queries (the difference between the two can be made infinitesimally small, after all), which are not.

A: use aliasses :
SELECT DATEPART(YEAR,LastSeenOn) as 'seen_year', COUNT(*) as 'count'
    FROM Employee AS e
    GROUP BY 'seen_year'

** EDIT **
if GROUP BY alias is not allowed for you, here's a solution / workaround:
SELECT seen_year
     , COUNT(*) AS Total
  FROM (
    SELECT DATEPART(YEAR,LastSeenOn) as seen_year, *
    FROM Employee AS e
  ) AS inline_view
GROUP
    BY seen_year

A: I'm not sure if the standard specifies if it is valid, but I believe it is implementation-dependent.  I just tried your first example with one SQL engine, and it worked fine.

A: databases that don't support this basically are choosing not to. understand the order of the processing of the various steps, but it is very easy (as many databases have shown) to parse the sql, understand it, and apply the translation for you. Where its really a pain is when a column is a long case statement. having to repeat that in the group by clause is super annoying. yes, you can do the nested query work around as someone demonstrated above, but at this point it is just lack of care about your users to not support group by column numbers.


text:
Q: WKInterfaceTable detect which row selected I just need to check which row was selected to pass data between WKInterfaceController. Here is my code, but NSLog doesn't show anything:
- (void)loadTableData {

     NSArray* items = [NSArray arrayWithObjects:@"cell 1 ",@"cell2 ", @"cell 3",@"cell4",nil];

    // Configure the table object (self.todoItems) and get the row controllers.
    [self.myTable setNumberOfRows:items.count withRowType:@"DinoNameRow"];
    NSInteger rowCount = self.myTable.numberOfRows;

    // Iterate over the rows and set the label for each one.
    for (NSInteger i = 0; i < rowCount; i++) {
        // Get the to-do item data.
        NSString* itemText = items[i];

        // Assign the text to the row's label.
        DinoNameRow* row = [self.myTable rowControllerAtIndex:i];
        [row.dinoName setText:itemText];
    }
}
- (void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex {

    switch (rowIndex) {
        case 0:
            NSLog(@"ROW 1");
            break;

        default:
            break;
    }
}

A: Make sure that...

*

*Your WKInterfaceTable is connected via IBOutlet to your Storyboard element.

*Your rowType identifier for the row controller is set in Storyboard:

*Your Class identifier for the row controller is set in Storyboard:

*You have overridden the correct WKInterfaceController method:
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {

}

A: The code as below that I use in my project works well.
  override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
        let string = data[rowIndex]
        self.delegate?.didSeletStyle(style, string: string, index: rowIndex)
        popController()
    }

  private func reloadTable() {
        for i in 0 ..< table.numberOfRows {
            let row = table.rowControllerAtIndex(i) as! tableRow
            row.label.setText(data[i])
        }
    }

private func getData(style: Style) {
    if style == .Friend {
        data = ["a","b","c","d"]
    }

    table.setNumberOfRows(data.count, withRowType: "tableRow")
    reloadTable()
}


text:
Q: A viewmodel without a view, can it be justified? In an MVVM application, is it be frowned upon to have a viewmodel without a view?
My justification for having such a viewmodel is that the underlying model fires some events caught by the viewmodel which then in turn notifies other viewmodels of this event using an event aggregator.

A: In MVVM, ViewModels must be independant of Views. So, YES, a Viewmodel can be without a View.


text:
Q: Gradle build doesn't work due to drawables files - Android Studio I'm trying to build a little Android app on Android Studio.
There is no error showed in my code.
When I try to deploy the app, Gradle crashes and Android Studio (version 1.5) opens me a .png file.
Here is my Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.saphirel.toto">

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Styles.xml
<resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"></style>
</resources>

And here comes the build error :
/home/UserName/AndroidStudioProjects/Toto/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_switch_to_on_mtrl_00012.9.png

Error:Error: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/home/UserName/android-sdk-linux/build-tools/19.1.0/aapt'' finished with non-zero exit value 127

:app:mergeDebugResources FAILED

Error:Execution failed for task ':app:mergeDebugResources'.

/UserName/AndroidStudioProjects/Toto/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_switch_to_on_mtrl_00012.9.png:

Error: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/home/saphirel/android-sdk-linux/build-tools/19.1.0/aapt'' finished with non-zero exit value 127

A: This happens when the build tools version is not aligned with the support library. Make sure you are using the same version of build tools as the support libraries you've added under your dependencies.


text:
Q: Permissions problem when selecting image from gallery on Android I'm starting with Xamarin to be able to create an app that runs both on iOS and Android.
The first thing I wanted to do is to click a button -> Open Gallery -> Select image -> Display selected image on a Image label
The current content of MainPage.xaml is:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:HelloWorld" x:Class="HelloWorld.MainPage">
    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        <Label Text="0" x:Name="lbl_counter" HorizontalOptions="Center" VerticalOptions="StartAndExpand" FontSize="Large"/>
        <Image x:Name="img_selected" Source="" />
        <Button Text="Click Me" Clicked="Handle_Clicked" VerticalOptions="StartAndExpand"/>
    </StackLayout>
</ContentPage>

I'm using Plugin.Media so, when the button gets clicked I run this code:
async void Handle_Clicked(object sender, System.EventArgs e){
    lbl_counter.Text = (++counter).ToString();

    await CrossMedia.Current.Initialize();
    if (!CrossMedia.Current.IsPickPhotoSupported){
        await DisplayAlert("no upload", "picking a photo is not supported", "ok");
        return;
    }

    var file = await CrossMedia.Current.PickPhotoAsync();
    if (file == null)
        return;

    img_selected.Source = ImageSource.FromStream(file.GetStream);
}

After a bit (a lot) of effort I managed to get it working on iOS.
But I can't get it working on Android. It keeps complaining about permissions.
I already followed all I could think of from:

*

*https://forums.xamarin.com/discussion/89455/how-to-loading-images-from-gallery

*https://github.com/jamesmontemagno/MediaPlugin

*https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
Any idea?

Adding information from the comments
Comment 1:
I don't get a (visible) stack trace in Xamarin.
I get this if I copy from the error window:
Plugin.Media.Abstractions.MediaPermissionException: Storage permission(s) are required.

In the Output Window I can see:
Does not have storage permission granted, requesting.
Storage permission Denied.

CODE
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Plugin.Media;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;

namespace HelloWorld
{
    public partial class MainPage : ContentPage
    {
        private int counter;
        public MainPage()
        {
            InitializeComponent();
        }

        async void Handle_Clicked(object sender, System.EventArgs e)
        {
            lbl_counter.Text = (++counter).ToString();

            /******************************/
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
                    {
                        await DisplayAlert("Need Storage", "Gunna need that Storage", "OK");
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
                    status = results[Permission.Storage];
                }

                if (status == PermissionStatus.Granted)
                {
                    await CrossMedia.Current.Initialize();
                    if (!CrossMedia.Current.IsPickPhotoSupported)
                    {
                        await DisplayAlert("no upload", "picking a photo is not supported", "ok");
                        return;
                    }

                    var file = await CrossMedia.Current.PickPhotoAsync();
                    if (file == null)
                        return;

                    img_selected.Source = ImageSource.FromStream(file.GetStream);
                }
                    else if (status != PermissionStatus.Unknown)
                {
                    await DisplayAlert("Storage Permission Denied", "Can not continue, try again.", "OK");
                }
            }
            catch
            {
                //...
            }
            /******************************/

        }
    }
}

MainPage.xaml
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:HelloWorld" x:Class="HelloWorld.MainPage">
    <StackLayout>
        <!-- Place new controls here -->
        <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        <Label Text="0" x:Name="lbl_counter" HorizontalOptions="Center" VerticalOptions="StartAndExpand" FontSize="Large"/>
        <Image x:Name="img_selected" Source="" />
        <Button Text="Click Me" Clicked="Handle_Clicked" VerticalOptions="StartAndExpand"/>
    </StackLayout>
</ContentPage>

MainActivity.cs
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace HelloWorld.Droid
{
    [Activity(Label = "HelloWorld", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.gedons.HelloWorld">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
    <uses-permission android:name="android.permission.CAMERA" />
    <application android:label="HelloWorld.Android">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

_file_path.xml_
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_images" path="Pictures" />
    <external-files-path name="my_movies" path="Movies" />
</paths>

A:
Permissions problem when selecting image from gallery on Android

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. You should requesting permissions at runtime.
System permissions are divided into two categories, normal and dangerous:

*

*Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.

*Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app.

READ_EXTERNAL_STORAGE is divided in to Dangerous permissions, so  you should checking this permissions manually for API level 23 and above.

For Xamarin.Forms project, you could use the PermissionsPlugin to request this permission in Xamarin.Forms at runtime.

*

*Here is the official sample of PermissionsPlugin.

*setup of this PermissionsPlugin
Simple usage here, add this code in your MainActivity:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

Request permission when you need it:
try
{
    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
    if (status != PermissionStatus.Granted)
    {
        if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
        {
            await DisplayAlert("Need Storage", "Gunna need that Storage", "OK");
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
        status = results[Permission.Storage];
     }

     if (status == PermissionStatus.Granted)
     {
         //Permission granted, do what you want do.
     }
     else if(status != PermissionStatus.Unknown)
     {
         await DisplayAlert("Storage Permission Denied", "Can not continue, try again.", "OK");
     }
}
catch (Exception ex)
{
    //...
}

A: Starting from Android M you have to grand other apps such as (gallery) a storage permission, i.e the gallery needs to save the picked image into the provided URI path.
follow the steps here:
https://thinkandroid.wordpress.com/2012/08/07/granting-content-provider-uri-permissions/


text:
Q: Bigcommerce getTransaction call not returning expected result I am using a Bigcommerce sandbox account, which is not live yet. Test orders are allowed from backend. Two orders can be seen from admin: order_id 100 and 101. But when I am using Postman to get either one, response is:
{
  "status": 500,
  "code": 10000,
  "title": "Transactions not found for order_id 101. [Internal Code 204]",
  "type": "https://developer.bigcommerce.com/api#api-status-codes"
}

My Get call is:
https://api.bigcommerce.com/stores/<mystorehash>/v3/orders/101/transactions

I am using Postman with headers:
X-Auth-Client:<my API client id>
X-Auth-Token: <my Auth token>

I have got these values when I created the API....also there in header:
Accept: application/json
Content-type:application/json

What am I missing?


text:
Q: Coefficient Variable Membership in R I have worked up a horribly lengthy solution to this before using regular expressions but I hope  there is a more native way to do it.
Given a model, perhaps like
data(tips, package="reshape2")
mod <- lm(tip ~ total_bill*sex + sex*day, tips)
mod$coefficients

I want to identify which coefficients go with which variable in the formula.  Like this:
|    Coefficient     |    Variable    |
|:-------------------|:---------------|
| total_bill         | total_bill     |
| sexMale            | sex            |
| daySat             | day            |
| daySun             | day            |
| dayThur            | day            |
| total_bill:sexMale | total_bill,sex |
| sexMale:daySat     | sex,day        |
| sexMale:daySun     | sex,day        |
| sexMale:dayThur    | sex,day        |

I have inspected model.matrix and model.formula but those led me to this line of code
.Internal(model.matrix(t, data))

I dove into the C code but I figured there had to be an easier way.  Is there?
In response to DWin's nice answer I have built a convoluted example where the the regex could fail.  This is one of those edge cases where regex scares me.
The data.frame is built with variable names and values that can easily be confused which happens a lot.
baseball <- data.frame(Bat=sample(1:100, 20, replace=T), Batter=sample(c("David", "Batley", "Bob", "Ace"), 20, replace=T), Hits=sample(1:20, 20, replace=T))
baseball
bMod <- lm(Hits ~ Bat*Batter, baseball)
bMod$coefficients

col.matx <- sapply(colnames(model.matrix(bMod)), function(cols) sapply(labels(bMod), function(trm) grep(patt=trm, x=cols, value=TRUE)))

This matches the continuous variable Bat to all the coefficients for the factor Batter.
Yes, this is a stupid example, but can easily happen.

A: This is not the exact answer but should be able to see a way of rearranging it to suit your purposes. The first step identifies which of the labels are in each of the model.matrix column names.
col.matx <- sapply(colnames(model.matrix(mod)), function(cols)
         sapply(labels(mod), function(trm) grep(patt=trm, x=cols, value=TRUE)))
#---------------------------------------
               (Intercept) total_bill   sexMale     daySat      daySun      dayThur
total_bill     Character,0 "total_bill" Character,0 Character,0 Character,0 Character,0
sex            Character,0 Character,0  "sexMale"   Character,0 Character,0 Character,0
day            Character,0 Character,0  Character,0 "daySat"    "daySun"    "dayThur"
total_bill:sex Character,0 Character,0  Character,0 Character,0 Character,0 Character,0
sex:day        Character,0 Character,0  Character,0 Character,0 Character,0 Character,0
               total_bill:sexMale   sexMale:daySat   sexMale:daySun   sexMale:dayThur
total_bill     "total_bill:sexMale" Character,0      Character,0      Character,0
sex            "total_bill:sexMale" "sexMale:daySat" "sexMale:daySun" "sexMale:dayThur"
day            Character,0          "sexMale:daySat" "sexMale:daySun" "sexMale:dayThur"
total_bill:sex "total_bill:sexMale" Character,0      Character,0      Character,0
sex:day        Character,0          Character,0      Character,0      Character,0

The rownames of the result would need to be collapsed associated with the matrix values when the value is not a zero length item:
> which(sapply(col.matx, length) != 0 , arr.ind=TRUE)
 [1]  6 12 18 23 28 31 32 34 37 38 42 43 47 48

So this picks out the items names from the above matrix and associates them with the term.labels
 using modulo arithmetic:
data.frame(coef =  unlist(col.matx[
                      which(sapply(col.matx, length) != 0 , arr.ind=TRUE)] ),
           term.label =rownames(col.matx)[
                       which(sapply(col.matx, length) != 0 , arr.ind=TRUE) %% 5 ])
                 coef     term.label
1          total_bill     total_bill
2             sexMale            sex
3              daySat            day
4              daySun            day
5             dayThur            day
6  total_bill:sexMale     total_bill
7  total_bill:sexMale            sex
8  total_bill:sexMale total_bill:sex
9      sexMale:daySat            sex
10     sexMale:daySat            day
11     sexMale:daySun            sex
12     sexMale:daySun            day
13    sexMale:dayThur            sex
14    sexMale:dayThur            day

Collapsing values methods are a frequent request onSO. There was one that was answered in the last 24 hours.

A: Ok, found a solution for lm models using information entirely included in the model.
require(plyr)       # for join function
require(reshape2)   # for melt function

matchCoefs <- function(model)
{
    # get the terms
    theTerms <- model$terms
    # get the assignment position
    thePos <- model$assign
    # get intercept indicator
    inter <- attr(theTerms, "intercept")
    # get coef names
    coefNames <- names(coef(model))
    # get pred names
    predNames <- attr(theTerms, "term.labels")
    # expand out pred names to match coefficient names
    predNames <- predNames[thePos]
    # if there's an intercept term add it to the pred names
    if(inter == 1)
    {
        predNames <- c("(Intercept)", predNames)
    }

    # build data.frame linking term to coefficient name
    matching <- data.frame(Term=predNames, Coefficient=coefNames)

    ## now match individual predictor to term
    # get matrix as data.frame
    factorMat <- as.data.frame(attr(theTerms, "factor"))
    # add column from rownames as identifier
    factorMat$.Pred <- rownames(factorMat)
    # melt it down for comparison
    factorMelt <- melt(factorMat, id.vars=".Pred", variable.name="Term", )
    # only keep rows where there's a match
    factorMelt <- factorMelt[factorMelt$value == 1, ]
    # again, bring in coefficient if needed
    if(inter == 1)
    {
        factorMelt <- rbind(data.frame(.Pred="(Intercept)", Term="(Intercept)", value=1), factorMelt)
    }
    # join into the matching data.frame
    matching <- join(matching, factorMelt, by="Term")

    return(matching)
}

# fit some models with different terms
mod1 <- lm(tip ~ total_bill * sex + day, tips)
mod2 <- lm(tip ~ total_bill * sex + day - 1, tips)
mod3 <- lm(tip ~ (total_bill + sex + day)^3, tips)
mod4 <- lm(tip ~ total_bill * sex + day + I(total_bill^2), tips)

matchCoefs(mod1)
matchCoefs(mod2)
matchCoefs(mod3)
matchCoefs(mod4)

# now with the convoluted baseball example
baseball <- data.frame(Bat=sample(1:100, 20, replace=T), Batter=sample(c("David", "Batley", "Bob", "Ace"), 20, replace=T), Hits=sample(1:20, 20, replace=T))
bMod <- lm(Hits ~ Bat*Batter, baseball)
matchCoefs(bMod)

No loops, all built in functions, no regex.  I will need to test this some more and throw in the data type information, but that should be comparatively simple.


text:
Q: How to set python3 as default I recently installed python3.9.6 on ubuntu
and it all seemed to work
but when enter python3 on the terminal it shows python3.8.5, not python3.9.6
I want to type in python, python3, or python3.9 to open python3.9.6
can someone help me?

A: Check python version on terminal - python --version
Get root user privileges. On terminal type - sudo su
Write down the root user password.
Execute this command to switch to python 3.6.
update-alternatives --install  /usr/bin/python python /usr/bin/python3 1
Check python version - python --version

A: You could try adding a permanent alias:

*

*Open your .bashrc file: vim ~/.bashrc

*Add this to the end of the file:
alias sudo="sudo "  (credit to https://askubuntu.com/a/22043)
alias python="INSERT-PATH-TO-PYTHON-EXE-HERE"
alias python3="INSERT-PATH-TO-PYTHON-EXE-HERE"
alias python3.9="INSERT-PATH-TO-PYTHON-EXE-HERE"

*If you have any of the following: .bash_aliases, .bash_login, .profile. Add to it instead

*Reload .bashrc: source ~/.bashrc


text:
Q: Maximal ideal of ring of matrices
Let $R=M_n(\mathbb F_q )$ be the ring of $n\times n$ matrices over the finite field $\mathbb F_q$. I want to show that every matrix of rank $n-1$ in any maximal left ideal of $R$ generates that maximal left ideal.

I know that $R$ is semi-simple ring. I deduce that every ideal of $R$ was generated by idempotent element, but I don't know how do I use this fact.
Any suggestion?

A: Finally, I found the solution of my question in Jacobson's book (page 232 of Lectures in Abstract Algebra). However Jacobson used old literature and I restate with modern literature.

Let $D$ be a division ring and n be a natural number. If $H_r$, $0 \leq r \leq n$, denotes the left ideal of $M_n(D)$ containing all matrices whose $d_{ij} = 0$, for every $r \leq j \leq n$, then every left ideal of $M_n(D)$ is similar to $H_r$, for some $r$, $0 \leq r
\leq n$ (there exists an invertible matrix $P$, so that every matrix in the left ideal of $M_n(D)$ is of the form $PKP^{−1}$, where $K\in H_r$).


text:
Q: boost::lockfree::spsc_queue - segmentation fault after some seconds
*

*Using boost::lockfree::spsc_queue with uint_16 data

*Quick explanation of program: From within a thread uint_16 data is continuously delivered by an acquisition object and pushed to the spsc_queue (producer). Meanwhile in the parent process "one second" length data is popped from the spsc_queue when avaliable (consumer).

*Getting segmentation faults, but have not been able to find the root cause so far.

*Have been using boost::lockfree::spsc_queue with data type int in several project so far without any issues.

Complete source:
#include <Acquisition.h>
#include <atomic>
#include <thread>
#include <boost/lockfree/spsc_queue.hpp>

size_t sample_rate_Hz = 250e3;

void data_acqui(boost::lockfree::spsc_queue<uint16_t>& bf, std::atomic<bool>& stop)
{
    try
    {
        uint16_t *data;
        uint32_t data_size = 0;

        // acquisition channels 1-4
        std::vector<Channel> channels;
        channels.emplace_back(Channel::ANALOG, Channel::ATT_15dB, false);
        channels.emplace_back(Channel::ANALOG, Channel::ATT_15dB, false);
        channels.emplace_back(Channel::ANALOG, Channel::ATT_15dB, false);
        channels.emplace_back(Channel::ANALOG, Channel::ATT_15dB, false);

        Acquisition Acq(channels, sample_rate_Hz, 0);

        while(!stop.load())
        {
            data = Acq.get(&data_size);

            if(data_size && data != NULL)
            {
                // data_size is number of bytes delivered by Acquisition::get class method
                // adapt size to data type used by spsc_queue
                data_size /= sizeof(*data);

                std::cout << "THREAD: bf.push(data, data_size) => data:" << data << " data_size:" << data_size << std::endl;

                bf.push(data, data_size);
            }
        }
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
}

int main()
{
    try
    {
        std::cout << "MAIN: sample_rate_Hz: " << std::dec << sample_rate_Hz << std::endl;
        // 4 channels data acquisition
        size_t oneSecChunkSize = 4 * sample_rate_Hz;
        std::cout << "MAIN: oneSecChunkSize: " << std::dec << oneSecChunkSize << std::endl;

        // 5 sec buffer
        boost::lockfree::spsc_queue<uint16_t> sec_buffer(5 * oneSecChunkSize);

        std::atomic<bool> stop(false);
        std::thread th(data_acqui,std::ref(sec_buffer), std::ref(stop));

        // helper used to empty spsc_queue when data of a single second length is available
        std::vector<uint16_t> oneSecChunk(oneSecChunkSize ,0);

        // let's record 10 seconds
        size_t num_sec = 10;

        for(size_t i = 0; i < num_sec; ++i)
        {
            while(sec_buffer.read_available() <= oneSecChunkSize)
            {
                std::cout <<  "MAIN: waiting..." << std::dec << sec_buffer.read_available() << " <= " << oneSecChunkSize << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }

            std::cout << "MAIN: number of seconds recorded:  " << (i+1) << "/" << num_sec << " sec" << std::endl;
            sec_buffer.pop(oneSecChunk.data(), oneSecChunkSize);
        }

        std::cout << "stop thread..." << std::endl;
        stop = true;
        std::cout << "join thread..." << std::endl;
        th.join();

    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }

    return 0;
}

GDB:
user@linux:~ gdb -ex run ./main
Reading symbols from ./main...done.
Starting program: /root/main
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
MAIN: sample_rate_Hz: 250000
MAIN: oneSecChunkSize: 1000000
[New Thread 0xb638d450 (LWP 29640)]
MAIN: waiting...0 <= 1000000
MAIN: waiting...0 <= 1000000
MAIN: waiting...0 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb5400000 data_size:172032
MAIN: waiting...172032 <= 1000000
MAIN: waiting...172032 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb54a8000 data_size:172032
MAIN: waiting...344064 <= 1000000
MAIN: waiting...344064 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb5550000 data_size:172032
MAIN: waiting...516096 <= 1000000
MAIN: waiting...516096 <= 1000000
MAIN: waiting...516096 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb55f8000 data_size:172032
MAIN: waiting...688128 <= 1000000
MAIN: waiting...688128 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb56a0000 data_size:172032
MAIN: waiting...860160 <= 1000000
MAIN: waiting...860160 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb5748000 data_size:172032
MAIN: number of seconds recorded:  1/10 sec
MAIN: waiting...32192 <= 1000000
MAIN: waiting...32192 <= 1000000
THREAD: bf.push(data, data_size) => data:0xb57f0000 data_size:172032
MAIN: waiting...32192 <= 1000000

Thread 2 "main" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb638d450 (LWP 29640)]
0xb6dec564 in __memcpy_neon () at ../sysdeps/arm/armv7/multiarch/memcpy_impl.S:591
591 ../sysdeps/arm/armv7/multiarch/memcpy_impl.S: No such file or directory.
(gdb) bt
#0  0xb6dec564 in __memcpy_neon () at ../sysdeps/arm/armv7/multiarch/memcpy_impl.S:591
#1  0x0002e162 in std::__copy_move<false, true, std::random_access_iterator_tag>::__copy_m<unsigned short> (__first=0xb57f0000, __last=0xb5844000,
    __result=0xb6586008) at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_algobase.h:378
#2  0x0002e28e in std::__copy_move_a<false, unsigned short const*, unsigned short*> (__first=0xb57f0000, __last=0xb5844000, __result=0xb6586008)
    at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_algobase.h:396
#3  0x0002e12e in std::__copy_move_a2<false, unsigned short const*, unsigned short*> (__first=0xb57f0000, __last=0xb5844000, __result=0xb6586008)
    at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_algobase.h:434
#4  0x0002df36 in std::copy<unsigned short const*, unsigned short*> (__first=0xb57f0000, __last=0xb5844000, __result=0xb6586008)
    at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_algobase.h:466
#5  0x0002dd66 in std::__uninitialized_copy<true>::__uninit_copy<unsigned short const*, unsigned short*> (__first=0xb57f0000, __last=0xb5844000,
    __result=0xb6586008) at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_uninitialized.h:93
#6  0x0002dbb2 in std::uninitialized_copy<unsigned short const*, unsigned short*> (__first=0xb57f0000, __last=0xb5844000, __result=0xb6586008)
    at /usr/arm-linux-gnueabihf/include/c++/4.9.3/bits/stl_uninitialized.h:126
#7  0x0002d914 in boost::lockfree::detail::ringbuffer_base<unsigned short>::push<unsigned short const*> (this=0xbefffa80, begin=0xb57f0000,
    end=0xb5844000, internal_buffer=0xb638e008, max_size=5000001)
    at /home/user/repo/platform/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:149
#8  0x0002d24c in boost::lockfree::detail::ringbuffer_base<unsigned short>::push (this=0xbefffa80, input_buffer=0xb57f0000, input_count=172032,
    internal_buffer=0xb638e008, max_size=5000001) at /home/user/repo/platform/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:118
#9  0x0002c9ba in boost::lockfree::detail::runtime_sized_ringbuffer<unsigned short, std::allocator<unsigned short> >::push (this=0xbefffa80,
    t=0xb57f0000, size=172032) at /home/user/repo/platform/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:592
#10 0x0002c0ac in boost::lockfree::spsc_queue<unsigned short, boost::parameter::void_, boost::parameter::void_>::push (this=0xbefffa80, t=0xb57f0000,
    size=172032) at /home/user/repo/platform/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:803
#11 0x0002b7d6 in data_acqui (bf=..., stop=...) at main.cpp:37
#12 0x0002e9b4 in std::_Bind_simple<void (*(std::reference_wrapper<boost::lockfree::spsc_queue<unsigned short, boost::parameter::void_, boost::parameter::void_> >, std::reference_wrapper<std::atomic<bool> >))(boost::lockfree::spsc_queue<unsigned short, boost::parameter::void_, boost::parameter::void_>&, std::atomic<bool>&)>::_M_invoke<0u, 1u>(std::_Index_tuple<0u, 1u>) (this=0x5d330) at /usr/arm-linux-gnueabihf/include/c++/4.9.3/functional:1700

GDB - stackframe 7:
(gdb) frame 7
#7  0x0040ab98 in boost::lockfree::detail::ringbuffer_base<unsigned short>::push<unsigned short const*> (this=0xbefffa78, begin=0xb57f0000,
    end=0xb5844000, internal_buffer=0xb638e008, max_size=5000001)
    at /home/marx/repos/alpha-buildenv/platform-ia/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:149
149             std::uninitialized_copy(begin, last, internal_buffer + write_index);
(gdb)
#7  0x0040ab98 in boost::lockfree::detail::ringbuffer_base<unsigned short>::push<unsigned short const*> (this=0xbefffa78, begin=0xb57f0000,
    end=0xb5844000, internal_buffer=0xb638e008, max_size=5000001)
    at /home/marx/repos/alpha-buildenv/platform-ia/sysroot/usr/include/boost/lockfree/spsc_queue.hpp:149
149             std::uninitialized_copy(begin, last, internal_buffer + write_index);
(gdb) info locals
write_index = 1032192
read_index = 1000000
avail = 4967808
input_count = 172032
new_write_index = 1204224
last = 0xb5844000


text:
Q: I cant relocate or reverse string python So my question is, how to manipulate date positions to get the desired output...
date = "12-01-2011"
#       MM-DD-YYYY
# I want to output: YYYY-MM-DD

A: Since the string is a fixed format, you can use string slicing and a f-string.
date = "12-01-2011"
date_year = date[6:]
date_month = date[0:2]
date_day = date[3:5]

#Then print with f string

print(f"{date_year}-{date_month}-{date_day}")

A: Using datetime function
from datetime import datetime
date = "12-01-2011"
datetimeobject = datetime.strptime(date,'%d-%m-%Y')
newformat = datetime.strftime(datetimeobject,'%Y-%m-%d')
print(newformat)

A: Here's a simple way to do it.
date = "12-01-2011"

date_list = date.split('-')
date_list[0], date_list[1], date_list[2] = date_list[2], date_list[0], date_list[1]

date = "-".join(date_list)

print(date)


text:
Q: how do i send my location via url in sms? i am making a android project so can anyone tell me how do i send my current location in URL via SMS .
Let me explain what i want to know when the mobile got a shake then my app sent a string SMS to selected contact now i want to add location feature in my app mean i want to send the location via URL in SMS ,when the receiver hit on URL then he can the location of sender in his map ?
  private void sendSMS(String ph, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(ph, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS SENT",
                Toast.LENGTH_LONG).show();
    }

A: I suggest you to get the current latitude and longitude of the device. The in step two you can create a String which is a searching url with those parameters which looks like this
   String message = "http://maps.google.com/?q=" + {latitude} + "," + {longitude}

And for the further info to get the current longitude and latitude have a look here

A: normal way then you can insert a url as bellow:
String pos_url = "http://sharegps.com?lat=00000000000&long=00000000000"; // you can replace your real gps position and your domain (or use maps.google.com)

First way:
SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(ph, null, pos_url, null, null);
        Toast.makeText(getApplicationContext(), "SMS SENT",
                Toast.LENGTH_LONG).show();

Second way:
private void shareTextUrl() {
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("text/plain");
    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide
    // what to do with it.
    share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");

    share.putExtra(Intent.EXTRA_TEXT, pos_url);

    startActivity(Intent.createChooser(share, "Share location!"));

}


text:
Q: Is it possible to change language for weather widgets from weather.com? I want change language for weather widgets that provide by weather.com site provides
The generated code for the widgets is:
 <script type=\"text/javascript\">

   /* Locations can be edited manually by updating 'wx_locID' below.  Please also update */
   /* the location name and link in the above div (wx_module) to reflect any changes made. */
   var wx_locID = 'SAXX0017';

   /* If you are editing locations manually and are adding multiple modules to one page, each */
   /* module must have a unique div id.  Please append a unique # to the div above, as well */
   /* as the one referenced just below.  If you use the builder to create individual modules  */
   /* you will not need to edit these parameters. */
   var wx_targetDiv = 'wx_module_9421';

   /* Please do not change the configuration value [wx_config] manually - your module */
   /* will no longer function if you do.  If at any time you wish to modify this */
   /* configuration please use the graphical configuration tool found at */
   /* https://registration.weather.com/ursa/wow/step2 */
   var wx_config='SZ=300x250*WX=FHW*LNK=SSNL*UNT=C*BGI=sun*MAP=me|null*DN=www.top2top.net*TIER=0*PID=1309975798*MD5=34d989859d8c0614f3af42405cb4d631';

   document.write('<scr'+'ipt src=\"'+document.location.protocol+'//wow.weather.com/weather/wow/module/'+wx_locID+'?config='+wx_config+'&proto='+document.location.protocol+'&target='+wx_targetDiv+'\"></scr'+'ipt>');
</script>

is this possible ?


text:
Q: keep variable or target entire class Assuming I have a jQuery click handler for a certain class, where multiple buttons/bodies/section have that class. I want to know which button was clicked last, unclick any previously clicked button, and make it obvious to the client as well.
What is a better approach, keep track of a variable for the last clicked button so I can change it to 'unclicked' when another one is clicked, or just target the entire class?
demo
part of why I ask is because if I target the entire class, and remove a style or class from all those objects, it requires less code, however, I'm modifying many elements. But if I keep a variable, I'm only modifying 2 elements, the one that was already clicked, and the one that just got clicked on.
however, keeping a variable means having to add conditional logic that isn't required if I just say "remove class 'clicked' from all 'buttons'". So as far as performance, is there one way that's better or are they relatively equivalent?

A: Global or locally scoped variables, holding state, are best avoided if you can.
For this type of scenario I would target the classes (fast selector). Exclude the current item from the clearing of classes and toggle the target. This allows for on/off too.
$(function() {
    $('.button').on('click', function() {
        $('.button').not(this).removeClass('clicked');
        $(this).toggleClass('clicked');
    });
});

JSFiddle: http://jsfiddle.net/ou1wy5vt/2/
You will not care about any speed differences, unless you click 50,000 times a second, but if you want a fast selector, without caching it, this is a tad fast as it will have less results:
$('.clicked').not(this).removeClass('clicked');

or, cache the jQuery selector:
$(function() {
    var $buttons = $('.button').on('click', function() {
        $buttons.not(this).removeClass('clicked');
        $(this).toggleClass('clicked');
    });
});

Again though, you want the simplest, easiest to read/maintain option, rather than trying to be too clever/fast and losing maintainability.

A: If you target the entire class, all elements in that class will be iterated, and jQuery will attempt to remove the class for each one, even if they don't have it.
Therefore, keeping track of the previous clicked button is faster, because you only remove the class of the desired element.
It would be even faster if you stored the jQuery element wrapper:
var $clicked = $();
$('.button').on('click', function() {
    $clicked.removeClass('clicked');
    $clicked = $(this).addClass('clicked');
});