text:
Q: Unexpected value in JSON reposnse after receiving in CoffeeScript I use simple http client in my coffee script. It should send request to server which responds with JSON, I do it and try to parse response, but get strange result:
http = require 'http'

http.get { host: 'myurl' }, (res) ->
    data = ''
    res.on 'data', (chunk) ->
        data += chunk
        log 'Body: ' + chunk
    log 'Data: ' + data

Actual result from server looks like this:
config{
    username: login,
    password: password
}

But I get such output:
Body: config{username:login,password: password}
Data: config{username:login,password: password}:unexpected

When I try to parse data in JSON and use it, I get an error, and I suppose it is cause I get token ':enexpected'. Why it appears here?
P.S. Write code by memory, cause original source not available now, so here could be so syntax errors, but don`t take them into account in original code everything works.

A: Not quite sure if that is a related issue, but you are trying to print the data immediately, without waiting for the request to complete. What you should do is to wait for the end event:
http.get { host: 'myurl' }, (res) ->
  data = ''
  res.on 'data', (chunk) ->
    data += chunk
    log 'Body: ' + chunk
  # request might - and might not - be finished yet
  # log 'Data: ' + data
  res.on 'end', ->
    # request is certainly done
    log 'Complete: ' + data

If you got the data complete the way you posted it, it was either accidental, or you were already using this handler.


text:
Q: How to get equivalent Google Text-to-Speech pitch in Android I "created" a custom Google TTS voice by setting a pitch and speech rate here.
The value I chose for pitch is negative (-6.4) and I want to use the exact values in my Android app.
However, TextToSpeech.setPitch(float) cannot accept negative values. Here is the code from android.speech.tts.TextToSeech:
public int setPitch(float pitch) {
  if (pitch > 0.0f) {
    int intPitch = (int)(pitch * 100);
    if (intPitch > 0) {
      synchronized (mStartLock) {
        mParams.putInt(Engine.KEY_PARAM_PITCH, intPitch);
      }
      return SUCCESS;
    }
  }
  return ERROR;
}

I need some help determining the equivalent positive value that would be equivalent to -6.4. It appears I cannot simply extrapolate the value using the relative scales [-20, 20] (default: 0) on the web interface and apparently [25, 400] (default: 100) from the Android library. The latter obtained from com.android.settings.tts.TextToSpeechSettings, available here:
    /**
     * Speech pitch value. TTS pitch value varies from 25 to 400, where 100 is the value for normal
     * pitch. The max pitch value is set to 400, based on feedback from users and the GoogleTTS
     * pitch variation range. The range for pitch is not set in stone and should be readjusted based
     * on user need. This value should be kept in sync with the max value set in tts_settings xml.
     */
    private static final int MAX_SPEECH_PITCH = 400;
    private static final int MIN_SPEECH_PITCH = 25;

Thank you for your time.

A: I'm not sure how the default 0 (web interface) can equate to 100 (android library), but maybe this formula would work.
You can try using this formula:
A_MIN_SPEECH_PITCH = -20;
A_MAX_SPEECH_PITCH = 20;
B_MIN_SPEECH_PITCH = 25;
B_MAX_SPEECH_PITCH = 400;
a_speech_pitch = // Desired pitch
b_speech_pitch = (B_MAX_SPEECH_PITCH - B_MIN_SPEECH_PITCH) * ((a_speech_pitch - A_MIN_SPEECH_PITCH) / (A_MAX_SPEECH_PITCH - A_MIN_SPEECH_PITCH)) + B_MIN_SPEECH_PITCH;
Test Case #1
a_speech_pitch = -20
b_speech_pitch = (400-25) * ((-20-(-20))/(20-(-20))) + 25 = 25
Test Case #2
a_speech_pitch = 0
b_speech_pitch = (400-25) * ((0-(-20))/(20-(-20))) + 25 = 212.5
Test Case #3
a_speech_pitch = 20
b_speech_pitch = (400-25) * ((20-(-20))/(20-(-20))) + 25 = 400
Test Case #4
a_speech_pitch = -6.4
b_speech_pitch = (400-25) * ((-6.4-(-20))/(20-(-20))) + 25 = 152.5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looking for algorithm to help determine shortest path from one terminal screen to another I am using a terminal client to interact with a mainframe computer.  The entire interface is based on the concept of screens.  An example workflow might look like:

*

*Login Screen: enter login credentials, press enter

*Menu Screen: enter the number of the menu item you want (lets say "6" for memos), press enter

*Memo Screen: enter account number, press enter

*Add Memo Screen: enter memo details, etc, press enter to save, F3 to go back

I have written a python application to automate the processing of records through this terminal interface.  One of the difficulties I am having is that there are a lot of different screens and my application right now is pretty dumb about how to get from one screen to another.  It can go from the login screen, to adding memos.  But, if it finds itself on the memo screen and needs to de-activate an account, it has to logout and login again because it only knows how to get to the deactivation screen from the login screen, not from the add memos screen.
So, I would like to create a "map" in my application that links each screen to the screens that are "next" to it.  Then, I need an algorithm that could tell how to get from any screen A to any screen B in the shortest manner possible.
I already have some screen objects setup and have "related" them to the screens next to them.  So, I am looking for some kind of algorithm that I can implement or python library that I can use that will do the work of calculating the route from one screen to another.
Edit: I realize that I am looking for some kind of shortest-path graph algorithm.  What is currently throwing me is that I don't really have a "distance", I just have nodes.  So, I really don't want shortest-distance, I want least-nodes.

A: If you have created a topology of the screens, the A* algorithm should work fine.

A: Since I am using an unweighted graph, it looks like the simplest approach is going to be Breadth-first search:
http://en.wikipedia.org/wiki/Breadth-first_search
Edit: I found a library which does everything I need:
http://networkx.lanl.gov/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html


text:
Q: Is there a way to use multiple tables in Looker dashboard model? Can a dashboard be created using multiple not-joined snowflake tables in Looker model?
There is a requirement to get data from different tables in one dashboard

A: A dashboard can be made up by connecting to different/non joined models.  When creating each visual (chart / graph / data table) on the dashboard, you will choose the model to use.  A single visual has a one to one relationship with a model, but a dashboard can be driven by multiple models
If filtering occurs at a dashboard level, you'll need to be mindful if / how the filters potentially interact between models.


text:
Q: Изменить стиль оглавления в приложениях Оформляю дипломную работу. В конце работы должны быть приложения, которые должны отображаться в содержании определённым образом, в отличии от самой работы, примерный вид:
Содержание

1 Название главы ......страница
  1.1 Название секции ......страница
     1.1.1 Название пункта ......страница
Приложение А ......страница
Приложение Б ......страница

То есть:

*

*Если в приложении есть секции - они не должны отображаться

*Заголовки приложений тоже не должны отображаться

Постарался выделить минимальный рабочий код, на котором видна проблема:
\documentclass[fontsize=14bp,a4paper]{scrreprt}

% Подключение пакетов
%===================================================
\usepackage{polyglossia}    %для русского языка
\usepackage[left=25mm, right=15mm, top=20mm, bottom=20mm, footskip=10mm]{geometry} %задаёт поля документа
\usepackage{tocloft} %пакет для оформления оглавления
\usepackage{titlesec} %пакет для оформления заголовков
\usepackage[nottoc]{tocbibind} %добавление списка источников в оглавление
\usepackage[titletoc]{appendix} %добавление приложений в оглавление

% Установка параметров для документа
%===================================================
\setdefaultlanguage[forceheadingpunctuation=false]{russian}  % устанавливает главный язык документа, опция - убирает последнюю точку в нумерации заголовков
\setotherlanguage{english} % объявляет второй язык документа
\pagestyle{plain} %номера страниц будут печататься снизу и при этом колонтитулов не будет
\defaultfontfeatures{Ligatures={TeX}, Renderer=Basic}
\setmainfont{Liberation Serif}
\setsansfont{Liberation Serif}
\setmonofont{Liberation Mono}
\parindent=1.25cm %красная строка

\renewcaptionname{russian}{\contentsname}{\normalsize \MakeUppercase{Содержание}} %заголовок оглавления
\renewcaptionname{russian}{\appendixname}{Приложение} %заголовок приложений
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % заполнение точками Глав в оглавлении

%параметры заголовков разделов (глав)
\titleformat{\chapter}[hang]{\normalsize\bfseries}{\thechapter~}{0pt}{\thispagestyle{empty}\MakeUppercase}
\titlespacing{\chapter}{\parindent}{0bp}{2\baselineskip}
%параметры заголовков подразделов (секций)
\titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
\titlespacing{\section}{\parindent}{\baselineskip}{\baselineskip}
\titleformat{\subsection}[hang]{\normalsize\bfseries}{\thesubsection~}{0pt}{}
\titlespacing{\subsection}{\parindent}{\baselineskip}{\baselineskip}

\begin{document}
    \begin{titlepage}
        Титульный лист
    \end{titlepage}

    \tableofcontents{}
    \thispagestyle{empty}
    \clearpage

    \chapter{Первая}
        \section{Первый}
            \subsection{первый}

    \chapter{Вторая}
        \section{Второй}
            \subsection{второй}

    \begin{appendices}
        \titleformat{\chapter}[display]{\normalsize\bfseries}{\centering\appendixname~\thechapter}{0pt}{\centering\thispagestyle{empty}\MakeUppercase}
        \titlespacing{\chapter}{\parindent}{0bp}{\baselineskip}
        \titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
        \titlespacing{\section}{0bp}{0bp}{\baselineskip}

        \chapter{Первое приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}

        \chapter{Второе приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}
    \end{appendices}
\end{document}

Находил около 2,5 решения этого вопроса, но ни одно не работает:

*

*Команда \addtocontents{toc}{\setcounter{tocdepth}{0}} - компилятор ругается (и похожее решение - объявить отдельную команду под это)

*Пакет tocvsec2 с командой \settocdepth{chapter} - просто не работает, полный игнор

Есть подозрения, что имеются какие-то конфликты - поэтому ни один из способов нерабочий. Что касается удаления заголовков из содержания - тоже не нашёл никакого решения, но подозреваю, что его нужно подставить в окружение appendices. Искал в том числе и в документации пакета tocloft, который использую.
Дистрибутив: TeXLive
Компилятор: XeLaTeX

A: Я внес незначительные изменения в Ваш код и, если я правильно понял чего Вы добивались, все получилось.

*

*Чтобы удалить названия приложений верхнего уровня я просто воспользовался штатным средством - для секций в LaTeX можно указывать как необязательный параметр альтернативное имя, которое будет отображаться в колонтитулах и оглавлении. Если сделать просто пустое имя, типа \chapter[]{Название раздела}, то тогда этот раздел в оглавление совсем не попадет, но если обмануть компилятор и скормить туда что-то фиктивное (я в одном случае использую вертикальный фантом, а в другом просто пустую внутристрочную формулу), то всё срабатывает как надо. Ну, можно конечно придраться к немного большему пробелу от метки приложения до отточия, но может и так сойдет?

*Чтобы убрать из оглавления заголовки меньшего уровня у меня получилось использовать пакет tocvsec2 с командой \settocdepth{chapter}. И естественно, при любых изменениях заголовков (и всего, что касается сборки оглавления) компилировать документ нужно как минимум два раза. После секции с приложениями я еще добавил необязательную (здесь) команду \resettocdepth, которая должна вернуть учет уровня заголовков для оглавлений (вдруг после приложений еще какой-то блок будет? :-) ).
Если что, я тестировал всё это в XeLaTeX от TeXLive 2020 под MS Win10. И я слегка изменил строку с указанием языка по умолчанию, поскольку мой компилятор не принимает опцию [forceheadingpunctuation=false].
Собственно, ниже сам код и результат компиляции.
\documentclass[fontsize=14bp,a4paper]{scrreprt}

% Подключение пакетов
%===================================================
\usepackage[utf8]{inputenc}  % Кодировка исходного текста
\usepackage[T2A]{fontenc}   %внутренняя кодировка

\usepackage{polyglossia}    %для русского языка
\usepackage[left=25mm, right=15mm, top=20mm, bottom=20mm, footskip=10mm]{geometry} %задаёт поля документа
\usepackage{tocloft} %пакет для оформления оглавления
\usepackage{titlesec} %пакет для оформления заголовков
\usepackage[nottoc]{tocbibind} %добавление списка источников в оглавление
\usepackage[titletoc]{appendix} %добавление приложений в оглавление

\usepackage{tocvsec2}

% Установка параметров для документа
%===================================================
%\setdefaultlanguage[forceheadingpunctuation=false]{russian}  % устанавливает главный язык документа, опция - убирает последнюю точку в нумерации заголовков
\setdefaultlanguage[indentfirst=true]{russian}
\setotherlanguage{english} % объявляет второй язык документа
\pagestyle{plain} %номера страниц будут печататься снизу и при этом колонтитулов не будет
\defaultfontfeatures{Ligatures={TeX}, Renderer=Basic}
\setmainfont{Liberation Serif}
\setsansfont{Liberation Serif}
\setmonofont{Liberation Mono}
\parindent=1.25cm %красная строка

\renewcaptionname{russian}{\contentsname}{\normalsize \MakeUppercase{Содержание}} %заголовок оглавления
\renewcaptionname{russian}{\appendixname}{Приложение} %заголовок приложений
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % заполнение точками Глав в оглавлении

%параметры заголовков разделов (глав)
\titleformat{\chapter}[hang]{\normalsize\bfseries}{\thechapter~}{0pt}{\thispagestyle{empty}\MakeUppercase}
\titlespacing{\chapter}{\parindent}{0bp}{2\baselineskip}
%параметры заголовков подразделов (секций)
\titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
\titlespacing{\section}{\parindent}{\baselineskip}{\baselineskip}
\titleformat{\subsection}[hang]{\normalsize\bfseries}{\thesubsection~}{0pt}{}
\titlespacing{\subsection}{\parindent}{\baselineskip}{\baselineskip}

\begin{document}
    \begin{titlepage}
        Титульный лист
    \end{titlepage}

    \tableofcontents{}
    \thispagestyle{empty}
    \clearpage

    \chapter{Первая}
        \section{Первый}
            \subsection{первый}

    \chapter{Вторая}
        \section{Второй}
            \subsection{второй}

    \begin{appendices}
        \titleformat{\chapter}[display]{\normalsize\bfseries}{\centering\appendixname~\thechapter}{0pt}{\centering\thispagestyle{empty}\MakeUppercase}
        \titlespacing{\chapter}{\parindent}{0bp}{\baselineskip}
        \titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
        \titlespacing{\section}{0bp}{0bp}{\baselineskip}

        \settocdepth{chapter}
        \chapter[\vphantom{A}]{Первое приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}

        \chapter[\(\)]{Второе приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}
    \end{appendices}
    \resettocdepth
\end{document}

A: Посмотрите вот это:
http://mydebianblog.blogspot.com/2011/05/latex.html
Мне кажется. там как раз про это:

если в документе есть Appendix, то отображать в оглавлении его
subsections совсем не обязательно.
Для этого есть пакет tocvsec2 который позволяет нам менять уровень
отображения разделов там, где нам надо.


text:
Q: International Power Converter I am going out of th country in a few weeks, and I am planning on taking my Macbook. I have a power adapter for the country I'm visiting, but it was bought for a PC. Will it work on a Mac?

A: You don't need a power converter, as Apple power supplies will all take 100-240V at 50 or 60 Hz, so a simple mechanical adaptor will do. Having said that, anything that will work with a PC power supply should also work with a Mac.


text:
Q: Drag Drop Feature and Arrow Map I intend to make a flowchart tool which if feasible will use a drag and drop feature, such as drag a rhombus, oval, diamond box etc. and the arrows that can connect them.
Can anyone please suggest proper language to begin which can support features like defining objects for rectangle, arrows, and there mapping so that i know a particular arrow is pointing to a rectangle with ID xyz....
I am tagging this question with jquery, javascript,actionscript...some libraries that i know by name not by technical expertise if in case they do support what i am looking for.
Please suggest.

A: This is meant as a starting point: http://jsfiddle.net/Qgt9V/2/
$( ".box-handle" ).draggable({
    containment: ".container",
    scroll: false,
    drag: function () { /* While dragging check for stuff */

        var box = $(this);
        var boxPosition = box.position();
        box.find('.arrow').show();

        if (boxPosition.left >= 90)
        {
            // In the parent div called ".box" find ".box-line"
            box.closest('.box').find('.box-line').css({
                'top':'50px', /* Put top left corner of ".box-line" a the edge of ".static" */
                'left':'110px',
                'width': boxPosition.left - 60, /* Put bottom right corner of ".box-line" a the edge of current dragged box */
                'height': boxPosition.top + 50,
                'border':'none',
                'border-top':'1px solid #bfbfbf',
                'border-right':'1px solid #bfbfbf'
            });
            /* place the arrow*/
            box.find('.arrow').css({
                'top':'-10px',
                'left':'45px'
            });
        }
        else if (boxPosition.left < 90)
        {
            box.closest('.box').find('.box-line').css({
                'top':'110px',
                'left':'50px',
                'width': boxPosition.left,
                'height': boxPosition.top - 60,
                'border':'none',
                'border-left':'1px solid #bfbfbf',
                'border-bottom':'1px solid #bfbfbf'
            });
            box.find('.arrow').css({
                'top':'45px',
                'left':'-10px'
            });
        }
    }
});

I'm using jQuery UI draggable for moving div's around. While moving the div "box-line" resizes itself according to the position of the box I'm dragging. Then it's just a matter of adding borders to the correct side of "box-line".

*

*More about draggable.

*Also have a look at position and/or offset methods.

A: See also this question, which references the excellent JsPlumb.
The toolkit edition includes drag and drop in the community edition and actually has a demo flowchart app in the (very expensive) toolkit edition.
In fact the community edition fully answers your question. Take a look at the perimeter anchors demo.


text:
Q: Безопасность на сервере У меня на сайте есть серверная часть, которая обрабатывает post запросы из js. Как мне сделать, чтоб все post запросы, кроме из js, игнорировались и чтоб переделаный код в браузере юзером не исполнялся?

A: В любом случае, клиентская часть уязвима, нет надежного способа определить, что из нее пришла информация только от JS (это можно подделать).
Также не понятен этот момент:

чтоб переделаный код в браузере юзером не исполнялся

Может "переданный" код? Если так, то его все равно может исполнить тот, кому такое очень нужно, если изменит клиентскую часть под эту задачу.


text:
Q: Trying to add annotations to my map in Titanium 3.4 I'm trying to add annotations to my map in Titanium and I keep ending up with this error:
"line = 37;
message = "Invalid type passed to function";
Invalid type passed to function"
nativeLocation = "-[TiMapViewProxy annotationFromArg:] (TiMapViewProxy.m:120)";
nativeReason = "expected: Object, was: NSNull";"
Here's my code. As far as I know it should work.
//This is the code to implement a map and store locations using annotations
var locationsTabGroup = Titanium.UI.createTabGroup({
    barColor: '#E62B2B'
});

var locationsToHome = Titanium.UI.createButton({
title: 'Back',
titleAttributes: {
color: 'white'
},
backgroundImage: 'images/revisedbackbutton2.png',
height: 35,
width: 80,
borderRadius: 10
});

var locationsWindow = Titanium.UI.createWindow({
    leftNavButton: locationsToHome,
    title:'Select Store',
    tabBarHidden: true,
    titleAttributes:  {
        color:'white'
       }
});

var MapModule = require('ti.map');

var locationsMap = MapModule.createView({
    mapType: MapModule.NORMAL_TYPE,
    animate: true,
    region: {latitude: -27.962939, longitude: 153.382428, latitudeDelta: 0.1, longitudeDelta: 0.1 },
    height: '100%',
    top: 0,
    width: Ti.UI.FILL,
    annotations: [store1]
});

var store1 = MapModule.createAnnotation({
    latitude: -27.465868,
    longitude: 153.028309,
    pincolor: MapModule.ANNOTATION_RED,
    title: 'Pita Pit Brisbane',
    subtitle: '280 Adelaide St, Brisbane QLD 4000'
});

var store2 = MapModule.createAnnotation({
    latitude: -27.499154,
    longitude: 152.972711,
    pincolor: MapModule.ANNOTATION_RED,
   title: 'Pita Pit Indooroopilly',
    subtitle: '322 Moggill Rd, Indooroopilly QLD 4068'
});

var store3 = MapModule.createAnnotation({
    latitude: -27.453312,
    longitude: 153.034908,
    pincolor: MapModule.ANNOTATION_RED,
    title: 'Pita Pit Green Square',
    subtitle: '6/515 St Pauls Terrace, Fortitude Valley QLD 4006'
});

var locationsTab = Titanium.UI.createTab({
    window: locationsWindow
});

locationsWindow.add(locationsMap);
locationsTabGroup.addTab(locationsTab);

A: You are using the annotation before it is created.
You should declare all your annotations before passing them to the map.
Or don't set the annotations at creation and use locationsMap.setAnnotations([store1, store2, store3]); once your annotations have been declared.


text:
Q: Is this method allowed for centering an object with css? Is this way to center an object?
This method creates a accurate center position as well, is there another method to do this?
.content {
    width:1200px;
    height:800px;
    position:absolute;
    left:50%;
    margin-left:-600px;
    top:50%;
    margin-top:-400px;
}

Thanks for your time.

A:

(function() {
  var toggle = true;
  setInterval(function() {
    if (toggle) {
      $("#content").html("Line 1");
    } else {
      $("#content").html("
Line 1

Line 2
");
    }
    toggle = !toggle;
  }, 1300);
}());
body {
  font: 36px Arial, sans-serif;
}

#container {
  color: white;
  background: #ffbd17;
  width: 400px;
  height: 260px;
}

#content {
  background: #06c;
  width: 120px;
  margin-left: auto;
  margin-right: auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Centering example:

    Line 1

A: Try simply:
content{
   margin:50% auto;
   text-align:center;/* if content has text then*/
   /*Your other properties like:width,height,etc*/
}

A: yups thats the exact way if you want to center any div on both horizontally and vertically.
Negative margins are exactly half the height and width, which pull the element back into perfect center. Only works with elements of a fixed height/width.
or you can use
.content{
    width:400px;
    height:200px;
    text-align:center;
    line-height:200px;
}

or you can use it in inline coding if you dont have specific measure

<!–content–>

For further help, go this tutorial, its the good and quite helpful in understanding in centering the elements horizontally and vertically.
Regards.

A: I would solve it like this using display: table-cell;. This way it gets centered vertically and horizontally and it does not depend of the height of the element you want to display.
HTML

        I'm centered.

CSSS
html {
    width: 100%;
    height: 100%;
}
body {
    display: table;
    width: 100%;
    height: 100%;
}
.wrapper{
    display: table-cell;
    vertical-align: middle;
}

.content {
    width: 200px;
    height: 200px;
    border: 1px solid red;
    margin: 0 auto;
}

Demo
http://jsfiddle.net/Gyq4t/
Note
This works fine in every modern browser. I does not work in IE7.


text:
Q: Passing Form Data to separate PHP Page I have a table with multiple columns (index.php). One column is a checkbox. Whenever the checkbox is checked, it displays another row where you can select a quantity. You can then hit a button called "Add to Order" and it will take you to a confirmation page (index-order.php) where I want it to display each row along with all of the data in that specified row that has the checkbox checked. Currently, I am getting no errors in my console, but no data is being displayed at all.
What do I need to change to make this happen? Here is what I have so far.
Index.php code:
<form name="form1" method="POST" action="index-order.php">

<button type="submit" class="order" id="order" name="order" value="AddToOrder">Add to Order</button>

            Loc
            Report Code
            SKU
            Special ID
            Description
            Quantity
            Unit
            Quantity #

        <?php foreach ($dbh->query($query) as $row) {?>

        <input type="checkbox" class="check" name="check">
        <td name="rows[0][0][loc]" class="loc ui-widget-content" id="loc-<?php echo intval ($row['Loc'])?>"><?php echo $row['Loc'];?>
        <td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?>
        <td name="rows[0][0][sku]" class="sku ui-widget-content" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?>
        <td name="rows[0][0][special-id]" class="special-id ui-widget-content" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?>
        <td name="rows[0][0][description]" class="description ui-widget-content" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?>
        <td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?>
        <td name="rows[0][0][unit]" class="unit ui-widget-content" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?>
        <input type="textbox" style="width: 100px;" class="spinner" name="value" id="test">

    <?php } ?>

</form>

Index-order.php:
<?php if(isset($_POST['rows'])): ?>

        Loc
        Report Code
        SKU
        Special ID
        Description
        Quantity
        Unit
        Quantity #

    <?php
        foreach($_POST['rows'][0] as $row):
    ?>

            <?php echo $row['loc']; ?>
            <?php echo $row['rp-code']; ?>
            <?php echo $row['sku']; ?>
            <?php echo $row['special-id']; ?>
            <?php echo $row['description']; ?>
            <?php echo $row['quantity']; ?>
            <?php echo $row['unit']; ?>
            <?php echo $row['quant']; ?>

    <?php
        endforeach;
    ?>

A: I am okay with the precedent answer, I never heard about this kind of method with PHP and it doesn't seems to be the right solution. Anyway, the following post would maybe help you : How to get value from td's via $_POST.
You cannot transfer datas through POST by using td ; but an alternative would be to use the "hidden" type of forms element :
<form action="script.php" method="post">
<input type="hidden" name="td1" value="...">value
...
</form>

In PHP, you'll grab the data with the $_POST array and the td1 name :
<?php var_dump($_POST); ?>

Itwould in my opinion be the easier way to get what you want in a proper way ; the link I gave upper is also talking about DOMDocument, but it looks more complex to manage with.


text:
Q: Is there a way in Java to check the availability of a network printer? I tried to use javax.print libraries to check for the network printer status without an effect results. the only 4 attributes i am getting are the following:
queued-job-count , printer-name, printer-is-accepting-jobs, color-supported
I need more detailed status such as "out of paper" and things like that. I read about PrinterStateReason but couldn't know how to implement.
Any ideas how to do that?


text:
Q: How to sort data in Descending order in JsonResult? I have this function
public JsonResult GetStoreIndNo(string STranNo, string sStatus, string
SToStore)
    {
        StoreMdClient smClient = new StoreMdClient();
        string StoreCode = ("" + HttpContext.Session["StoreCode"]).Trim();
        DataSet ds = new DataSet();
        if (sStatus == "N") ds.ReadXml(new XmlTextReader(new StringReader(smClient.GetStoreIndNoDataNew(SToStore, StoreCode, "", BL_GeneralFunctionsSUMDTLS.Summary))));
        else ds.ReadXml(new XmlTextReader(new StringReader(smClient.GetStoreIndNoDataDisply(STranNo, BL_GeneralFunctionsSUMDTLS.Summary))));

        DataTable load = new DataTable();
        if (ds.Tables.Count > 0) load = ds.Tables[0];
        var jsondata = new
        {
            rows = (from DataRow row in load.Rows
                    select new
                    {
                        id = ("" + row["INDENTNO"]).Trim(),
                        cell = new string[] {
                            GeneralFunction.GetDate(("" + row["INDENTDATE"]).Trim()), ("" + row["INDENTNO"]).Trim()
                     }
        }).ToArray()
        };
        return Json(jsondata);
    }

I get value in ds.ReadXml after which when it is loaded in DataTable here, I want to arrange or sort the rows with descending order. I get values in two column like this :-
1           24/04/2017      26SI170424PH0001
2           24/04/2017      26SI170424PH0002
3           24/04/2017      26SI170424PH0003
I want to sort in "desc" order. Datewise in first column and using the last 3 digits of second column.
Also, here is my jQuery:
function StoreIndNoBind(condiA) {
        if (condiA == 'empty' || condiA == 'enablefill' || condiA == 'disablefill') {
            var FrmdateA = ""; var ToDateA = "";
            var sStatus = gact;
            var SToStore = ("" + $("#cmbToStoreSel").select2("val")).trim();
            if (condiA == 'empty') {
                STranNo = "";
                var urlq = "GetStoreIndNo?STranNo=" + STranNo + "&&sStatus=" + sStatus + "&&SToStore=" + SToStore;
            }
            else {
                STranNo = ("" + $("#txtTranNo").val()).trim();
                var urlq = "GetStoreIndNo?STranNo=" + STranNo + "&&Status=" + sStatus + "&&SToStore=" + SToStore;
            }
        }
        colnames = ['Indent Date', 'Indent Number'];
        $("#GridIndentNo").jqGrid('GridUnload');
        $("#GridIndentNo").clearGridData();
        $("#GridIndentNo").jqGrid({
            url: urlq,
            datatype: 'json',
            mtype: 'post',
            colNames: colnames,
            colModel: [
                { name: 'INDDATE', index: 'INDDATE', width: 93, editable: false },
                { name: 'INDENTNO', index: 'INDENTNO', width: 140, editable: false }
            ],
            sortname: 'id',
            sortorder: 'desc',
            shrinkToFit: false,
            hidegrid: false,
            gridView: true,
            rownumbers: true,
            loadonce: true,
            multiselect: true,
            sortableColumns: false,
            cellsubmit: 'clientArray',
            height: 110,
            width: 316,
            rowNum: 9999999999,
            ondblClickRow: true,
            loadtext: 'Loading.....',
            footerrow: false,
            gridComplete: function () {
                if (condiA != 'empty' && condiA != '') {
                    var ids = jQuery("#GridIndentNo").jqGrid('getDataIDs');
                    if (ids.length >= 0) {
                        for (var i = 0; i < ids.length; i++) {
                            $(this).find('>tbody>tr.jqgrow>td>input[type="checkbox"]')[i].checked = true;
                        }
                        if (condiA == 'disablefill') {
                            var cbs = $("tr.jqgrow > td > input.cbox", $("#GridIndentNo")[0]);
                            var hbs = $("tr.ui-jqgrid-labels > th > div > input.cbox", $("#GridIndentNo")[0]);
                            cbs.prop("disabled", "disabled");
                            hbs.prop("disabled", "disabled");
                        }
                    }
                }
            },
            beforeSelectRow: function (rowid, e) {
                if (e.target.type == 'checkbox' && e.toElement.cellIndex == undefined) {
                    if (e.target.checked == true) GetIndentMtrlBind(rowid,e);
                    else RmvMtrlForIndentNo(rowid);
                }
            },
        }).trigger("reloadGrid");
        $("#cb_GridIndentNo")[0].style.display = 'none';
        $('.ui-jqgrid-sdiv').removeClass('ui-widget-content');
        $("#GridIndentNo").parents('div.ui-jqgrid-bdiv').css("overflow-y", "scroll");
}

A: I've set row.Date because i dont know the Date column name or the identifier column name, i've said them Date and Number:
  rows = (from DataRow row in load.Rows
              let lasts = row.Number.Substring(row.Number- 3, 3)
             orderby row.Date descending, lasts descending
                select new
                {
                    id = ("" + row["INDENTNO"]).Trim(),
                    cell = new string[] {
                        GeneralFunction.GetDate(("" + row["INDENTDATE"]).Trim()), ("" + row["INDENTNO"]).Trim()
                 }
    }).ToArray()

A: Thanks Jordi,
I have found yet another way to do the same.
 DataView dv = ds.Tables[0].DefaultView;
 dv.Sort = "INDENTDATE desc";
 dv.Sort = "INDENTNO desc";
 DataTable sortedDT = dv.ToTable();

this works too.,
Have a nice day.,


text:
Q: Problemas sobre Python y mariadb code=3221225477 al realizar la consulta, solo me recupera primera fila, el codigo es el siguiente
from email.mime import application
from tkinter import *
from tkinter import ttk
import mariadb

class ReporteCaja:
    def __int__(self,ventana):
        self.ventana=ventana
        self.ventana.title("Hola Mundo")
        marco=LabelFrame(self.ventana,text="ReporteCaja")
        marco.grid(row=0,column=1)
        #nombre
        Label(marco,text="Nombre").grid(row=0,column=0)
        Entry(marco).grid(row=0,column=1)
        #clave
        Label(marco,text="Clave").grip(row=1,column=0)
        Entry(marco).grid(row=1,column=1)
        #Boton
        ttk.Button(marco,text="Guardar Alumno").grip(row=2,columnspan=2,sticky=W+E)

    def consulta(self,query):
        try:
            conn=mariadb.connect(
                host="host",
                user="automaton",
                password="****",
                database="prueba"
            )
        except mariadb.Error as identifer:
            print("Error al conectar al DB")

        cur=conn.cursor()
        cur.execute(query)
        return cur

    def mostrarDatos(self):
        cur=self.consulta("select Name from User ")
        for (Name) in cur:
            print(Name)

if __name__=="__main__":
    ventana=Tk()
    application=ReporteCaja()
    application.mostrarDatos()
    ventana.mainloop()

dicha tabla tiene 160 filas pero solo logro imprimir 17 filas de ella luego finaliza el codigo, en VSC suele salir el error [Done] exited with code=3221225477, la verdad ni idea de donde mirar, si tienen alguna idea de ello, o de por ahi si estoy cometiendo una feroz novatada


text:
Q: How to interpret dummy and ratio variable interactions in R I have performed a regression examining data on crime rates. It looks at a standard ratio type variable (beginning crime rate at a point in  time) and a dummy variable (if the countries crime rate is in the top mid or bottom third of beginning crime rates). We consider the effect upon the change in crime over time, crmdelta. The model code and HC standard error regression output is as follows:
df$rank.f <- factor(df$rank)
eqn1 <- lm(crmdelta ~ crmbegin+rank.f+(crmbegin*rank.f), data=df)

                Estimate Std. Error t value Pr(>|t|)
(Intercept)       3.57085    4.04330  0.8832  0.37839
crmbegin         -0.15049    0.29486 -0.5104  0.61045
rank.f2          -3.38911    4.22533 -0.8021  0.42361
rank.f3           1.59112    4.69654  0.3388  0.73518
crmbegin:rank.f2  0.16871    0.43199  0.3906  0.69661
crmbegin:rank.f3 -3.12450    1.64205 -1.9028  0.05874 .

2 questions:
(1) I cant tell what happened to the interaction crmbegin:rank.f1. Is this represented by crmbegin? And if so, is there no lone crmbegin variable even though it was specified in the regression?
(2) How do I precisely interpret the coefficients on the interactions? Is it the effect of the ratio variable given the singular case of whichever dummy is in effect? Ie. crmbegin:rank.f2 is the marginal effect of crmbegin, given we are operating in rank.f2 data subset?
Thanks very much for any help. My first post here and looks like a great community.

A: Sigh... out of the concern that they will "eat you alive" over there on Cross Validated, I might give you a brief answer. My answer will be migrated along with your question. (So Stack Overflow fellows, do not vote me down, please.)

Understanding your interaction model
Your model is a regression line per group:
crmdelta = alpha[i] + beta[i] * crmbegin

where group rank_fi has intercept alpha[i] and slop beta[i].

Interpretation of your model coefficients

*

*(Intercept): alpha[1]

*crmbegin: beta[1]

*rank.f2: alpha[2] - alpha[1]

*rank.f3: alpha[3] - alpha[1]

*crmbegin:rank.f2: beta[2] - beta[1]

*crmbegin:rank.f3: beta[3] - beta[1]
If you ask why it is like this, well, it is due to the contrast treatment of factor variables.

misc
crmbegin:rank.f2 is not a ratio variable; : denotes interaction.
You can replace your call to lm() by: eqn1 <- lm(crmdelta ~ crmbegin * rank.f, data=df) (Read ?formula for more on this).


text:
Q: Rounding of significant figures if less than 1 in R I would like to create a function in R that rounds numeric dataframes (or columns in a dataframe) depending on the number. If the number is less than 1, round to 1 decimal, but if it is greater than 1, round to 0 decimals.
This is what I have
data <- data.frame(x = c(1.111, 0.809, 5.55555, 0.567), y = c(0.235, 0.777, 4.55555555, 393.55))
round0 <- function(x) format(round(x, digits=0), nsmall = 0, trim = TRUE)
round0(data)
   x   y
1  1   0
2  1   1
3  6   5
4  1 394

# What I want
   x   y
1  1   0.2
2 0.8  1
3  6   5
4  1 394

A: > round0 <- function(x) ifelse(x<1,round(x,1),round(x))
> sapply(data,round0)
       x     y
[1,] 1.0   0.2
[2,] 0.8   0.8
[3,] 6.0   5.0
[4,] 0.6 394.0

A: You can use :
round0 <- function(x) ifelse(x < 1, format(round(x, 1), nsmall = 1), round(x))
data[] <- lapply(data, round0)
data
#    x     y
#1   1   0.2
#2 0.8   0.8
#3   6     5
#4 0.6   394

Note that this is only for display purpose and classes of columns are of type character. If you want to perform any mathematical calculation on it you need to convert it back to numeric.


text:
Q: Two different maximum symmetry metrics Let $ M $ be a compact connected manifold. The degree of symmetry of $ M $, denoted $ N(M) $, is the maximum of the dimensions of the isometry groups of all possible Riemannian structures on $ M $. See for example
https://www.ams.org/journals/tran/1969-146-00/S0002-9947-1969-0250340-1/S0002-9947-1969-0250340-1.pdf
Does there exists a compact connected manifold $ M $ and two metrics $ g_1,g_2 $ such that
$$
dim(Iso(M,g_1))=N(M)=dim(Iso(M,g_2))
$$
but the isometry groups $ Iso(M,g_1) $ and $ Iso(M,g_2) $ are non isomorphic Lie groups?
I'm mostly interesting in the case that $ Iso(M,g_1) $ and $ Iso(M,g_2) $ are semisimple or even simple. I'm also mostly interested in the connected component of the identity. So examples like the flat metric on the hexagonal torus $ T^2 $ versus the square torus $ T^2 $ don't really concern me because the isometry groups agree on the identity component.
What I'm really looking for would be something like $ N(M)=21 $ and $ Iso(M,g_1)=Sp(3) $ while $ Iso(M,g_2)=Spin_7 $
This question
Uniqueness of metric from compact simple group of isometries
gives examples like round $ S^5=SO_6/SO_5 $ and Berger $ S^5=SU_3/SU_2 $. But the Berger sphere does not have an isometry group of maximum dimension $ dim(Iso(SU_3/SU_2))=8 \neq 15= dim(Iso(SU_3/SU_2)) = N(S^5) $


text:
Q: Angular directive, link not called when attribute updates In the following example: http://plnkr.co/edit/OZjg6sUgl35GIriaabQg?p=preview
I've got 2 directives, the showCard one inside an ng-repeat which link function get called any time the attribute is updated. (see the console)
The other one showCards is working properly but the link function is not called when the attribute is updated, but only once at the beginning.
I'd like to understand the difference between those 2 kind.

A: The linking function is only invoked once per element, so whenever you add a new card the ngRepeat-directive will add a new <show-card ...> which will invoke the link function.
If you want some function to trigger every time cards is changed you can add a $watch function on the scope in the showCards link function, like this:
   $scope.$watch('cards',function(){
     console.log('multi',$scope.cards);
   },true);


text:
Q: How does linux manage threads stack On intel x86 32/64 bits architecture, each thread owns it own stack.
Where the kernel switch between threads of the same process, stack and registers of current threads are backuped somewhere. I suppose it is in a stack ?
Does that mean if i have N thread on my process, i will have N+1 stacks in the process memory ? Or is it managed by kernel ? Can i thread read the stack of another thread if it knows esp/bsp of that thread ?
(i am talking about threads of the same process)

A:
Where the kernel switch between threads of the same process, stack and registers of current threads are backuped somewhere. I suppose it is in a stack ?

Yes, thats correct. Usually, a rescheduling is triggered by a timer interrupt. A timer interrupt, like any other hardware-interrupt[1], requests the CPU to stop working on what it is working at the moment and execute some special code, the interrupt service routine. The kernel can set this up itself, so it is just a function provided by the kernel. Usually, the first thing a kernel does when an interrupt happens is, it pushes all registers onto the stack. The only thing the kernel has to save is the top of the stack, the esp. When the kernel now switches to another thread, all it has to do is load the new threads esp and pop back all the registers.

Does that mean if i have N thread on my process, i will have N+1 stacks in the process memory ?

You'll most likely have N stacks in your memory and N stacks in kernel memory, as a interrupt, calling into kernel code, loads another stack. Usually, every thread has it's own kernel stack, but don't quote me on that.

Can i thread read the stack of another thread if it knows esp/bsp of that thread ? (i am talking about threads of the same process)

Yes, you can. Threads in the same process share the same virtual address space, so if you know where exactly a threads stack is you can access this memory.

[1]: A hardware interrupt is triggered by the Programmable Interrupt Controller from the "outside" of the CPU when something happens, like a key-press on your keyboard. There are also software interrupts, which are triggered by the cpu/the software itself, either intended or to handle an error (division by zero). Software interrupts are one way to implement systemcalls, because you can not call ring-0 code from ring-3 code. A interrupt however can jump "up" to ring-0 if the TSS is set up to do so.


text:
Q: Fire an event from Laravel controller and listen on Livewire component I'm trying to figure if i could emit an event from a Laravel regular controller and define a listener on a Livewire component. There's my journey so far:
I've generated the event:
php artisan make:event NewOrder

then, on the Controller method placeNewOrder i'm triggering the event like this:
event(new NewOrder())

On the Livewire component i define a varible $showNewOrderNotification and the listener:
public $showNewOrderNotification = false

protected $listeners = ['NewOrder' => 'notifyNewOrder'];

and setting the method notifyNewOrder
 public function notifyNewOrder()
    {
        $this->showNewOrderNotification = true;
    }

the livewire view is only showing an alert when the $showNewOrderNotification variable is true:
@if($showNewOrderNotification)
  <div class="alert alert-danger text-uppercase">
    New Orders !!!
  </div>
@endif

This should be pretty straight forward but for some reason the listener is not getting the event.
I appreciate all the help.

A: user1 = order processor
user2 = customer
Scenario 1:
If user2 places a new order and you're trying to update user1's interface, you'll need to look into broadcasting to get your livewire component to pickup the event for user1.
https://laravel.com/docs/8.x/broadcasting
https://laravel-livewire.com/docs/2.x/laravel-echo
Scenario 2:
If user2 places a new order and you're trying to update user2's interface, it would probably be best to just convert the controller to an entire livewire component and avoid the controller all together.  It can be done just storing session variables and checking for those variables using wire:init in your livewire blade view, but much easier to just do it all in a livewire component to begin with.


text:
Q: C# DataGridView Text Style?
See my datagridview.
First record was added via HeidiSQL.
Second was added via DataGridView on C# Winform.
I just want the first record style.
Can anyone tell me what makes second style and how I can fix it?
Thanks in advance.


text:
Q: Durandal (knockout) app with multilanguage support I am building multilingual support for the app I'm working on. After doing some research and reading SO  (internationalization best practice) I am trying to integrate that in a 'framework-friendly' way.
What I have done at the moment is following:
Created .resource modules formatted like so:
resources.en-US.js
define(function () {
   return {
       helloWorlLabelText: "Hello world!"
   }
});

On the app.start I get the resource module with requirejs and assign all data to app.resources. Inside of each module specific resource is assigned to observables and bonded with text binding to labels and other text related things. Like so:
define(function (require) {
   var app = require('durandal/app'),
       router = require('durandal/plugins/router')
   };
   return{
       helloWorldLabelText: ko.observable(app.resources.helloWorldLabelText),

       canDeactivate: function () {
      }
   }
});

On the view:

The resources are swapped just by assigning new module to app.resources.
Now the problem is when the language is changed and some of the views have been already rendered, the values of previous language are still there. So I ended up reassigning observables inside of activate method. Also tried wrapping app.resources into observable, but that didn't work either.
I don't think I ended up with the most clean way and maybe anybody else had some other way that could share. Thanks.

A: I was quite inspired by the answers in SO regarding this topic, so I came up with my own implementation of a i18n module + binding for Knockout/Durandal.
Take a look at my github repo
The choice for yet another i18n module was that I prefer storing translations in databases (which ever type required per project) instead of files. With that implementation you simply have a backend which has to reply with a JSON object containing all your translations in a key-value manner.
@RainerAtSpirit
Good tip with the singleton class was very helpful for the module

A: You might consider having one i18n module that returns a singleton with all required observables. In addition a init function that takes an i18n object to initialize/update them.
define(function (require) {
   var app = require('durandal/app'),
       i18n = require('i18n'),
       router = require('durandal/plugins/router')
   };
   return{

       canDeactivate: function () {
      }
   }
});

On the view:

A: Here is an example repo made using i18next, Knockout.Punches, and Knockout 3 with Durandal:
https://github.com/bestguy/knockout3-durandal-i18n
This allows for Handlebars/Angular-style embeds of localized text via an i18n text filter backed by i18next:

  {{ 'home.label' | i18n }}

also supports attribute embeds:

  {{ 'home.label' | i18n }}

And also lets you pass parameters:

  {{ 'home.welcome' | i18n:name }}

JSON example:
English (en):
{
  "home": {
    "label": "Home Page",
    "title": "Type your name…"
    "welcome": "Hello {{0}}!",
  }
}

Chinese (zh):
{
  "home": {
    "label": "家",
    "title": "输入你的名字……",
    "welcome": "{{0}}您好!",
  }
}

A: For those who are still confused about best practices, those who feel that something is lacking, or those who are simply curious about how to implement things in a better way with regard to Durandal, Knockout, RequireJS, and client-side web applications in general, here is an attempt at a more useful overview of what's possible.
This is certainly not complete, but hopefully this can expand some minds a little bit.
First, Nov 2014 update
I see this answer keeps being upvoted regularly even a year later. I hesitated to update it multiple times as I further developed our particular solution (integrating i18next to Durandal/AMD/Knockout). However, we eventually dropped the dependent project because of internal difficulties and "concerns" regarding the future of Durandal and other parts of our stack.  Hence, this little integration work was canceled as well.
That being said, I hopefully distinguished generally applicable remarks from specific remarks below well enough, so I think they keep offering useful (perhaps even well needed) perspectives on the matters.
If you're still looking to play with Durandal, Knockout, AMD and an arbitrary localization library (there are some new players to evaluate, by the way), I've added a couple of notes from my later experiences at the end.
On the singleton pattern
One problem with the singleton pattern here is that it's hard to configure per-view; indeed there are other parameters to the translations than their locale (counts for plural forms, context, variables, gender) and these may themselves be specific to certain contexts (e.g. views/view models).
By the way it's important that you don't do this yourself and instead rely on a localization library/framework (it can get really complex).  There are many questions on SO regarding these projects.
You can still use a singleton, but either way you're only halfway there.
On knockout binding handlers
One solution, explored by zewa666 in another answer, is to create a KO binding handler.  One could imagine this handler taking these parameters from the view, then using any localization library as backend.  More often than not, you need to change these parameters programmatically in the viewmodel (or elsewhere), which means you still need to expose a JS API.
If you're exposing such an API anyway, then you may use it to populate your view model and skip the binding handlers altogether.  However, they're still a nice shortcut for those strings that can be configured from the view directly.  Providing both methods is a good thing, but you probably can't do without the JS API.
Current Javascript APIs, document reloading
Most localization libraries and frameworks are pretty old-school, and many of them expect you to reload the entire page whenever the user changes the locale, sometimes even when translation parameters change, for various reasons.  Don't do it, it goes against everything a client-side web application stands for.  (SPA seems to be the cool term for it these days.)
The main reason is that otherwise you would need to track each DOM element that you need to retranslate every time the locale changes, and which elements to retranslate every time any of their parameters change.  This is very tedious to do manually.
Fortunately, that's exactly what data binders like knockout make very easy to do.  Indeed, the problem I just stated should remind you of what KO computed observables and KO data-bind attributes attempt to solve.
On the RequireJS i18n plugin
The plugin both uses the singleton pattern and expects you to reload the document. No-go for use with Durandal.
You can, but it's not efficient, and you may or may not uselessly run into problems depending on how complex your application state is.
Integration of knockout in localization libraries
Ideally, localization libraries would support knockout observables so that whenever you pass them an observable string to translate with observable parameters, the library gives you an observable translation back.  Intuitively, every time the locale, the string, or the parameters change, the library modifies the observable translation, and should they be bound to a view (or anything else), the view (or whatever else) is dynamically updated without requiring you to do anything explicitly.
If your localization library is extensible enough, you may write a plugin for it, or ask the developers to implement this feature, or wait for more modern libraries to appear.
I don't know of any right now, but my knowledge of the JS ecosystem is pretty limited.  Please do contribute to this answer if you can.
Real world solutions for today's software
Most current APIs are pretty straightforward;  take i18next for example.  Its t (translate) method takes a key for the string and an object containing the parameters.  With a tiny bit of cleverness, you can get away with it without extending it, using only glue code.
translate module
define(function (require) {
    var ko = require('knockout');
    var i18next = require('i18next');
    var locale = require('locale');

    return function (key, opts) {
        return ko.computed(function () {
            locale();
            var unwrapped = {};
            if (opts) {
                for (var optName in opts) {
                    if (opts.hasOwnProperty(optName)) {
                        var opt = opts[optName];
                        unwrapped[optName] = ko.isObservable(opt) ? opt() : opt;
                    }
                }
            }
            return i18next.t(key, unwrapped);
        });
    }
});

locale module
define(function (require) { return require('knockout').observable('en'); });

The translate module is a translation function that supports observable arguments and returns an observable (as per our requirements), and essentially wraps the i18next.t call.
The locale module is an observable object containing the current locale used globally throughout the application. We define the default value (English) here, you may of course retrieve it from the browser API, local storage, cookies, the URI, or any other mechanism.
i18next-specific note: AFAIK, the i18next.t API doesn't have the ability to take a specific locale per translation: it always uses the globally configured locale. Because of this, we must change this global setting by other means (see below) and place a dummy read to the locale observable in order to force knockout to add it as a dependency to the computed observable. Without it, the strings wouldn't be retranslated if we change the locale observable.
It would be better to be able to explicitly define dependencies for knockout computed observables by other means, but I don't know that knockout currently provides such an API either; see the relevant documentation. I also tried using an explicit subscription mechanism, but that wasn't satisfactory since I don't think it's currently possible to trigger a computed to re-run explicitly without changing one of its dependencies. If you drop the computed and use only manual subscription, you end up rewriting knockout itself (try it!), so I prefer to compromise with a computed observable and a dummy read. However bizarre that looks, it might just be the most elegant solution here. Don't forget to warn about the dragons in a comment.
The function is somewhat basic in that it only scans the first-level properties of the options object to determine if they are observable and if so unwraps them (no support for nested objects or arrays). Depending on the localization library you're using, it will make sense to unwrap certain options and not others. Hence, doing it properly would require you to mimic the underlying API in your wrapper.
I'm including this as a side note only because I haven't tested it, but you may want to use the knockout mapping plugin and its toJS method to unwrap your object, which looks like it might be a one-liner.
Here is how you can initialize i18next (most other libraries have a similar setup procedure), for example from your RequireJS data-main script (usually main.js) or your shell view model if you have one:
var ko = require('knockout');
var i18next = require('i18next');
var locale = require('locale');

i18next.init({
    lng: locale(),
    getAsync: false,
    resGetPath: 'app/locale/__ns__-__lng__.json',
});

locale.subscribe(function (value) {
    i18next.setLng(value, function () {});
});

This is where we change the global locale setting of the library when our locale observable changes. Usually, you'll bind the observable to a language selector; see the relevant documentation.
i18next-specific note: If you want to load the resources asynchronously, you will run in a little bit of trouble due to the asynchronous aspect of Durandal applications; indeed I don't see an obvious way to wrap the rest of the view models setup code in a callback to init, as it's outside of our control. Hence, translations will be called before initialization is finished. You can fix this by manually tracking whether the library is initialized, for example by setting a variable in the init callback (argument omitted here). I tested this and it works fine. For simplicity here though, resources are loaded synchronously.
i18next-specific note: The empty callback to setLng is an artifact from its old-school nature; the library expects you to always start retranslating strings after changing the language (most likely by scanning the DOM with jQuery) and hence the argument is required. In our case, everything is updated automatically, we don't have to do anything.
Finally, here's an example of how to use the translate function:
var _ = require('translate');

var n_foo = ko.observable(42);
var greeting = _('greeting');
var foo = _('foo', { count: n_foo });

You can expose these variables in your view models, they are simple knockout computed observables. Now, every time you change the locale or the parameters of a translation, the string will be retranslated. Since it's observable, all observers (e.g. your views) will be notified and updated.
var locale = require('locale');

locale('en_US');
n_foo(1);
...

No document reload necessary. No need to explicitly call the translate function anywhere. It just works.
Integration of localization libraries in knockout
You may attempt to make knockout plugins and extenders to add support for localization libraries (besides custom binding handlers), however I haven't explored the idea, so the value of this design is unknown to me. Again, feel free to contribute to this answer.
On Ecmascript 5 accessors
Since these accessors are carried with the objects properties everywhere they go, I suspect something like the knockout-es5 plugin or the Durandal observable plugin may be used to transparently pass observables to APIs that don't support knockout. However, you'd still need to wrap the call in a computed observable, so I'm not sure how much farther that gets us.
Yet again, this is not something I looked at a lot, contributions welcome.
On Knockout extenders
You can potentially leverage KO extenders to augment normal observables to translate them on the fly. While this sounds good in theory, I don't think it would actually serve any kind of purpose; you would still need to track every option you pass to the extender, most likely by manually subscribing to each of them and updating the target by calling the wrapped translation function.
If anything, that's merely an alternative syntax, not an alternative approach.
Conclusion
It feels like there is still a lot lacking, but with a 21-lines module I was able to add support for an arbitrary localization library to a standard Durandal application.  For an initial time investment, I guess it could be worse. The most difficult part is figuring it out, and I hope I've done a decent job at accelerating that process for you.
In fact, while doing it right may sound a little complicated (well, what I believe is the right way anyway), I'm pretty confident that techniques like these make things globally simpler, at least in comparison to all the trouble you'd get from trying to rebuild state consistently after a document reload or to manually tracking all translated strings without Knockout.  Also, it is definitely more efficient (UX can't be smoother): only the strings that need to be retranslated are retranslated and only when necessary.
Nov 2014 notes
After writing this post, we merged the i18next initialization code and the code from the translate module in a single AMD module.  This module had an interface that was intended to mimick the rest of the interface of the stock i18next AMD module (though we never got past the translate function), so that the "KO-ification" of the library would be transparent to the applications (except for the fact that it now recognized KO observables and took the locale observable singleton in its configuration, of course).  We even managed to reuse the same "i18next" AMD module name with some require.js paths trickery.
So, if you still want to do this integration work, you may rest assured that this is possible, and eventually it seemed like the most sensible solution to us.  Keeping the locale observable in a singleton module also turned out to be a good decision.
As for the translation function itself, unwrapping observables using the stock ko.toJS function was indeed far easier.
i18next.js (Knockout integration wrapper)
define(function (require) {
    'use strict';

    var ko = require('knockout');
    var i18next = require('i18next-actual');
    var locale = require('locale');
    var namespaces = require('tran-namespaces');
    var Mutex = require('komutex');

    var mutex = new Mutex();

    mutex.lock(function (unlock) {
        i18next.init({
            lng: locale(),
            getAsync: true,
            fallbackLng: 'en',
            resGetPath: 'app/locale/__lng__/__ns__.json',
            ns: {
                namespaces: namespaces,
                defaultNs: namespaces && namespaces[0],
            },
        }, unlock);
    });

    locale.subscribe(function (value) {
        mutex.lock(function (unlock) {
            i18next.setLng(value, unlock);
        });
    });

    var origFn = i18next.t;
    i18next.t = i18next.translate = function (key, opts) {
        return ko.computed(function () {
            return mutex.tryLockAuto(function () {
                locale();
                return origFn(key, opts && ko.toJS(opts));
            });
        });
    };

    return i18next;
});

require.js path trickery (OK, not that tricky)
requirejs.config({
    paths: {
        'i18next-actual': 'path/to/real/i18next.amd-x.y.z',
        'i18next': 'path/to/wrapper/above',
    }
});

The locale module is the same singleton presented above, the tran-namespaces module is another singleton that contains the list of i18next namespaces.  These singletons are extremely handy not only because they provide a very declarative way of configuring these things, but also because it allows the i18next wrapper (this module) to be entirely self-initialized.  In other words, user modules that require it will never have to call init.
Now, initialization takes time (might need to fetch some translation files), and as I already mentioned a year ago, we actually used the async interface (getAsync: true).  This means that a user module that calls translate might in fact not get the translation directly (if it asks for a translation before initialization is finished, or when switching locales).  Remember, in our implementation user modules can just start calling i18next.t immediately without waiting for a signal from the init callback explicitly;  they don't have to call it, and thus we don't even provide a wrapper for this function in our module.
How is this possible?  Well, to keep track of all this, we use a "Mutex" object that merely holds a boolean observable.  Whenever that mutex is "locked", it means we're initializing or changing locales, and translations shouldn't go through.  The state of that mutex is automatically tracked in the translate function by the KO computed observable function that represents the (future) translation and will thus be re-executed automatically (thanks to the magic of KO) when it changes to "unlocked", whereupon the real translate function can retry and do its work.
It's probably more difficult to explain than it is to actually understand (as you can see, the code above is not overly long), feel free to ask for clarifications.
Usage is very easy though;  just var i18next = require('i18next') in any module of your application, then call i18next.t away at any time.  Just like the initial translate function you may pass observable as arguments (which has the effect of retranslating that particular string automatically every time such an argument is changed) and it will return an observable string.  In fact, the function doesn't use this, so you may safely assign it to a convenient variable: var _ = i18next.t.
By now you might be looking up komutex on your favorite search engine.  Well, unless somebody had the same idea, you won't find anything, and I don't intend to publish that code as it is (I couldn't do that without losing all my credibility ;)).  The explanation above should contain all you need to know to implement the same kind of thing without this module, though it clutters the code with concerns I'm personally inclined to extract in dedicated components as I did here.  Toward the end, we weren't even 100% sure that the mutex abstraction was the right one, so even though it might look neat and simple, I advise that you put some thoughts into how to extract that code (or simply on whether to extract it or not).
More generally, I'd also advise you to seek other accounts of such integration work, as its unclear whether these ideas will age well (a year later, I still believe this "reactive" approach to localization/translation is absolutely the right one, but that's just me).  Maybe you'll even find more modern libraries that do what you need them to do out of the box.
In any case, it's highly unlikely that I'll revisit this post again.  Again, I hope this little(!) update is as useful as the initial post seems to be.
Have fun!


text:
Q: Encoding 2D List How can I encode 2D List here to send to the server, so that server can print the 2D List?
ERROR: AttributeError: 'list' object has no attribute 'encode'
CODE:
Client.py
from socket import *
serverName = "localhost"
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))

input = [
            [1, 0, 1, 1, 0],
            [1, 0, 0, 1, 0],
            [1, 1, 1, 0, 1]
        ]

clientSocket.send(input.encode())

clientSocket.close()

Server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)

print("The server is ready to receive!")

while True:
    connectionSocket, addr = serverSocket.accept()
    array = connectionSocket.recv(1024).decode()
    print(array)
    connectionSocket.close()

A: If you only want the peer to be able to print, or send back the 2D list, you can directly send a string representation:
clientSocket.send(str(input).encode())

If you want it to be able to process the data as a 2D list, you should serialize the list, for example with json:
clientSocket.send(json.dumps(input).encode())

Then you can retrieve the list with:
list2D = json.loads(connectionSocket.recv(1024))

A: the simplest way to do it is to use serialization like JSON.
Here is an example with your code, its convert your list into a JSON string and then to bytes before sending it:
Client.py
from socket import *
import json
serverName = "localhost"
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))

input = [
            [1, 0, 1, 1, 0],
            [1, 0, 0, 1, 0],
            [1, 1, 1, 0, 1]
        ]

clientSocket.send(json.dumps(input).encode('utf8'))

clientSocket.close()

Server.py
from socket import *
import json
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)

print("The server is ready to receive!")

while True:
    connectionSocket, addr = serverSocket.accept()
    array = json.loads(connectionSocket.recv(1024).decode('utf8'))
    print(array)
    connectionSocket.close()


text:
Q: Enumerated types in SQL Server 2008? Is there some kind of mechanism in SQL Server to allow Enumerated type like functionality?
For example, if I have a column Called "UpdateStatus" it usually gets setup with single letter values like so:

*

*D

*X

*U

*I

This could equate to a lot of things.  That leads to confusion.  The alternative is to have it be a string column like this:

*

*Downloaded

*Deleted

*Updated

*Initialized

But that has its own problems.  Eventually someone is going to write something like this: where UpdateStatus = 'Initalized' (spelled wrong).  Plus I hear that keying off of strings is not all that performant.
So, is there any kind of enumerated type for SQL Server that can help out with this?  Basically I am looking for compile time checking that a value being compared (ie "Initialized") is part of a list of values.
I am using SQL Server 2008.

A: Besides lookup tables (FKs), in simple cases, you can use check constraints:
CREATE TABLE my_table (
    UpdateStatus VARCHAR2(11)
      CHECK( UpdateStatus IN ('Downloaded', 'Deleted', 'Updated', 'Initialized'))
)

A: Why not have lookup table that contains the code and description.  Creating a foreign key to this lookup table will result in only valid codes being used.

A: The only way that I've seen this done is by using a UDF to evaluate whether or not the enum's string representation is valid. It's slow, it's painful, and usually not worth it, but at least you have a way to fail loudly instead of silently.
And remember, you can't RAISERROR in a UDF so you have to cause an intentially cause an error, and log separately.
Ultimately, at the moment, the 'perfect' solution to the problem would be to approach from the other side -- you can achieve this mentality with a code-first ORMs, which would allow you to use native enums in your code, and the corresponding SQL lookups will be created properly in migration.
Here's to hoping we get enums soon, we're feeling a little left out.


text:
Q: Ubuntu 16.04 - How to make an encrypted swap after install I have enabled full disk encryption on Ubuntu 16.04 by following this guide. But I have not yet created a swap partition for it. I would like to setup an encrypted swap partition, what I have found online is the following (Please correct me if I am wrong) -:
Steps taken from here.
First format the swap partition as an encrypted swap, but then here how do I link it to my original passphrase for booting the system ? I don't want to have a passphrase for unlocking the system and then one for the swap partition separately. Also I would like to use the same encryption key used for all the other LUKS partition.
sudo cryptsetup luksFormat --cipher aes-xts-plain64 --verify-passphrase --key-size 256 /dev/sdXN

Second I think is adding to the list of encrypted partitions (I am not sure what the function of luksOpen is yet,)
sudo cryptsetup luksOpen /dev/sdXN cryptswap1

Third is marking the partition as swap-:
sudo mkswap /dev/mapper/cryptswap1

And next steps are as in the tutorial.
Now before I try anything I want to know is this the correct way of setting up an encrypted swap for 16.04 ? Also I would like them all to be in the same setup if possible, like if I could configure the encrypted swap at install time, what would be great.
Also there is another set of instructions over here, but that brings up the same questions that how do I use the same passphrase and encryption scheme as the other partitions. Also as given in the comments the -v1 option is causing problems.


text:
Q: How to apply images conditionally using entries and categories? Using version 2.5.3 of ExpressionEngine, I have a list of products displayed by category, but I need the premium products among this list being featured with a small star image. How do you call conditionally this little stars besides the {title}?
At the moment this code shows stars for all products and that is not ideal.

{exp:channel:entries channel="product" orderby="title" sort="asc" category="2&6" dynamic="no"}

{title}

{/exp:channel:entries}

I need your help, please.

A: Best to set up a new checkbox field named "is_premium" with the value set to "y".
Next, edit each premium product entry and check the box and save.
Finally, in your template use this conditional.
{if is_premium == "y"}add star code{/if}

A: I like the approach shown in the answer posted by @MediaGirl and have used it many times.
An alternative approach is to handle it with a custom status rather than a custom field, if only to have the ability on the main edit screen to quickly and easily see and sort the list by "premium" (Zenbu could add the custom field to the edit screen, of course). The conditional would be similar, and of course the entries loop would need to have the status param of "open|premium".


text:
Q: ChainableTemporaryCredentials getPromise and Missing credentials in config, if using AWS_CONFIG_FILE I have an node application deployed in GCP.
The application includes code to access ressources in AWS-cloud.
For this purpose it uses the aws-SDK with ChainableTemporaryCredentials.
The relevant code lines are...
      const credentials = new ChainableTemporaryCredentials({
        params: {
          RoleArn: `arn:aws:iam::${this.accountId}:role/${this.targetRoleName}`,
          RoleSessionName: this.targetRoleName,
        },
        masterCredentials: new WebIdentityCredentials({
          RoleArn: `arn:aws:iam::${this.proxyAccountId}:role/${this.proxyRoleName}`,
          RoleSessionName: this.proxyRoleName,
          WebIdentityToken: token,
        }),
      })

      await credentials.getPromise()

The WebIdentityToken was received from google and looks good.
At AWS-side I created an proxy-role (the line from masterCredentials RoleArn).
However at runtime I get the error:
Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
I do not understand this error. Because my application runs in GCP and I use temporary credentials I do not understand why I should use aws-credentials in form of an credentials file or environment variables like AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY. I thought the idea to use ChainableTemporaryCredentials is NOT to have direct aws-credentials. Right?
You can see the public code at:
https://github.com/cloud-carbon-footprint/cloud-carbon-footprint/blob/trunk/packages/aws/src/application/GCPCredentials.ts
and documentation regarding env-variables at:
https://www.cloudcarbonfootprint.org/docs/configurations-glossary/
Any help which leads to understanding of this error message is welcome.
Thomas

A: Solved it. "Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1 was totally misleading." In reality it was a problem with the field-names in the GCP-JWT-token und the policy in aws. See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_aud


text:
Q: Most efficient way to sort a 2d array with sorted rows into 1d sorted array Given a 2d array (a matrix) with n rows and k columns, with it's rows sorted, columns unspecified, what would be the most efficient algorithm to sort it?
For exmaple:
Input (n = 3 ; k = 4):
1 5 8 10
3 4 5 6
2 3 3 9

Output:
1 2 3 3 3 4 5 5 6 8 9 10

This is purely algorithmic question, so no specific .sort() methods of some languages help me, as I'm actually intereseted in the runtime complexity.
What I had in mind would be an algorithm as follows:
- Build a Binary Search tree with n nodes. Each node contains:
  ID - of the row it refers to;
  Value - The number at the "head" of the row.
- Sort the tree where the sorting key are the values.
- Find the lowest valued node.
- Do while the tree has a root:
  - Take the lowest value and append it to the new array.
  - Update the node's value to the next one in the same row.
  - If the updated value is null, delete that node.
    - else re-sort the tree.
  - If the node moved, the first node it swapped with will be the next lowest
    - else, if it didn't move, it's the new lowest.

If I'm not mistaken the runtime complexity is O(n*k * log n), Since I'm sorting the tree n*k times, which takes O(log n) time, and process of finding the next lowest is O(1).
If my complexity calculation is wrong, please let me know.
Is there any way more efficient than this?

A: You basically have n sorted lists, each of size k. You need a generalization of merge-sort, which is the k-way merge.
The idea is to keep a min-heap, that contains the smallest element from each list.
Now, iteratively pop the min of the heap. Let this number be x, and say it was taken from row i. Now, append x to the result list, and add to the min heap the next element in row i (if such element exists)
Repeat until all elements are exhausted.
Complexity is O(n*k*logn), which is pretty efficient considering you are sorting n*k elements, and need to traverse all of them. The constants for using a binary heap are pretty good.
Note that this is often refered as external sort (or to be exact a close variant to external sort's second part).
This is very similar to the algorithm you are suggesting, but will probably run much faster (with better constants) due to the usage of heap rather than the less efficient tree.
Also note, that if you use a 'regular' binary tree, you get complexity of O(n^2k), since there is no guarantee on the height of the tree. You need a self balancing binary search tree in order to get O(nklogn) run time.

A: This can be done using Sorted Merge which will take o(rows*cols) time i.e. total number of elements and o(rows) space complexity.
The java code for this problem is as below: (Consider rows = 3 and cols = 4)
    for(int i=0;i<3;i++)
    {
        index[i] =0;
    }

    int count=0;
    int a;
    int b;
    int c;

    while(count<(ROWS*COLS))
    {
        int smallest;
        if(index[0]>=COLS)
            a= Integer.MAX_VALUE;
        else
            a= matrix[0][index[0]];
        if(index[1]>=COLS)
            b = Integer.MAX_VALUE;
        else
            b = matrix[1][index[1]];
        if(index[2]>=COLS)
            c = Integer.MAX_VALUE;
        else
            c = matrix[2][index[2]];
        if(a<=b && a<=c){
            // a is smallest
            smallest = a;
            index[0] = index[0] +1;

        }else if(b<=c && b<=a){
            //b is smallest
            smallest = b;
            index[1] = index[1] + 1;
        }else{
            //c is smallest
            smallest = c;
            index[2] = index[2] + 1;
        }
        System.out.print(smallest + ", ");
        count++;
    }


text:
Q: Send mail to third person based on order meta data once order is placed in WooCommerce we have used Checkout Field Editor for WooCommerce where we have created extra email field and we tried to send mail to the email that email field value after every new order and here is the code:
function custom_email_for_gift( $order_id ) {
    global $wpdb;

    $order = wc_get_order( $order_id );
     //this is the field we were talking about
     $gift_to_person_email =$wpdb->get_var(
        "SELECT meta_value FROM wp_postmeta WHERE post_id=$order_id AND meta_key='gift_to_person_email'"
    ) ?: '';

    $gift_to_organization_email =$mailfororginazation=$wpdb->get_var(
        "SELECT meta_value FROM wp_postmeta WHERE post_id=$order_id AND meta_key='gift_to_organization_email'"
    ) ?: '';

    $name = $order->get_billing_first_name();

    if($gift_to_person_email){
        $to = $gift_to_person_email;
    }elseif($gift_to_organization_email){
        $to = $gift_to_organization_email;
    }

    if($to){
        $subject = 'The subject';
        $headers = array('Content-Type: text/html; charset=UTF-8');
       $email_content = 'Hello';
        wp_mail( $to, $subject, $email_content, $headers );
    }else{
        $to = 'test@gmail.com';
        $subject = 'Email Failed';
        $email_content = "Failed";
        $email_content .= $gift_to_person_email;
        $email_content .= $gift_to_organization_email;
        $headers = array('Content-Type: text/html; charset=UTF-8');
        wp_mail( $to, $subject, $email_content, $headers );
    }
}
// add the action
add_action( 'woocommerce_new_order', 'custom_email_for_gift',11);

We have tested for woocommerce_new_order and woocommerce_thankyou hook and in both hook it is not working and not sending mail when used thankyou hook and sending failed mail when using woocommerce_new_order and we have checked in database and the email field value is there but also not sending mail

A: Custom SQL queries are not needed for the meta data, you can use get_meta
So you get:
function action_woocommerce_new_order( $order_id ) {
    // Getting an instance of WC_Order object
    $order = wc_get_order( $order_id );

    // Is a WC_Order
    if ( is_a( $order, 'WC_Order' ) ) {
        // Get meta
        $gift_to_person_email = $order->get_meta( 'gift_to_person_email' );
        $gift_to_organization_email = $order->get_meta( 'gift_to_organization_email' );

        // Initialize
        $to = '';

        // NOT empty
        if( ! empty( $gift_to_person_email ) ) {
            $to = $gift_to_person_email;
        } elseif( ! empty( $gift_to_organization_email ) ) {
            $to = $gift_to_organization_email;
        }

        // Get billing first name
        $name = $order->get_billing_first_name();

        // NOT empty
        if( ! empty ( $to ) ) {
            $to = $to;
            $subject = 'The subject';
            $email_content = 'hello';
            $headers = array( 'Content-Type: text/html; charset=UTF-8' );

            wp_mail( $to, $subject, $email_content, $headers );
        } else {
            $to = 'test@gmail.com';
            $subject = 'Email Failed';
            $email_content = 'Failed';
            $email_content .= $gift_to_person_email;
            $email_content .= $gift_to_organization_email;
            $headers = array( 'Content-Type: text/html; charset=UTF-8' );

            wp_mail( $to, $subject, $email_content, $headers );
        }
    }
}
// Add the action
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );


text:
Q: How can I implement the use of two textboxes for my calculator? The purpose of my assignment is to create a calculator that uses number inputs from two textboxes. The calculator works when only dealing with a single textbox(boxequation1) but I need it to accept another input from the other textbox(boxequation2). Is there any way to input a number into boxequation1, select an operation, input a number into boxquation2, and then compute the result?
    Public Class Form1
Private Sub ButtonClickMethod(sender As Object, e As EventArgs) Handles num0.Click, num1.Click, num2.Click, num3.Click, num4.Click, num5.Click, num6.Click, num7.Click, num8.Click, num9.Click, opdivision.Click, opmultiply.Click, opdecimal.Click, opclear.Click, opminus.Click, opadd.Click, opequal.Click
    Dim button As Button = CType(sender, Button)
    If button.Name = "num1" Then
        boxequation1.Text = boxequation1.Text + "1"
    End If
    If button.Name = "num2" Then
        boxequation1.Text = boxequation1.Text + "2"
    End If
    If button.Name = "num3" Then
        boxequation1.Text = boxequation1.Text + "3"
    End If
    If button.Name = "num4" Then
        boxequation1.Text = boxequation1.Text + "4"
    End If
    If button.Name = "num5" Then
        boxequation1.Text = boxequation1.Text + "5"
    End If
    If button.Name = "num6" Then
        boxequation1.Text = boxequation1.Text + "6"
    End If
    If button.Name = "num7" Then
        boxequation1.Text = boxequation1.Text + "7"
    End If
    If button.Name = "num8" Then
        boxequation1.Text = boxequation1.Text + "8"
    End If
    If button.Name = "num9" Then
        boxequation1.Text = boxequation1.Text + "9"
    End If
    If button.Name = "num0" Then
        boxequation1.Text = boxequation1.Text + "0"
    End If
    If button.Name = "opdecimal" Then
        boxequation1.Text = boxequation1.Text + "."
    End If
    If button.Name = "opequal" Then
        Dim equation1 As String = boxequation1.Text
        Dim equation2 As String = boxequation2.Text
        Dim result = New DataTable().Compute(equation1, Nothing)

        boxresult.Text = result
    End If
    If button.Name = "opminus" Then
        boxequation1.Text = boxequation1.Text + "-"
        boxoperator.Text = boxoperator.Text + "-"
    End If
    If button.Name = "opmultiply" Then
        boxequation1.Text = boxequation1.Text + "*"
        boxoperator.Text = boxoperator.Text + "x"
    End If
    If button.Name = "opdivision" Then
        boxequation1.Text = boxequation1.Text + "/"
        boxoperator.Text = boxoperator.Text + "÷"
    End If
    If button.Name = "opadd" Then
        boxequation1.Text = boxequation1.Text + "+"
        boxoperator.Text = boxoperator.Text + "+"
    End If
    If button.Name = "opclear" Then
        boxequation1.Clear()
        boxoperator.Clear()
        boxresult.Clear()
    End If
End Sub
Private Sub opbackspace_Click(sender As Object, e As EventArgs) Handles opbackspace.Click
    boxequation1.Text = boxequation1.Text.Remove(boxequation1.Text.Count - 1)
End Sub

End Class

A: I'm having a lot of fun with your homework.
Now... I'm not sure how I should do to help you. I initially wanted to code it and obfuscate parts of the code so you could check at what's clear and understand the rest by yourself, but on the other hand I have no idea if that would really help. I though that maybe you would do better with more explanations.
So I re-coded the whole thing, loosely based on what you posted earlier.
I heavily commented my work so you will be able to understand why I did things that war, but really you can and should ask me questions about everything which isn't cristal clear in this.
And, once you feel more confident about it, you should scrap my work and code it again, but from scratch this time. You're doing this to learn, after all!
Here what it looks like:
.-.-.-.-.-.-.-.-.
Here's a very cusomized New() Sub. It's not how I coded it; I needed only the 3 first lines of this monstruosity, but I wanted you to see the rest of it because that's how I set up my controls in the designer.
You should set up your controls names, texts and tags in the designer, really. This part really is here only because it was easier to show you these settings this way.
Private Sub New()
    InitializeComponent()

    _currentTextBox = Number1TextBox
    _locked = False
    ResultsTextBox.TextAlign = HorizontalAlignment.Center
    ResultsTextBox.Text = "SUPER DUPER CALCULATOR"
    For Each textBox As System.Windows.Forms.TextBox In {ResultsTextBox, Number1TextBox, Number2TextBox}
        'This prevent the user from writing in your textboxes instead of using the buttons.
        textBox.ReadOnly = True
    Next

    'I used the .Text and .Tag properties to make the code easier to manage. Observe:
    num0Button.Text = "0"
    num1Button.Text = "1"
    num2Button.Text = "2"
    num3Button.Text = "3"
    '...
    num9Button.Text = "9"
    opAddButton.Text = "+"
    opMinusButton.Text = "-"
    opMultiplyButton.Text = "x"
    opDivideButton.Text = "÷"
    For Each button As Button In {num1Button, num2Button, num3Button, num4Button, num5Button, num6Button, num7Button, num8Button, num9Button}
        button.Tag = "number"
    Next
    For Each button As Button In {opAddButton, opMinusButton, opMultiplyButton, opDivideButton}
        button.Tag = "operation"
    Next
    num0Button.Tag = "numberZero"
    opDecimalButton.Tag = "decimal"
    opBackspaceButton.Tag = "backspace"
    opEqualButton.Tag = "equal"
End Sub

And now for the real code: the subs that your class will need and use:
'Class variables are useful to remember informations which will be useful at several unrelated places.
'_currentTextBox is a pointer to the TextBox which is currently being filled
Private _currentTextBox As System.Windows.Forms.TextBox = Number1TextBox
'_Llocked will prevent the user from messing with the calculator after he pressed "equal"
Private _locked As Boolean = False

'I didn't like this idea but I went with it since it was your initial method.
'Notice how shoter this iteration of your idea is. Strive to shorten your code while making your variable names much easier to read.
'For real, make sure your variables are aptly names. Every control should be identified as such (the button num0 should be names num0Button for example)
'Code is hard enough to read without making it sibylline
Private Sub ButtonClickMethod(sender As Object, e As EventArgs) Handles num0Button.Click, num1Button.Click, num2Button.Click, num3Button.Click, num4Button.Click, num5Button.Click, num6Button.Click, num7Button.Click, num8Button.Click, num9Button.Click, opDivideButton.Click, opMultiplyButton.Click, opDecimalButton.Click, opClearButton.Click, opMinusButton.Click, opAddButton.Click, opEqualButton.Click, opBackspaceButton.Click
    'DirectCast is more strick than CType. For this operation, it doesn't really make a difference, but that's the one you want anyway.
    Dim button As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)

    'The boolean _locked prevent the user from messing with your beautiful calculator.
    If Not _locked Then
        'This is where the .Tag property save lifes. All numbers (but zero) are "number" now. BAM!
        Select Case button.Tag.ToString
            Case "number"
                _currentTextBox.Text += button.Text
            Case "numberZero"
                'You don't want your clever teacher to try to divide by zero, or create a number with 5 zeros before the actual number.
                'This is how you can do this.
                If _currentTextBox.Text.Length > 0 Then
                    _currentTextBox.Text += button.Text
                End If
            Case "decimal"
                If _currentTextBox.Text.Length > 0 AndAlso Not _currentTextBox.Text.Contains(".") Then
                    _currentTextBox.Text += button.Text
                End If
            Case "operation"
                ResetOperationTextBoxes()
                'here's a nifty visual cue about which operation has been selected. It's not really important.
                button.BackColor = Color.LightSalmon
                'This label will be used to Calculate() the operation. It's important!
                OpLabel.Text = button.Text
            Case "backspace"
                If _currentTextBox.Text.Length > 0 Then
                    _currentTextBox.Text = _currentTextBox.Text.Substring(0, _currentTextBox.Text.Length - 1)
                End If
            Case "equal"
                'I could have put the code here instead of making another sub, but I didn't.
                'There are two valid reasons for this.
                '1- This code might be useful on it's own later: maybe something else will Calculate() or LockCalculator or ResetCalculator later.
                '2- try to avoid blobs of code. A big and complex sub is easier to understand when it's divided between several clean and clear smaller subs.
                '   (of course, you cannot always subdivise Subs. Use common sense)
                Calculate()
        End Select
    End If

    'This check is all alone because I want it to work even if the calculator is locked.
    If button.Tag.ToString = "clear" Then
        ResetCalculator()
    End If
End Sub

Private Sub Calculate()
    'Always make checks to make sure that things are going the way you think they should be going.
    'for example, here I want to have 2 numbers and an operation, er else I'll just ignore this click.
    If Number1TextBox.Text.Length > 0 AndAlso Number2TextBox.Text.Length > 0 And OpLabel.Text <> "?" Then
        'If the user could mess with the textboxes, i would have to make further checks to avoid crashes, but I already force the user to use only numbers se we're cool.
        Dim number1 As Double = Convert.ToDouble(Number1TextBox.Text)
        Dim number2 As Double = Convert.ToDouble(Number2TextBox.Text)
        Dim result As Double

        Select Case OpLabel.Text
            Case "+"
                result = number1 + number2
            Case "-"
                result = number1 - number2
            Case "x"
                result = number1 * number2
            Case "÷"
                result = number1 / number2
        End Select

        ResultsTextBox.TextAlign = HorizontalAlignment.Right
        ResultsTextBox.Text = result.ToString
        LockCalculator(True)
    End If
End Sub

'By using a boolean to signify to this Sub if I want to lock or unlock things, I make it easier to automatize this operation (and I have only one Sub instead of two).
Private Sub LockCalculator(ByVal isLocked As Boolean)
    _locked = isLocked
    'I'm kinda cheating here: I put the calculator inside a GroupBox just so I could be lazier and do this.
    'Being lazy is great for a coder, as long as you think ahead (and avoid being a nuisance to yourself when you'll come back to this code and weep).
    For Each control As System.Windows.Forms.Control In CalculatorGroupBox.Controls
        control.Enabled = Not isLocked
    Next
    'Except that I want this button to always be available, so I enable it. This operation wouldn't be necessary if isLocked is True, but checking for that is longer than just doing it.
    opClearButton.Enabled = True
End Sub

Private Sub ResetCalculator()
    ResetNumberTextBoxes()
    ResetOperationTextBoxes()
    LockCalculator(False)
    _currentTextBox = Number1TextBox
End Sub

Private Sub ResetNumberTextBoxes()
    For Each textBox As System.Windows.Forms.TextBox In {Number1TextBox, Number2TextBox}
        textBox.Text = ""
    Next
    'Mea Culpa: I shouldn't had done a For Each for 2 elements like that. I did it anyway. Please don't call the Fun Police on me.
    'Also, you can now guess that using For Each loops to set up controls is a work method I like. Some don't like that.
    'There is about as many ways to code something as there are coders. You have to find your own, sure, but then you'll get hired somewhere
    'and they will absolutely hate everything that you do that isn't done the way they like it. And they will be right. On a big project where
    'several coders works, at the same time and for month and years, you have to find a common ground or else the code will become a nightmare
    'to understand and maintain. Trust me: being able to adapt quickly to other's work methodology is a GREAT skill in this field of work.

    ResultsTextBox.TextAlign = HorizontalAlignment.Center
    ResultsTextBox.Text = "SUPER DUPER CALCULATOR"
End Sub

Private Sub ResetOperationTextBoxes()
    For Each button As System.Windows.Forms.Button In {opAddButton, opMinusButton, opMultiplyButton, opDivideButton}
        button.BackColor = DefaultBackColor
    Next
    OpLabel.Text = "?"
End Sub

'This sub is great. It uses the _currentTextBox as a pointer. Maybe you're not familiar with pointers, I don't know. The short explanation is this:
'A pointer is like a phone number. You can give your number to several people without "losing" it. And if they call you and tell you something, they
'are all speaking to the same person.
'_currentTextBox is a pointer which can point toward Number1TextBox or Number2TextBox.
'This Event makes it so when the user click on Number1TextBox or Number2TextBox, the pointer updates it's "phone number" to the right box,
'so later when we'll write we'll write in the last one which was clicked on.
Private Sub NumberTextBoxes_Click(sender As Object, e As EventArgs) Handles Number1TextBox.Click, Number2TextBox.Click
    _currentTextBox = DirectCast(sender, System.Windows.Forms.TextBox)
End Sub

Here you go. I hope that you'll have as much fun with coding as I did!
Before I go to sleep now, here's a few things that I think that you should make an effort to improve on:
1  Name your controls with really, really obvious names. Nobody care that the names are long, we all use the intelliSense anyway. But anything that we cannot guess at a glance is not clear enough!
2  Same thing with your variables. Same for everything which has a name, in fact. If you show your work to a teammate and he's not able to guess which control you're speaking about just by it's name, it's not clear enough!
3  The rest you will learn as you persevere through understanding your friend, the computer.
4  You should turn on Explicit and Strict mode. It'll help you understand the type you're working with and how they interact. It'll reduce dramatically the risk of awful manipulations. In fact, as though the more experience a coder has, the less he'll need these options, the more experienced a coder is, the more likely he'll be to have those two little lines of code at the beginning of all his works...
Here's how I begin every page of VB code at home:
.-.-.-.-.-.-.-.-.
4  Ask questions! To me, to classmates, to teachers! Ask questions to everything that moves!
Good luck!


text:
Q: Add external data source In Storm I am new to Apache Storm. I have currently done word-count problem. Currently my data source (file containing words) is in my local system. But now i need this file to be in external system. i.e. if i tell ip of external system and path to file, then is there way that my application will get data from that file (remotely located)?

A: One option is to feed your file to MongoDB and let your spout pull the file from MongoDB.  Have a look at Storm Mongo. But please keep in mind the size of your file.    You don't want to transfer huge files as 'tuples'.