text:
Q: Will_filter gem generate error I get the error below when trying to install the will_filter gem, running the following command: rails generate will_filter
C:\Sites\eyesproject>rails generate will_filter
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action
_dispatch/routing/mapper.rb:191:in `normalize_conditions!': You should not use t
he `match` method in your router without specifying an HTTP method. (RuntimeErro
r)
If you want to expose your action to both GET and POST, add `via: [:get, :post]`
 option.
If you want to expose your action to GET, use `get` in the router:
  Instead of: match "controller#action"
  Do: get "controller#action"
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:67:in `initialize'
        from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0
.0/lib/action_dispatch/routing/mapper.rb:1438:in `new'

my routes.rb:
Eyesproject::Application.routes.draw do
  resources :project_details

  resources :welcomes

get "sessions/new"
  get "sign_up" => "users#new", :as => "sign_up"
  root 'welcome#index'
  get "welcome/index"

end

Any ideas on this?


text:
Q: SQL DML SCRIPTS For a given period (bounded by two given dates inclusive), say 01 December 2002 to 31 July 2003,
find the set of the people who have at least one EZ link card issued within the specified period. For
EACH person in the set, list the (i) Owner NRIC, (ii) the total number of his/her cards issued during
the period, and (iii) total number of card replacements (till current date) that have been made by the
owner for only those cards that were issued during the given period. List your results in ascending
order of Owner NRIC.
create table card
(
CardID  int not null primary key,
OwnerNRIC   char(9),
IssuedDcardate  date,
StoredValue decimal (5,2),
OldCardID   int,
constraint card_fk foreign key (OldCardID) references card(CardID)
);

As above is my card table.
This is my attempt at it but i was pretty lost.
 Select distinct(ownerNRIC) as NRIC,count(*) as Total Crads Issued during Period
From card
Where issuedDate between '2002-12-01' and '2003-7-31' group by ownerNRIC;

A: I'm assuming a card replacement results in a non-null OldCardId.  If OldCardId is NULL, then this was not a card replacement.  Take advantage of the way COUNT(expr) ignores rows where expr is NULL.
SELECT ownerNRIC AS NRIC,
  COUNT(*) AS `Total Cards Issued During Period`,
  COUNT(OldCardID) AS `Card Replacements During Period`
FROM card
WHERE issuedDate BETWEEN '2002-12-01' AND '2003-7-31'
GROUP BY ownerNRIC;

You were using DISTINCT incorrectly.  It's not a function, and it's unnecessary anyway because ownerNRIC was your GROUP BY column.

total number of card replacements (till current date) that have been made by the owner for only those cards that were issued during the given period

This requirement is not clear.  Do you mean the old card was issued during the given period, and the new card was issued anytime up to the current date?  If so, the query above won't give you that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: create piramid when click a button i want to create a piramid from for loop.
my current result is like this

i want to be like this

<button id="piramid" onclick="piramid()">test</button>

heres the code
https://jsfiddle.net/k22bf4o4/
how to loop so the result will become like the last image?
thank  you for your time

A: The previous commenters are right that you should not post your homework on StackOverflow. That said, it's a fun excercise that I wanted to do for myself.
For the numbers, I see now that the numbers originate from pyramids of two rows high, that are turned upside down. E.g. take the third row from the top: 1 + 2 = 3 where the 3 will be the top of the upside down pyramid with base row 1 and 2 (the row above the row with 3). Once you see that, it's up to you or somebody else on SO to write code for it.
HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Pyramid</title>

pyramid.js
let blockWidth = 20,
    blockHeight = 20,
    blockCountBaseRow = 10,
    blockOffset = blockWidth / 2;
let drawSurfaceWidth = blockWidth * blockCountBaseRow,
    drawSurfaceHeight = blockHeight * blockCountBaseRow,
    drawSurfaceCenter = drawSurfaceWidth / 2;

createDrawingSurface();
drawPyramid();

function createDrawingSurface() {
    let body = document.getElementsByTagName('body').item(0);
    body.innerHTML += '
' +
        '
';
}

function drawPyramid() {
    for (let row = 1; row < blockCountBaseRow + 1; row++) {
        let left = calculateLeftFirstBlock(row);
        let top = calculateTop(row);
        for (let j = 1; j < row + 1; j++) {
            addBlock(left, top);
            left += blockWidth;
        }
    }
}

function addBlock(left, top) {
    let drawingSurface = document.getElementById("drawingSurface");
    drawingSurface.innerHTML += '
' +
        '
';
}

function calculateLeftFirstBlock(row) {
    return drawSurfaceCenter - blockOffset * row;
}

function calculateTop(row) {
    return (row - 1) * blockHeight;
}


text:
Q: Mount/dismount database for migration I'm mirgrating from one domain to another.
Finally managed to get the new sharepoint version to match (infact, its actually a little newer than the original now!).
I have exported the databases shown when i ran Get-SPContentDatabase and I have them in .bak format.
I tried importing at the other end, starting with WSS_Content, however there is already a WSS_Content database in SQL. how would one go about restoring these databases?
Also, once I have the databases in the new servers SQL, is that the time when I need to start using STSADM to remove the old permissions or are there other steps involved?
Many thanks in advance

A: Reason why you have the same content DB name on both farm is, You are using the Default Name for the Content DB when provision a new web application.
Now you have two options.

*

*On the destination Farm, detach the WSS-Content db from the web application then wither rename it or delete it( if you are not using it). After that restore the Content db then attach it to the web app.

*Restore the content DB with different Name( this will not change the Content or functionality of DB). After restoring to different name then attach it to the Web Application.


text:
Q: Filtering the Grid in Magento I have made a custom grid in magento that displays saved video urls and its working. But i want to show only records where the urlid is for example 3 . Here is my _prepareCollection function
protected function _prepareCollection()
{
    // Get and set the collection for the grid
    $collection = Mage::getResourceModel('drecomm_productvideo/video_collection');
    //what should i put in here, addFieldtoSelect?
    $this->setCollection($collection);
    return parent::_prepareCollection();
}

my grid extends from Mage_Adminhtml_Block_Widget_Grid and there is no addFieldToFilter function in that class.

A: First of all, if you want to create a permanent filter for your collection (meaning that you will not be able to remove it from your grid view) you should use addFieldToFilter to your collection object. This method is not a part of grid class, it's the part of collection class.
$collection = Mage::getResourceModel('drecomm_productvideo/video_collection')
    ->addFieldToFilter('urlid', 3);

Now if you want to just add a default filter for you collection (meaning that it will be applied from the start, but you'll be able to reset it and see all entries), you should use setDefaultFilter() method of your grid block.
protected function _construct()
{
    parent::_construct();

    //... your code
    $this->setDefaultFilter(array('urlid' => 3));
}


text:
Q: disable spurious "warning: left shift count >= width of type" I'm getting a spurious "warning: left shift count >= width of type" when compiling some template code with gcc:
template <int N> class bitval {
unsigned long  val;
#pragma GCC diagnostic ignored "-Wall"
    const bitval &check() {
        if (N < sizeof(unsigned long) * CHAR_BIT && val >= (1UL << N)) {
            std::clog << val << " out of range for " << N << " bits in " << std::endl;
            val &= (1UL << N) - 1; }
        return *this; }
#pragma GCC diagnostic pop
};

The problem being that when it is instantiated with N == 64, it gives the warning.
Now the warning is completely spurious, as the code checks for N being large enough that no check/mask is needed, so when N is 64, the shifts will never happen.  But gcc warns anyways.  So I'm trying to disable the warning, but I can't figure out the needed #pragma magic to shut it up...

A: Tag dispatching to the rescue:
const bitval& check() {
  constexpr bool enough_bits = (N < sizeof(unsigned long) * CHAR_BIT);
  using enough_bits_t = std::integral_constant<bool, enough_bits>;
  return check( enough_bits_t{} );
}
const bitval& check(std::false_type /*enough bits*/) {
  return *this;
}
const bitval& check(std::true_type /*enough bits*/) {
  if (val >= (1UL << N)) {
    std::clog << val << " out of range for " << N << " bits in \n";
    val &= (1UL << N) - 1;
  }
  return *this;
}

The decision (are there enough bits) is a compile-time constant, so I calculate it as one.
I then build a type (std::true_type or std::false_type) based off that decision, and dispatch to one of two different overloads.
So the code where N is too big to be shifted that far is never instantiated, and hence no warning.  If there is a logic error in the decision, and the code is instantiated, I get a compiler warning instead of silence (had you managed to disable the warning, and you had a logic error, you'd get silent UB).


text:
Q: using security function on tradingview, how to make the gaps smooth? I am trying to plot multiple timeframe EMA on 15 min chart, this is my code.

//@version=5
indicator(title='higher tf', overlay=true)

// 4 hr

show_4h = input(title='Show 4 hour', defval=true, group = "4 HOUR")

show_ema20_4 = input(title='Show 20 EMA of 4 hour', defval=true, group = "4 HOUR")
ema20_4_period = input(title='20 EMA of 4 hour Period', defval=20, group = "4 HOUR")

show_ema50_4 = input(title='Show 50 EMA of 4 hour', defval=true, group = "4 HOUR")
ema50_4_period = input(title='50 EMA of 4 hour Period', defval=50, group = "4 HOUR")

show_ema100_4 = input(title='Show 100 EMA of 4 hour', defval=true, group = "4 HOUR")
ema100_4_period = input(title='100 EMA of 4 hour Period', defval=100, group = "4 HOUR")

show_ema200_4 = input(title='Show 200 EMA of 4 hour', defval=true, group = "4 HOUR")
ema200_4_period = input(title='200 EMA of 4 hour Period', defval=200, group = "4 HOUR")

ema20_4 = request.security(syminfo.tickerid, '360', ta.ema(close, ema20_4_period),lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema50_4 = request.security(syminfo.tickerid, '360', ta.ema(close, ema50_4_period),lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema100_4 = request.security(syminfo.tickerid, '360', ta.ema(close, ema100_4_period), lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema200_4 = request.security(syminfo.tickerid, '360', ta.ema(close, ema200_4_period), lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)

plot(show_4h ? show_ema20_4 ? ema20_4 : na : na, title='20 EMA 4 hour')
plot(show_4h ?show_ema50_4?ema50_4: na : na, title="50 EMA 4 hour")
plot(show_4h ?show_ema100_4?ema100_4: na : na, title="100 EMA 4 hour")
plot(show_4h ?show_ema200_4?ema200_4: na : na, title="200 EMA 4 hour")

on plotting, there are steps on the graph.
However, when I use the in-built indicator and change the timeframe to 4 hour that line is completely smooth.
This is how it looks like.

the red line is the in-built indicator and the blue line is my indicator.
How can I make the line smooth?

A: You face this problem, because you make the values of timeframe for exponential moving average "EMA" is 360 which mean 6 hours so once you open any chart the EMA will be for 6 hours, you should to change it to timeframe.period to be the EMA similar to timeframe timeframe.period
//@version=5
indicator(title='higher tf', overlay=true)

// 4 hr

show_4h = input(title='Show 4 hour', defval=true, group = "4 HOUR")

show_ema20_4 = input(title='Show 20 EMA of 4 hour', defval=true, group = "4 HOUR")
ema20_4_period = input(title='20 EMA of 4 hour Period', defval=20, group = "4 HOUR")

show_ema50_4 = input(title='Show 50 EMA of 4 hour', defval=true, group = "4 HOUR")
ema50_4_period = input(title='50 EMA of 4 hour Period', defval=50, group = "4 HOUR")

show_ema100_4 = input(title='Show 100 EMA of 4 hour', defval=true, group = "4 HOUR")
ema100_4_period = input(title='100 EMA of 4 hour Period', defval=100, group = "4 HOUR")

show_ema200_4 = input(title='Show 200 EMA of 4 hour', defval=true, group = "4 HOUR")
ema200_4_period = input(title='200 EMA of 4 hour Period', defval=200, group = "4 HOUR")

ema20_4 = request.security(syminfo.tickerid, timeframe.period, ta.ema(close, ema20_4_period),lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema50_4 = request.security(syminfo.tickerid, timeframe.period, ta.ema(close, ema50_4_period),lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema100_4 = request.security(syminfo.tickerid, timeframe.period, ta.ema(close, ema100_4_period), lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
ema200_4 = request.security(syminfo.tickerid, timeframe.period, ta.ema(close, ema200_4_period), lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)

plot(show_4h ? show_ema20_4 ? ema20_4 : na : na, title='20 EMA 4 hour')
plot(show_4h ?show_ema50_4?ema50_4: na : na, title="50 EMA 4 hour")
plot(show_4h ?show_ema100_4?ema100_4: na : na, title="100 EMA 4 hour")
plot(show_4h ?show_ema200_4?ema200_4: na : na, title="200 EMA 4 hour")


text:
Q: Calculating ellipse arc length via elliptic integral I'm looking for an exact equation to calculate the arc length of an ellipse.  I've found https://keisan.casio.com/exec/system/1343722259 to correctly calculate the length, but cannot calculate the same result when implementing in Julia via Elliptic.jl or ArbNumerics.
The MathJax equation for the arc length on the Keisan calculator is the same as I've found elsewhere; in Julia:
import Elliptic
function ellipticArcLength(a,b, th0, th1)
  # b<a
  # 0 <= th <= pi/2

  k2 = 1-b^2/a^2
  k = sqrt(k2)
  r2 = th -> a^2*b^2/( b^2*cos(th)^2 + a^2*sin(th)^2 ) #r(th)^2
  r = th -> sqrt(r2(th))
  x = th -> r(th) * cos(th)
  L = a*Elliptic.E( x(th0)/a, k) - a*Elliptic.E( x(th1)/a, k)
  return L
end

println("36.874554322338 ?= $(ellipticArcLength(  50, 20, deg2rad(10), deg2rad(60) ))")
println("99.072689284541 ?= $(ellipticArcLength( 500, 20, deg2rad(10), deg2rad(60) ))")

yielding

36.874554322338 ?= 29.051564462163682
99.072689284541 ?= 98.17285637594554

That is, the 50x20 ellipse is significantly off while the 500x20 is close, but I expect the elliptic integral method to be exact.
Can anyone point out my error(s)?
(DLMF provides a 2-part formula which hasn't been close in my attempts.)
Thank you

A: using ArbNumerics

function ellipticArcLength(a, b, angle )
  phi = atan( a/b*tan(angle))
  m = 1 - (a/b)^2
  return b*elliptic_e( ArbReal(phi), ArbReal(m) )
end
function ellipticArcLength(a, b, start, stop)
  lStart = ellipticArcLength(a,b, start)
  lStop = ellipticArcLength(a,b, stop)
  return lStop - lStart
end

println("36.874554322338 ?= $(ellipticArcLength(  50, 20, deg2rad(10), deg2rad(60) ))")
println("99.072689284541 ?= $(ellipticArcLength( 500, 20, deg2rad(10), deg2rad(60) ))")

Multiplying by the major axis instead of the minor seems to be the root error, see https://math.stackexchange.com/a/1123737/974011 .

A: Ellipse Circumferential length
Ellipse circumference is expressed in terms of the elliptic integral of the second kind exactly:
$$ 4 a E(e)$$
For $(a,b) = (5,4), e =\dfrac{\sqrt{21}}{4}.$


text:
Q: DD-WRT: Router assigns a dynamic IP in addition to a static IP causing systems to get two IP addresses I have my server in my room right now because my WiFi card doesn't support AP mode and I need to bridge a VM to the local network.
I opted to start simple. I used my WNDR3400 with DD-WRT and put all my devices on that.
I have my Kubuntu server with a windows 7kvm plugged in via ethernet.
I gave kubuntu a static ip of 192.168.1.110 and Windows 7 a static ip of 192.168.1.111.
I declared this in the Services menu of DD-WRT. And I declared .110 in kubuntu's network settings menu on a new ethernet connection.
Everything worked great! I could ssh and rdp through my forwarded ports and everything.
Cool, now to add the 2nd router. I plug kubuntu into the 2nd router, disconnect my old connction (rt1) and created a new one (rtSetup) with a static ip of 192.168.1.140 (the 2nd router's local ip is 192.168.1.100)
I setup the router with the wifi info and set it to bridge more and then turned it off.
I plugged kubuntu back into the the original router, I did this because when i turn the 2nd router back on I want to see if I can ping it from the gateway router.
And then problems started, I couldn't get on the web even though I had an ip address or 192.168.1.110. I looked in the menu and I see two active devices with the same MAC address.
Kubuntu was given two ips, the one it declared and the one DHCP gave it .127.
If I set Kubuntu to use DHCP I get .127 and get get online. It will ignore the static assignment on the router. If I request .110 in Kubuntu wierd things happen, I get two connections with two different interfaces for connection rt1.
I will get (rt1 (enpl0s) this is systemd's name for the ethernet) and (rt1 (virbr0 (this is the bridge for windows). This never happened before as it has always been simply rt1.
So i look on DD-WRT and see this: (MAC gets two ips, conflicts all around)

I'm just trying to get back to my working config now and it's not happening.
Kubuntu shows no connections in network config, but if I run ifconfig I have all these broken duplicate connections that aren't in /etc/network/interfaces.
I noticed DD-WRT has two active connections for my nic, but if I look in DHCP clients only the working ip .127 will appear.
From DHCP clients I can erase the .127, this will make the name a * in active connections however .110 will still remain there.
I tried rebooting the router to no avail. Why are static IP's so cumbersome? I thought it was supposed to be simpler and more abolute than DHCP.


text:
Q: jQGrid error when firing edit form I'm using free jQGrid in it's latest version and jQuery Migrate 1.4.1 (1.6.x to 1.9.2) and jQuery UI 1.12.1.
After updating jQuery / jQuery UI edit form isn't working anymore!
CODE:
onInitializeForm: function(formid) {
    var form = $(formid).attr('id').split('-').pop();
    var id = $(formid).find('#id_g').val();
    var bt_gerar = $('<input />').attr('type', 'button').val('Gerar').click(function() {
        $(formid).find('input[name="senha"]').val(gerarPassword());
    });
    if (form === 'laudos') $(formid).find('input[name="senha"]').after(bt_gerar);
    if (form === 'usuarios') $(formid).find('input[name="senha"]').val('');
    $(formid).find('input[name="criacao"], input[name="exclusao"], input[name="data"]').datepicker({
        dateFormat: 'dd/mm/yy'
    });
    /* UPLOAD LAUDO */
    var base_url = window.location.protocol + "//" + window.location.host + "/_dev/";
    $('#arquivo').uploadify({
        'swf'  : base_url + 'admin/js/uploadify-new/uploadify.swf',
        'uploader'    : base_url + 'admin/js/uploadify-new/uploadify.php?laudo=true',
        'cancelImage' : base_url + 'admin/img/cancel.png',
        'buttonImage' : base_url + 'admin/img/upload_mini.png',
        'wmode'     : 'transparent',
        'width'     : '20',
        'height'    : '20',
        'auto'      : true,
        'multi'     : false,
        'fileExt'   : '*.pdf',
        'fileDesc'  : 'Arquivo PDF (.PDF)',
        'onComplete': function(event, ID, fileObj, response, data) {
            $('#arquivo').before($('<input />').attr({type:'text',id:'arquivo_temp',class:'FormElement',name:'arquivo',value:response,role:'textbox'}));
            $('#arquivo, #arquivoUploader, #arquivoQueue').remove();
            $('#arquivo_temp').attr('id','arquivo').hide();
            $('#arquivo').after($('<img />').attr({src:'/laudos/pdf.png',id:'arquivo_icone'}));
        }
    });

ERROR:
TypeError: $(...).closest(...).attr(...).replace is not a function

FILE: jquery.jqgrid.src.js at line 19319
CODE ERROR LINE:
$id = $(this).closest("table.ui-jqgrid-btable").attr("id").replace(/_frozen([^_]*)$/, "$1")

Got any light?
Thk yu!

A: Please specify the exact version of jqGrid, which you use. The line 19319 of  jquery.jqgrid.src.js of free jqGrid 4.13.6 contains var insertPrefixAndSuffix = function (sOutput, opts) { (see here). The statement "I'm using free jQGrid in it's latest version" gives not much enough information.
The line $id = $(this).closest("table.ui-jqgrid-btable").attr("id").replace(/_frozen([^_]*)$/, "$1"), which you posted, has the line number 19319 in the version 4.13.5 of free jqGrid. The code is inside of $.fn.fmatter.rowactions. Thus you have probably some problems with the usage of formatter: "actions", but you don't included colModel with the corresponding column. The method $.fn.fmatter.rowactions will be called in onclick of actions buttons, which must be inside of jqGrid, which must have ui-jqgrid-btable class.
It's difficult for me to guess, why you get the error. Either you made some illegal modifications of jqGrid classes (like removing ui-jqgrid-btable class) or you moved the grid content (inclusive the actions buttons) outside of jqGrid content or some other strange things. In any way you should include the definition of the column of colModel, which uses formatter: "actions".
By the way, free jqGrid supports template: "actions", which you can use instead of formatter: "actions". The template: "actions" is the shortcut of the following settings
formatter: "actions", align: "center", label: "", autoResizable: false, frozen: true,
fixed: true, hidedlg: true, resizable: false, sortable: false,
search: false, editable: false, viewable: false

and width setting, which value depend on some other options of jqGrid. The most of the properties are strictly recommended for the column with formatter: "actions" (even for old versions of jqGrid).
I'd recommend you to update to free jqGrid 4.13.6 and to replace formatter: "actions" to template: "actions" (or add editable: false and other above properties in the actions column alternatively). I hope that it will fix your problem.


text:
Q: Шифр Цезаря и Виженера. Не получается вывести ответ на textbox Хотел реализовать метод шифрования Цезаря и Виженера с помощью интерфеса и классами.Код работает. Он считывает с textBox1.Text, textBox3.Text значения и шифрует, но я не знаю как вывести ответ на textBox2.Text при нажатии на кнопку. Класс Виженера на стал ставить.Помогите пожалуйста разобратья)
Код:
namespace Цезарь_и_Виженера
{
    interface IEncrypt
    {
        void Encrypt(string text, string key); //зашифровать
        void Decrypt(string text, string key); //расшифровать
        string Text { get; set; } //текст
    }
    class Cipher
    {
        public IEncrypt Encrypter { get; set; }
        public void Encrypt(string text, string key)
        {
            Encrypter.Encrypt(text, key);
        }
        public void Decrypt(string text, string key)
        {
            Encrypter.Decrypt(text, key);
        }
    }
    class Caesar : IEncrypt
    {
        const string alfabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
        public string Text { get; set; }
        private void CodeEncode(string text, int key)
        {
            //добавляем в алфавит маленькие буквы
            var fullAlfabet = alfabet + alfabet.ToLower();
            var letterQty = fullAlfabet.Length;
            var retVal = "";
            for (int i = 0; i < text.Length; i++)
            {
                var c = text[i];
                var index = fullAlfabet.IndexOf(c);
                if (index < 0)
                {
                    //если символ не найден, то добавляем его в неизменном виде
                    retVal += c.ToString();
                }
                else
                {
                    var codeIndex = (letterQty + index + key) % letterQty;
                    retVal += fullAlfabet[codeIndex];
                }
            }
            Text = retVal;
        }
        public void Encrypt(string text, string key)
        {
            CodeEncode(text, Convert.ToInt32(key));

        }
        public void Decrypt(string text, string key)
        {
            CodeEncode(text, -Convert.ToInt32(key));
        }
    }
}
public partial class Form1 : Form
{
    Cipher cipher = new Cipher();
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
            cipher.Encrypter = new Caesar();
            cipher.Encrypt(textBox1.Text, textBox3.Text);
            textBox2.Text =
    }
}

A: Я так понимаю Text = retVal; retVal - это зашифрованное\расшифрованное сообщение
тогда textBox2.Text = cipher.Encrypter.Text;


text:
Q: Android JDBC: Second SQL Thread not working for the past few days i've been trying to solve an issue i'm having with my Android code where i execute two different threads, the first one that executes when i start the app works perfectly and there are no errors with the query.
However the second thread that executes when I click the submit button is not executing the SQL query.
Here's the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    submitButton = (Button) findViewById(R.id.submitButton);

    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"This works",Toast.LENGTH_LONG).show();

            service = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            checkPermission();

            criteria = new Criteria();

            String provider = service.getBestProvider(criteria, false);

            if (provider != null & !provider.equals("")) {
                Location location = service.getLastKnownLocation(provider);
                service.requestLocationUpdates(provider, 2000, 1, MainActivity.this);

                if (location != null) {
                    onLocationChanged(location);
                } else {
                    Toast.makeText(MainActivity.this, "location not found", Toast.LENGTH_LONG).show();
                }

            } else {
                Toast.makeText(MainActivity.this, "Provider is null", Toast.LENGTH_LONG).show();
            }

            selectionEvent = eventSpinner.getSelectedItem().toString();

            insertThread.start();

        }
    });

    sqlThread.start();
}

Thread sqlThread = new Thread(){
    public void run(){

        alertHandler = new Handler(Looper.getMainLooper());

        try{

            Class.forName("org.postgresql.Driver");

            String url = "localhost:5432";
            Connection conn = DriverManager.getConnection(url,"arodriguez","alejandro2017");

            String statementSQL = "SELECT * FROM incidencias";
            Statement statement = conn.createStatement();
            ResultSet resultSet = statement.executeQuery(statementSQL);
            while(resultSet.next()){
                tiposIncidencias.add(resultSet.getString(2));
                naturalezaIncidencias.add(resultSet.getString(3));
            }

            alertHandler.post(new Runnable() {
                @Override
                public void run() {
                    addDefaultItemsOnTypeSpinner();
                    addDefaultItemsOnEventSpinner();
                }
            });

            String statementSQL2 = "INSERT INTO arodriguez.prueba (description,x,y) VALUES ('"+selectionEvent+"',"+latitude+","+longitude+")";
            Statement s = null;
            s = conn.createStatement();
            s.executeUpdate(statementSQL2);

            conn.close();

        } catch (SQLException se){
            Toast.makeText(MainActivity.this,se.toString(),Toast.LENGTH_LONG).show();

        } catch (ClassNotFoundException e){
            Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
        } catch (Exception ex){
            Log.d("Error",ex.toString());
        }
        return;
    }
};

Thread insertThread = new Thread(){

    public void run(){

        alertHandler = new Handler(Looper.getMainLooper());

        try{

            alertHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,selectionEvent,Toast.LENGTH_LONG).show();
                }
            });

            Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://localhost:5432/sde";
            Connection conn = DriverManager.getConnection(url,"arodriguez","alejandro2017");

            String statementSQL = "INSERT INTO arodriguez.prueba (description,x,y) VALUES ('"+selectionEvent+"',"+latitude+","+longitude+")";
            Statement statement = null;
            statement = conn.createStatement();
            statement.executeUpdate(statementSQL);

            conn.close();

        }catch (SQLException se){
            Log.d("Error",se.toString());
        } catch (ClassNotFoundException e){
            Log.d("Error",e.toString());
        } catch (Exception ex){
            Log.d("Error",ex.toString());
        }
        return;
    }
};

For some reason if I add the insert query in the first thread it does works:
     String statementSQL = "INSERT INTO arodriguez.prueba (description,x,y) VALUES ('"+selectionEvent+"',"+latitude+","+longitude+")";
     Statement statement = null;
     statement = conn.createStatement();
     statement.executeUpdate(statementSQL);

Am I doing something wrong?


text:
Q: Loop through sheet and return each table as a data set I have written a function that will read all the data from a spreadsheet, and then attempt to parse each dataset into an array of objects.
Right now, I am able to make it return the first dataset into an object but can't get it to do the same for the other datasets in the sheet.
This is what my sheet looks like.

My overall goal is to grab each section of data if there is a section name in column a, and then place them into the sectionData. Each section would be named by the sectionName. I would like the structure of the array to be something like this:
sectionData[sectionName[object[key][value]]sectionName[object[key][name]]]...

I have written some code that will loop through and return all the data for the first set, but am having difficulties getting it to return data for the other sets.
function getSheetSectionDataTest(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Params"); // get sheet
  var sheetData = sheet.getDataRange().getValues(); //get all sheet data
  //var sectionNames = normalizeHeaders(sheet.getRange("A1:A").getValues()); //get all data from column A (section names)
  var sectionData = [];
  var section = []; //create empty object for data

  for (var i=0; i<sheetData.length; i++){ //loop through data
      if (sheetData[i][0] !== ""){ // The loop should stop at each cell in the first column that has a value and run the following code:
        var sectionName = normalizeHeader(sheetData[i]); //return section name found in column A
        //if (sectionName === "types"){
          var headerRow = normalizeHeaders(sheetData[i+1]);
          for (var j = 2; j < sheetData.length; j++) {
              if(sheetData[j][1]!==""){
              var obj = {};
              section.push(obj);
              for (var rowColumn = 0; rowColumn < headerRow.length; rowColumn++) {

                obj[headerRow[rowColumn]]=sheetData[j][rowColumn+1];
                }
              }
              else{
                return section; //when the loop runs into an empty cell stop loop and return the data
              }
          }
        //}
      }
    }
};

My code will return all the data for 1 section, but not for the others:


text:
Q: C# Convert back from thousand separator to int I have a code that makes an int to a thousend separator but when I try to save this value in the text box to the database I want to remove the space between. I could not do this with replace(" ","").
YearTB.Text = (String.Format(culture, "{0:n0}", Int32.Parse(YearTB.Text)));

What is in the box is for example "536 396" but the space between is not an " ". its the effect of the thousand seperator. How can I return it back to int. "536396".

A: If you just want to convert to a string without the thousands rather than to an int:
string result = text.Replace(culture.NumberFormat.NumberGroupSeparator, "");

This assumes that culture is the CultureInfo with which the number was formatted using a thousand separator.
Alternatively if you want to convert to an int, you can use int.Parse() directly and specify that you want to allow the thousands separator (which I think is a better approach):
int result = int.Parse(text, NumberStyles.AllowThousands, culture);

A: Try this
string str = "536 396";
str = Regex.Replace(str, @"\s", "");


text:
Q: how to test persisting entity with not nullable collection I'm learning how to write test cases and I've encounter a problem.
I have a persistence unit with entityA that has not empty collection of  Bs.
The application workflow ensures that B is never empty and contains entities that have already been persisted.
(Let's say a user has to choose email addresses from his address book)
Now I have a problem in testing persisting A.
If I create A i must create a set of Bs (@NotNull).
B doesn't exist in test db so I get an error "object references an unsaved transient instance".
I'm using dbunit so the question is:
Is it all right to use entitymanager and select set of Bs, that have been loaded for test from xml files, then add them to A and persist A? It somehow doesn't sound like a unit test to me. What is the best practice to handle this situation
thanks

A: I don't see any other possibility. A has a dependency to B, so you need to have Bs in order to persist A. Since mocking is not possible in this case, you need to get your Bs from the database.


text:
Q: Change the color of elements in Select from MUI It seems that there were quite a lot of questions and answers on this topic, but I could not find anything suitable for myself. I ask the community for help.
I'm using the Select component from @mui/material to display the number of records per page. And I'd like to change the color of the window's border when it's clicked, and the background color of the currently selected element.
I marked with a red arrow in the picture those elements that I want to change.
SelectMenuItemsPerPage.jsx
import React from 'react';
import { MenuItem, Select } from "@mui/material";
import { styles } from './SelectMenuItemsPerPageStyles';

export default function SelectMenuItemsPerPage({ pageSize, setPageSize }) {
    const handleChange = (event) => {
        setPageSize(Number(event.target.value));
    };

    return (
        <Select
            value={pageSize}
            onChange={handleChange}
            sx={styles.Select}
        >
            <MenuItem value={5}>5</MenuItem>
            <MenuItem value={10}>10</MenuItem>
            <MenuItem value={25}>25</MenuItem>
            <MenuItem value={50}>50</MenuItem>
            <MenuItem value={100}>100</MenuItem>
        </Select>
    );
}

A: You need to add the following CSS to this page, add this to index.css or globals.css (In the case of Next.js).

The code

.MuiMenuItem-root.Mui-selected {
  background: yellow;
}
.MuiTablePagination-select[aria-expanded="true"] {
  border: 2px solid green;
}

The output

Play around with the code here

A: You need to use MenuProps and style it as follows:
<Select
     MenuProps={{
        sx: {
          "&& .Mui-selected": {
            color: "red",
            background: "rgba(0,233,0,0.2)",
          },
        },
       }}

Here is the complete working example:

<Select
      value={val}
      MenuProps={{
        sx: {
          "&& .Mui-selected": {
            color: "red",
            background: "rgba(0,233,0,0.2)",
          },
        },
      }}
      sx={{
        "& [aria-expanded=true]":{
          background: "rgba(0,233,0,0.2)",
        },
      }}
      onChange={(e) => setVal(e.target.value)}
    >
      <MenuItem value={5}>5</MenuItem>
      <MenuItem selected value={10}>
        10
      </MenuItem>
      <MenuItem value={25}>25</MenuItem>
      <MenuItem value={50}>50</MenuItem>
      <MenuItem value={100}>100</MenuItem>
    </Select>

The output (You can style them as you wish):


text:
Q: Is there a Dependency Injection framework for PHP4? I'm stuck on a PHP 4 server, and I would like to start moving an old legacy project to modern Design Patterns, including Dependency Injection.  Are there any dependency injection frameworks that will work with PHP 4?

A: Most dependency injection frameworks use reflection to determine dependencies. Since PHP4 doesn't have typehints, you can't really do this. Experiments have been made with using config files - Some times embedded in comments in the code (Often called annotations). While this works, I find it a bit clunky. In my opinion, you're better off using PHP's dynamic nature to your advantage, than to try and apply statically typed solutions to it. You can get a long way with hand-crafted factories. See for example this post on how.

A: i found this (drip), but it looks like it hasn't been updated in a few years.

A: I don't think a dependency injection framework will really work on PHP because of the way object-oriented programs are structured in it. First of all, it's not like C# or Java wherein the binaries are already there and you just have to find a way to instantiate this object and inject it into another. PHP has to load the class files and interpret them before it can use them. So if you have deep inheritance hierarchies with PHP I don't think that's a good idea.
Given that PHP is a scripting language, it's best to leverage it as that -- a scripting language. Which means, I would just make use of simple factory or builder methods to do something similar to dependency injection. I wouldn't burden it with a DI framework that will only add to the stuff the PHP runtime has to process for every web request (unless you do opcode caching, but there will still be overhead that's not incurred by web platforms for Java and .NET). If I have to change the objects that will be injected into objects or how they are created, it would be a simple task to just edit the script that contains the factory/builder methods. No need to recompile there anyway. So I have flexibility and I have a lightweight architecture that's suitable for the PHP way of doing things.


text:
Q: FB Pixel Purchase Event - Working on desktop not on mobile? FB Pixel on desktop firing fine passing order id, revenue etc
Not firing on mobile?
Am seeing the tag firing in GTM preview but getting error message in pixel helper on mob:
WARNINGS
We detected event code but the pixel has not activated for this event, so no information was sent to Facebook. This could be due to an error in the code, but could also occur if the pixel fires on a dynamic event such as a button click.Learn more
Any ideas why this would work fine on desktop but not on mob?
Thanks.

<!-- Facebook Pixel Code -->
<script>
 jQuery(document).ready(function()
 {
  var purchaseLength = {{transactionQty}};
  var purchaseID = [];
  var productName = [];
  var i;
  for(i = 0; i< purchaseLength; i++)
  {

    purchaseID.push({{transactionProducts}}[i].sku);
    productName.push({{transactionProducts}}[i].name);

  }

    fbq('track', 'Purchase', {
      content_ids: purchaseID,
      content_name: productName,
      content_type: 'product',
      value: {{transactionTotal}},
      currency: 'GBP'
    });
     });
</script>


text:
Q: spark.sql in pyspark - Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient I have an issue with pyspark.sql as I try to perform a simple SQL query, but I see the following error:

AnalysisException: 'org.apache.hadoop.hive.ql.metadata.HiveException:
java.lang.RuntimeException: Unable to instantiate
org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient;'

The code that initially reads the Hive table works properly:

df =
spark.read.csv("hdfs://localhost:54310/user/hduser/creditfraud/creditscoring.csv",
header=True, sep=',', inferSchema=True) df.printSchema()

But as soon as I run spark.sql I encounter some troubles:

df.createOrReplaceTempView("CreditTempTable")
df1 = spark.sql("SELECT * FROM CreditTempTable LIMIT 10") df1.show()

Hive 2.3.5 works normally and I can see the tables and run SQL code in it, so I believe that the issue comes from the Spark and Linux configuration files, which are the following:
spark-defaults.conf:

spark.sql.hive.metastore.version 2.3.0
spark.sql.hive.metastore.jars
/usr/local/hive/lib/:/usr/local/hadoop/share/hadoop/

.bashrc configuration file:

Set HIVE_HOME export
HIVE_HOME=/usr/local/hive
export HIVE_CONF_DIR=/usr/local/hive/conf
PATH=$PATH:$HIVE_HOME/bin
export PATH
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/usr/local/hive/lib/*
Set Spark vars
export SPARK_HOME=/usr/local/spark
PATH=$PATH:$SPARK_HOME/bin
export PYSPARK_PYTHON=python3 export
PYSPARK_DRIVER_PYTHON=jupyter export
PYSPARK_DRIVER_PYTHON_OPTS="notebook"

I would really appreciate if you could help me figuring out where the issue is coming from.


text:
Q: Broken page margins with boiboites package in Latex I'm  trying to write a mathematical proof with a newboxedtheorem command using boiboites package, but once the core is too long, I see no broken page, so a large part of my proof is missed in the output file, I will be very thankful if you could help me.
Here is my declaration:
\newenvironment{quotationb}
{\begin{leftbar}\begin{quotation}}
{\end{quotation}\end{leftbar}}
\newboxedtheorem[boxcolor=black, background=white, titlebackground=white, titleboxcolor = black,
size = 0.9\textwidth]{dem}{Démonstration}{compteurTH}
\renewcommand{\thecompteurTH}{\arabic{chapter}.\arabic{compteurTH}}
\newcommand{\norme}[1]{\left\Vert\par\nobreak\@afterheading #1\right\Vert}

and my proof:
\begin{dem}
Soit
\begin{align}
Y_{t}&:=\mathbb{E}\lbrace\xi +\int^{T}_{t} f(s)ds\vert\mathcal{F}_{t}\rbrace,
\end{align}
D'après le théorème de représentation de Martingale il existe un processus stochastique adapté $Z \in \mathit{L}^{2}_{T} $ tel que :
\begin{align}
Y_{0}&:=\mathbb{E}\lbrace\xi +\int^{T}_{0} f(s)ds\vert\mathcal{F}_{t}\rbrace - \int_{0}^{T} Z_{s}dw_{s},
\end{align}
D'où le couple $(Y,Z)$ définit en (7) et (8) est une solution de (6), grâce a l'intégrabilité de $\xi$ on a  :
\begin{align}
\mathbb{E}\lbrace\xi +\int^{T}_{0} f(s)ds\vert\mathcal{F}_{T}\rbrace = \xi +  \int^{T}_{0} f(s)ds = T(0) + \int^{T}_{0} Z_{s}dW_{s},
\end{align}
Soit
\begin{align}
 \int^{T}_{t} Z_{s}dW_{s}&=  \xi +\int^{T}_{0} f(s)ds - \mathbb{E}\lbrace\xi +\int^{T}_{0} f(s)ds\vert\mathcal{F}_{T}\rbrace,
\end{align}
Finalement on remplace par (7) dans (10) on retrouve le résultat, donc $(Y,Z)$ est la solution cherchée. \qedhere
\end{dem}
\begin{prop}
Soit $\xi \in \mathit{L}^{2}_{T}$ la condition terminale, $f: \Omega\times[0,T]\mathbb{R}^{n\times d} \longrightarrow \mathbb{R}^{d}$ le générateur $\mathcal{P}\bigotimes\mathcal{B}^{n\times d}$-mesurable, de telle sorte que $f(.,0)\in\mathit{H}^{2}_{T}$ Lipschitzienne par rapport a la deuxième variable, i.e:
$\exists C>0$ tel que :
\begin{align}
\vert f(t,z_{1})-f(t,z_{2})\vert \leq C\vert z_{1}-z_{2}\vert, \forall z_{1},z_{2}\in \mathbb{R}^{d\times n},
\end{align}
Alors il existe un unique couple $(Y,Z)\in \mathit{H}^{2}_{T}(\mathbb{R}^{d})\times\mathit{H}^{2}_{T}(\mathbb{R}^{n\times d})$ solution de l'équation suivante :
\begin{align}
Y_{t}&=\xi +\int^{T}_{t} f(s,Z_{s})ds - \int^{T}_{t} Z_{s}dW_{s},
\end{align}
\end{prop}
\begin{dem}
\textbf{L'unicité :}\\
Soit $(Y,Z)$ et $(\tilde{Y},\tilde{Z})$ deux solutions de (12).D'après la formule d'Itô appliquée à $\vert Y_{s}-\tilde{Y_{s}}\vert^{2}$.\newline
En fait, la dynamique de $\vert Y_{s}-\tilde{Y_{s}}\vert^{2}$ est comme suit :
\begin{align}
d \vert Y_{s}-\tilde{Y_{s}}\vert^{2} = \lbrace f(t,Z_{t})-f(t,\tilde{Z}_{t})\rbrace dt + \lbrace Z - \tilde{Z}_{t}\rbrace dW_{t},
\end{align}
Soit \begin{align*}
\vert Y_{t}-\tilde{Y_{t}}\vert^{2}-\vert Y_{0}-\tilde{Y_{0}}\vert^{2} =& 2\int_{0}^{t} (Y_{s}-\tilde{Y_{s}},f(s,Z_{s})-f(s,\tilde{Z}_{s}))ds \\&+ 2\int_{0}^{t} (Y_{s}-\tilde{Y_{s}},Z_{s} - \tilde{Z}_{s})dW_{s} + \int_{0}^{t} \vert Z_{s} - \tilde{Z}_{s}\vert^{2}ds,
\end{align*}
De la même façon
  \begin{align*}
 \vert Y_{T}-\tilde{Y}_{T}\vert^{2}- \vert Y_{0}-\tilde{Y_{0}}\vert^{2} = - \vert Y_{0}-\tilde{Y_{0}}\vert^{2} &= 2\int_{0}^{T} (Y_{s}-\tilde{Y}_{s},f(s,Z_{s})-f(s,\tilde{Z}_{s}))ds\\ &+ 2\int_{0}^{T} ( Y_{s}-\tilde{Y}_{s},Z_{s} - \tilde{Z}_{s})dW_{s} + \int_{0}^{T} \vert Z_{s} - \tilde{Z}_{s}\vert^{2}ds ,
\end{align*}
D'où
\begin{align*}
 \vert Y_{t}-\tilde{Y}_{t}\vert^{2} + \int_{t}^{T} \vert\bar{Z}_{s}\vert^{2}ds &= -2\int_{t}^{T}  (Y_{s}-\tilde{Y}_{s},f(s,Z_{s})-f(s,\tilde{Z}_{s}))ds  \\ &- 2\int_{0}^{T} (Y_{s}-\tilde{Y}_{s}, Z_{s} - \tilde{Z}_{s})dW_{s},
\end{align*}
On exploite le faite que $f$ est Lipschitzienne on a la majoration suivante :
\begin{align*}
\left(  Y_{s}-\tilde{Y}_{s},f(s,Z_{s})-f(s,\tilde{Z}_{s})\right) &=-2\left( \sqrt{2}c (Y_{s}-\tilde{Y}_{s}),\dfrac{f(s,Z_{s})-f(s,\tilde{Z}_{s})}{\sqrt{2}c}\right) \\
&=2c^{2}\vert Y_{s}-\tilde{Y}_{s}\vert^{2} + \dfrac{\vert f(s,Z_{s})-f(s,\tilde{Z}_{s})\vert^{2}}{2c^{2}}\\ & - \vert Y_{s}-\tilde{Y}_{s} + f(s,Z_{s})-f(s,\tilde{Z}_{s}) \vert^{2} \\
& \leq 2c^{2}\vert Y_{s}-\tilde{Y}_{s}\vert^{2} + \dfrac{\vert f(s,Z_{s})-f(s,\tilde{Z}_{s})\vert^{2}}{2c^{2}}\\
& 2c^{2}\vert Y_{s}-\tilde{Y}_{s}\vert^{2} + \dfrac{C \vert Z_{s}-\tilde{Z}_{s}\vert^{2}}{2},
\end{align*}
On regroupant l'inégalité et l'égalité précédentes on a :\newpage
\begin{align*}
\vert Y_{t}-\tilde{Y}_{t}\vert^{2} + \int_{t}^{T} \vert Z_{s}-\tilde{Z}_{s}\vert^{2}ds &\leq \int_{t}^{T} \lbrace 2c^{2}\vert Y_{t}-\tilde{Y}_{t}\vert^{2} + \frac{1}{2}\vert Z_{s}-\tilde{Z}_{s}\vert^{2}\rbrace ds\\ &- 2\int_{0}^{T} (Y_{s}-\tilde{Y}_{s}, Z_{s} - \tilde{Z}_{s})dW_{s},
\end{align*}
On faisant intervenir l'espérance, d'intégrale stochastique s'annule puisque $(Y,Z)\in \mathit{H}^{2}_{T}(\mathbb{R}^{d})\times\mathit{H}^{2}_{T}(\mathbb{R}^{n\times d})$, Soit alors
\begin{align}
\mathbb{E}\vert Y_{t}-\tilde{Y}_{t}\vert^{2} + \mathbb{E}\int_{t}^{T} \vert Z_{s}-\tilde{Z}_{s}\vert^{2}ds &\leq 2c^{2}\mathbb{E}\int_{t}^{T}  \vert Y_{t}-\tilde{Y}_{t}\vert^{2}ds + \frac{1}{2}\mathbb{E}\int_{t}^{T}\vert Z_{s}-\tilde{Z}_{s}\vert^{2} ds,
\end{align}
il s'en suit que
\begin{align}
\mathbb{E}\vert Y_{t}-\tilde{Y}_{t}\vert^{2} \leq -\frac{1}{2} \mathbb{E}\int_{t}^{T} \vert Z_{s}-\tilde{Z}_{s}\vert^{2}ds \\&+ 2c^{2}\mathbb{E}\int_{t}^{T}\vert Y_{t}-\tilde{Y}_{t}\vert^{2}ds,
\end{align}
D'après le lemme de Gronwall appliquée à (15):
\begin{align*}
0\leq\mathbb{E}\vert Y_{t}-\tilde{Y}_{t}\vert^{2}\leq-\frac{1}{2}e^{2c^{2}(T-t)}\mathbb{E}\int_{t}^{T} \vert Z_{s}-\tilde{Z}_{s}\vert^{2}ds\leq 0,
\end{align*}
d'où
\begin{align}
\mathbb{E}\vert Y_{t}-\tilde{Y}_{t}\vert^{2}=\mathbb{E}\int_{t}^{T} \vert Z_{s}-\tilde{Z}_{s}\vert^{2}ds = 0,
\end{align}
ce qui prouve l'unicité du couple solution.\\
 \textbf{L'existence:} \\
Soit $(Y_{0}(t),Z_{0}(t))\equiv (0,0),\lbrace(Y_{n}(t),Z_{n}(t)),0\leq t\leq T\rbrace_{n\geq}$ une suite de $\mathit{H}^{2}_{T}(\mathbb{R}^{d})\times\mathit{H}^{2}_{T}(\mathbb{R}^{n\times d})$, solution par l'équation stochastique rétrograde suivante :
\begin{align}
Y_{n}(t)= \xi + \int_{t}^{T}f(s,Z_{n-1}(s))ds - \int_{t}^{T}Z_{n}(s)dW_{s},
\end{align}
La suite est bien définit grâce au lemme 1.\newline
En suivant la même démarche utilisé dans (14) pour $\vert Y_{n+1}(s)-Y_{n}(s)\vert^{2}$ pour $s=t$, $s=T$ , et en utilisant le fait que $f$ est Lipschitzienne, on trouve l'inégalité suivante :
\begin{align*}
\mathbb{E}\vert Y_{n+1}(t)-Y_{n}(t)\vert^{2} + \mathbb{E}\int_{t}^{T}\vert Z_{n+1}(s)-Z_{n}(s)\vert^{2}ds&\leq 2c^{2} \mathbb{E}\int_{t}^{T}\vert Y_{n+1}(s)-Y_{n}(s)\vert^{2}ds\\
 &+ \frac{1}{2}\mathbb{E}\int_{t}^{T}\vert Z_{n}(s)-Z_{n-1}(s)\vert^{2}ds,
\end{align*}
ce qui est équivalent à :
\begin{align*}
-  \dfrac{d}{dt}\left( e^{2c^{2}t} \mathbb{E}\int_{t}^{T}\vert Y_{n+1}(s)-Y_{n}(s)\vert^{2}ds\right)e^{-2c^{2}t}  + \mathbb{E}\int_{t}^{T}\vert Z_{n+1}(s)-Z_{n}(s)\vert^{2}ds\leq
  \frac{1}{2}\mathbb{E}\int_{t}^{T}\vert Z_{n}(s)-Z_{n-1}(s)\vert^{2}ds,
\end{align*}
Soit $u_{n}(t):=\mathbb{E}\int_{t}^{T}\vert Y_{n}(s)-Y_{n-1}(s)\vert^{2}ds$ and $v_{n}(t):=\mathbb{E}\int_{t}^{T}\vert Z_{n}(s)-Z_{n-1}(s)\vert^{2}ds$,
Alors on a :
\begin{align}
-\dfrac{d}{dt}(u_{n+1}(t)e^{2c^{2}t})+e^{2c^{2}t}v_{n+1}(t)\leq \frac{1}{2}e^{2c^{2}t}v_{n}(t),
\end{align}
Intégrons cette formule entre $t$ et $T$, sachant que $u_{n}(T)=0$  :
\begin{align*}
u_{n+1}(t)e^{2c^{2}t}+\int^{T}_{t} e^{2c^{2}s}v_{n+1}(s)ds\leq \frac{1}{2}\int^{T}_{t}e^{2c^{2}s}v_{n}(s)ds,
\end{align*}
Soit :
\begin{align}
u_{n+1}(t)+\int^{T}_{t} e^{2c^{2}(s-t)}v_{n+1}(s)ds\leq \frac{1}{2}\int^{T}_{t}e^{2c^{2}(s-t)}v_{n}(s)ds,
\end{align}
Soit $\bar{c}:=\mathbb{E}\int_{0}^{T}\vert Z_{1}(s)\vert^{2}ds = sup_{0\leq t\leq T}v_{1}(t)$,
alors
\begin{align*}
\int^{T}_{0} e^{2c^{2}t}v_{1}(t)dt =\int^{T}_{0}e^{2c^{2}t}\mathbb{E}\int_{t}^{T}\vert Z_{1}(s)\vert^{2}dsdt \leq \int^{T}_{0}e^{2c^{2}T}\mathbb{E}\int_{0}^{T}\vert Z_{1}(s)\vert^{2}dsdt = \bar{c}e^{2c^{2}T},
\end{align*}
Comme $(u_{n})_{n\geq 0}$,$(v_{n})_{n\geq 0}$ sont à terme positif, alors :
\begin{align*}
\int^{T}_{t} e^{2c^{2}s}v_{n+1}(s)ds\leq \frac{1}{2}\int^{T}_{t}e^{2c^{2}s}v_{n}(s)ds,
\end{align*}
d'où
\begin{align*}
\int^{T}_{t} e^{2c^{2}s}v_{n+1}(s)ds\leq \frac{1}{2}\int^{T}_{t}e^{2c^{2}s}v_{n}(s)ds\leq \frac{1}{2^{n}}\bar{c}e^{2c^{2}T},
\end{align*}
En particulier, d'après (19) on a :
 \begin{align}
u_{n+1}(0)\leq \frac{1}{2^{n}}\bar{c}e^{2c^{2}T},
\end{align}
Or, $\dfrac{d}{dt}u_{n+1}(t)=-\mathbb{E}\vert Y_{n+1}(t)-Y_{n}(t)\vert^{2}\leq 0 $ alors on a d'après la formule (18):
\begin{align}
v_{n+1}(0)\leq \frac{1}{2}v_{n}(0) \leq \frac{1}{2^{n}}v_{1}(0)
\end{align}
Donc d'après (20) et (21), les suites $u_{n},$et,$v_{n}$ sont convergentes en d'autre terme :
$(Y_{n})_{n\geq 1}\in$et $ Z_{n}(t))_{n\geq 1}$ sont de Cauchy, de plus les espaces $\mathit{H}^{2}_{T}(\mathbb{R}^{d})$,et $\mathit{H}^{2}_{T}(\mathbb{R}^{n\times d})$ sont complets elles convergent pour tout $t\geq 0$, soit :
$$ \lim\limits_{n \rightarrow +\infty} Y_{n}= Y, \qquad \lim\limits_{n \rightarrow +\infty} Z_{n}= Z$$
Donc par construction le couple $(Y,Z)$ est solution de (12).
\end{dem}

A: The package boiboites won't let you break boxes over multiple pages.
You should use xeboiboites instead, available here:
https://github.com/alexisflesch/xeboiboites


text:
Q: Node.js Bytecode Constant Pool Output I'm extracting the bytecode generated by Node.js like so: 'node --print-bytecode ~/example.js'. The output looks almost identical as the output of d8. However, there are a couple of minor differences.
Take for example this function:
`[generated bytecode for function: emitPromiseRejectionWarnings]
Parameter count 1
Frame size 120
 2658 E> 0x20948dedb3ba @    0 : a0                StackCheck
 2702 S> 0x20948dedb3bb @    1 : 1b 08             LdaImmutableCurrentContextSlot [8]
         0x20948dedb3bd @    3 : a5 00             ThrowReferenceErrorIfHole [0]
         0x20948dedb3bf @    5 : 26 f1             Star r10
 2695 E> 0x20948dedb3c1 @    7 : 28 f1 01 00       LdaNamedProperty r10, [1], [0]
         0x20948dedb3c5 @   11 : 26 f1             Star r10
         0x20948dedb3c7 @   13 : 0b                LdaZero
 2702 E> 0x20948dedb3c8 @   14 : 67 f1 02          TestGreaterThan r10, [2]
         0x20948dedb3cb @   17 : 94 5d             JumpIfFalse [93] (0x20948dedb428 @ 110)
 2665 E> 0x20948dedb3cd @   19 : a0                StackCheck
         0x20948dedb3ce @   20 : 1b 08             LdaImmutableCurrentContextSlot [8]
 2742 E> 0x20948dedb3d0 @   22 : a5 00             ThrowReferenceErrorIfHole [0]
         0x20948dedb3d2 @   24 : 26 f0             Star r11
 2765 E> 0x20948dedb3d4 @   26 : 28 f0 02 03       LdaNamedProperty r11, [2], [3]
         0x20948dedb3d8 @   30 : 26 f1             Star r10
 2765 E> 0x20948dedb3da @   32 : 56 f1 f0 05       CallProperty0 r10, r11, [5]
         0x20948dedb3de @   36 : 26 f5             Star r6
         0x20948dedb3e0 @   38 : 97 06             JumpIfUndefined [6] (0x20948dedb3e6 @ 44)
         0x20948dedb3e2 @   40 : 25 f5             Ldar r6
         0x20948dedb3e4 @   42 : 96 10             JumpIfNotNull [16] (0x20948dedb3f4 @ 58)
         0x20948dedb3e6 @   44 : 0c 4d             LdaSmi [77]
         0x20948dedb3e8 @   46 : 26 f1             Star r10
         0x20948dedb3ea @   48 : 12 03             LdaConstant [3]
         0x20948dedb3ec @   50 : 26 f0             Star r11
         0x20948dedb3ee @   52 : 5e c1 00 f1 02    CallRuntime [NewTypeError], r10-r11
 2721 E> 0x20948dedb3f3 @   57 : a2                Throw
 2742 S> 0x20948dedb3f4 @   58 : 28 f5 03 07       LdaNamedProperty r6, [3], [7]
         0x20948dedb3f8 @   62 : 26 f7             Star r4
 2742 S> 0x20948dedb3fa @   64 : 28 f5 04 09       LdaNamedProperty r6, [4], [9]
         0x20948dedb3fe @   68 : 26 f6             Star r5
 2778 S> 0x20948dedb400 @   70 : 1b 04             LdaImmutableCurrentContextSlot [4]
         0x20948dedb402 @   72 : 26 f0             Star r11
 2791 E> 0x20948dedb404 @   74 : 28 f0 05 0b       LdaNamedProperty r11, [5], [11]
         0x20948dedb408 @   78 : 26 f1             Star r10
         0x20948dedb40a @   80 : 12 06             LdaConstant [6]
         0x20948dedb40c @   82 : 26 ef             Star r12
 2791 E> 0x20948dedb40e @   84 : 58 f1 f0 ef f7 0d CallProperty2 r10, r11, r12, r4, [13]
         0x20948dedb414 @   90 : 91 11             JumpIfToBooleanTrue [17] (0x20948dedb425 @ 107)
 2834 S> 0x20948dedb416 @   92 : 1b 04             LdaImmutableCurrentContextSlot [4]
         0x20948dedb418 @   94 : 26 f0             Star r11
 2842 E> 0x20948dedb41a @   96 : 28 f0 07 0f       LdaNamedProperty r11, [7], [15]
         0x20948dedb41e @  100 : 26 f1             Star r10
 2842 E> 0x20948dedb420 @  102 : 57 f1 f0 f6 11    CallProperty1 r10, r11, r5, [17]
         0x20948dedb425 @  107 : 85 6a 00          JumpLoop [106], [0] (0x20948dedb3bb @ 1)
 2896 S> 0x20948dedb428 @  110 : 11                LdaFalse
         0x20948dedb429 @  111 : 26 f4             Star r7
 2915 S> 0x20948dedb42b @  113 : 1b 07             LdaImmutableCurrentContextSlot [7]
         0x20948dedb42d @  115 : a5 08             ThrowReferenceErrorIfHole [8]
         0x20948dedb42f @  117 : 26 f1             Star r10
 2942 E> 0x20948dedb431 @  119 : 28 f1 01 13       LdaNamedProperty r10, [1], [19]
         0x20948dedb435 @  123 : 26 f3             Star r8
 2962 S> 0x20948dedb437 @  125 : 25 f3             Ldar r8
         0x20948dedb439 @  127 : 73 15             ToNumeric [21]
         0x20948dedb43b @  129 : 26 f1             Star r10
         0x20948dedb43d @  131 : 4b 15             Dec [21]
         0x20948dedb43f @  133 : 26 f3             Star r8
         0x20948dedb441 @  135 : 25 f1             Ldar r10
 2962 E> 0x20948dedb443 @  137 : 92 80             JumpIfToBooleanFalse [128] (0x20948dedb4c3 @ 265)
 2952 E> 0x20948dedb445 @  139 : a0                StackCheck
 2988 S> 0x20948dedb446 @  140 : 1b 07             LdaImmutableCurrentContextSlot [7]
         0x20948dedb448 @  142 : a5 08             ThrowReferenceErrorIfHole [8]
         0x20948dedb44a @  144 : 26 f0             Star r11
 3015 E> 0x20948dedb44c @  146 : 28 f0 02 16       LdaNamedProperty r11, [2], [22]
         0x20948dedb450 @  150 : 26 f1             Star r10
 3015 E> 0x20948dedb452 @  152 : 56 f1 f0 18       CallProperty0 r10, r11, [24]
         0x20948dedb456 @  156 : 26 f9             Star r2
 3048 S> 0x20948dedb458 @  158 : 1b 06             LdaImmutableCurrentContextSlot [6]
         0x20948dedb45a @  160 : a5 09             ThrowReferenceErrorIfHole [9]
         0x20948dedb45c @  162 : 26 f0             Star r11
 3071 E> 0x20948dedb45e @  164 : 28 f0 0a 1a       LdaNamedProperty r11, [10], [26]
         0x20948dedb462 @  168 : 26 f1             Star r10
 3071 E> 0x20948dedb464 @  170 : 57 f1 f0 f9 1c    CallProperty1 r10, r11, r2, [28]
         0x20948dedb469 @  175 : 26 f8             Star r3
 3089 S> 0x20948dedb46b @  177 : 97 55             JumpIfUndefined [85] (0x20948dedb4c0 @ 262)
 3128 S> 0x20948dedb46d @  179 : 10                LdaTrue
 3147 E> 0x20948dedb46e @  180 : 2c f8 0b 1e       StaNamedProperty r3, [11], [30]
         0x20948dedb472 @  184 : 27 f8 f2          Mov r3, r9
         0x20948dedb475 @  187 : 25 f2             Ldar r9
         0x20948dedb477 @  189 : 97 06             JumpIfUndefined [6] (0x20948dedb47d @ 195)
         0x20948dedb479 @  191 : 25 f2             Ldar r9
         0x20948dedb47b @  193 : 96 10             JumpIfNotNull [16] (0x20948dedb48b @ 209)
         0x20948dedb47d @  195 : 0c 4d             LdaSmi [77]
         0x20948dedb47f @  197 : 26 f1             Star r10
         0x20948dedb481 @  199 : 12 0c             LdaConstant [12]
         0x20948dedb483 @  201 : 26 f0             Star r11
 3185 E> 0x20948dedb485 @  203 : 5e c1 00 f1 02    CallRuntime [NewTypeError], r10-r11
 3169 E> 0x20948dedb48a @  208 : a2                Throw
 3185 S> 0x20948dedb48b @  209 : 28 f2 0c 20       LdaNamedProperty r9, [12], [32]
         0x20948dedb48f @  213 : 26 fb             Star r0
 3185 S> 0x20948dedb491 @  215 : 28 f2 0d 22       LdaNamedProperty r9, [13], [34]
         0x20948dedb495 @  219 : 26 fa             Star r1
 3204 S> 0x20948dedb497 @  221 : 1b 04             LdaImmutableCurrentContextSlot [4]
         0x20948dedb499 @  223 : 26 f0             Star r11
 3217 E> 0x20948dedb49b @  225 : 28 f0 05 24       LdaNamedProperty r11, [5], [36]
         0x20948dedb49f @  229 : 26 f1             Star r10
         0x20948dedb4a1 @  231 : 12 0e             LdaConstant [14]
         0x20948dedb4a3 @  233 : 26 ef             Star r12
         0x20948dedb4a5 @  235 : 27 fb ee          Mov r0, r13
         0x20948dedb4a8 @  238 : 27 f9 ed          Mov r2, r14
 3217 E> 0x20948dedb4ab @  241 : 55 f1 f0 04 26    CallProperty r10, r11-r14, [38]
         0x20948dedb4b0 @  246 : 91 0d             JumpIfToBooleanTrue [13] (0x20948dedb4bd @ 259)
 3272 S> 0x20948dedb4b2 @  248 : 1b 0d             LdaImmutableCurrentContextSlot [13]
         0x20948dedb4b4 @  250 : 26 f1             Star r10
 3272 E> 0x20948dedb4b6 @  252 : 5c f1 fa fb 28    CallUndefinedReceiver2 r10, r1, r0, [40]
         0x20948dedb4bb @  257 : 86 05             Jump [5] (0x20948dedb4c0 @ 262)
 3321 S> 0x20948dedb4bd @  259 : 10                LdaTrue
         0x20948dedb4be @  260 : 26 f4             Star r7
         0x20948dedb4c0 @  262 : 85 89 00          JumpLoop [137], [0] (0x20948dedb437 @ 125)
 3362 S> 0x20948dedb4c3 @  265 : 25 f4             Ldar r7
         0x20948dedb4c5 @  267 : 91 13             JumpIfToBooleanTrue [19] (0x20948dedb4d8 @ 286)
         0x20948dedb4c7 @  269 : 1b 07             LdaImmutableCurrentContextSlot [7]
 3385 E> 0x20948dedb4c9 @  271 : a5 08             ThrowReferenceErrorIfHole [8]
         0x20948dedb4cb @  273 : 26 f1             Star r10
 3412 E> 0x20948dedb4cd @  275 : 28 f1 01 2a       LdaNamedProperty r10, [1], [42]
         0x20948dedb4d1 @  279 : 26 f1             Star r10
         0x20948dedb4d3 @  281 : 0b                LdaZero
 3419 E> 0x20948dedb4d4 @  282 : 65 f1 2c          TestEqualStrict r10, [44]
         0x20948dedb4d7 @  285 : 4f                LogicalNot
 3425 S> 0x20948dedb4d8 @  286 : a4                Return
Constant pool (size = 15)
Handler Table (size = 0)
`

In d8's output, a constant table accessed e.g. by the LdaConstant instruction, was listed under "Constant pool". Node.js' output only contains the size of this table, but not the content. Is there a way to enable outputting this information also?
Thanks.

A: A look at the source:
  os << "Constant pool (size = " << constant_pool()->length() << ")\n";
#ifdef OBJECT_PRINT
  if (constant_pool()->length() > 0) {
    constant_pool()->Print();
  }
#endif

reveals that you'll have to compile with OBJECT_PRINT if you want to print the constant pool entries. In standalone V8, you do that by adding v8_enable_object_print = true to your args.gn. I don't know how to do it in Node. Debug builds of both V8 and Node should enable it by default.

A: Official Node.js will not print constant pool.
You need to rebuild it with modified source of the Node.js.
To do this, go the \deps\v8\src\objects.h in Node.js's source tree and insert the following line.
#define OBJECT_PRINT 1

Then rebuild and use it.


text:
Q: How to delete/not save files when Jupyter notebook in ran with plotly pio.renderers.default = "iframe"? I am plotting a plot using plotly python (inside jupyter notebook) like below-
fig = make_subplots(rows=1, cols=1, vertical_spacing=0.00)

fig.add_trace(
            go.Scatter(
                x=data.index,
                y=data.col_name,
                name="col_name",
                line=dict(color="#90EE90"),
            ),
            row=1,
            col=1,
        )

fig.show()

and I have imported and setup plotly like below
import plotly.io as pio
import plotly.offline as pyo
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Notebook setup
pyo.init_notebook_mode()
pio.renderers.default = "iframe"

Without pio.renderers.default = "iframe" jupyter notebook does not even render the plot.  By using iframe I can render the plot, but it starts saving every plot as HTML file with average of 3-4 MB in size on my local machine. How can I avoid that? Is there any better way to render plotly charts which will spare me all other things to deal with?
Thanks!

A: Try adding these into the import section:
from plotly.offline import plot, iplot, init_notebook_mode
init_notebook_mode(connected=True)
pio.renderers


text:
Q: React-native 0.61.2 with hermes disassembling index.android.bundle I created a release build of my app with react-native 0.61.2 and enabled Hermes.
In my Crashlytics I receive information about crashes along with stacktraces. Perviously I used to apply apktool to extract index.android.bundle from my apk, and it contained js code where I was able to find the issue by stacktrace.
But now using Hermes index.android.bundle seems to contain bytecode rather than js and I wasted a day trying to disassemble it. The last thing I tried was hbcdump tool mentioned in https://github.com/facebook/hermes/blob/master/doc/BuildingAndRunning.md, but all I get is "Error: fail to deserializing bytecode: Wrong bytecode version. Expected 73 but got 62"
What should I do to disassemble index.android.bundle created with Hermes? Any help is highly appreciated!

A: Edit: As of Hermes v0.5.0, there's also a hermes-engine-cli NPM that contains a bytecode disassembler. It is only compatible with the corresponding hermes-engine version (i.e. hermes-engine-cli@0.5.0 works with hermes-engine@0.5.0).
It's still primarily useful for compiler developers, and not for debugging app crashes.

Hermes tools are not backwards compatible, so you need to check out the correct version first. For bytecode version 62, you can checkout the the v0.2.1 release with git checkout v0.2.1. For arbitrary bytecode versions, git log -p include/hermes/BCGen/HBC/BytecodeFileFormat.h will show which commits updated the format to which versions.
Once built, you can use hbcdump myfile.hbc followed by disassemble at the prompt to show a disabled version of the file.
Be aware that hbcdump is intended for developing/debugging compilers, in the same vein as javap -c and objdump -d. Here's the kind of output you can expect:
Function<fizzbuzz>1(1 params, 22 registers, 0 symbols):
Offset in debug table: src 0xd, vars 0x0
fizzbuzz.js[1:21]
    LoadConstZero     r11
    LoadConstUInt8    r10, 15
    LoadConstUInt8    r9, 3
    LoadConstString   r8, "Fizzbuzz"
    LoadConstString   r7, "Fizz"
    LoadConstString   r6, "Buzz"
    GetGlobalObject   r5
    LoadConstUndefined r0
    LoadConstUInt8    r4, 1
    LoadConstUInt8    r3, 100
    LoadConstUInt8    r2, 5
    LoadConstZero     r1
L2:
fizzbuzz.js[1:21]
    Mod               r12, r1, r10
    Mov               r13, r8
    JStrictEqual      L1, r12, r11
    Mod               r12, r1, r9
    Mov               r13, r7
    JStrictEqual      L1, r12, r11
    Mod               r12, r1, r2
    Mov               r13, r6
    JStrictEqual      L1, r12, r11
    AddEmptyString    r13, r1
L1:
fizzbuzz.js[8:5]
    TryGetById        r12, r5, 1, "print"
    Call2             r12, r12, r0, r13
    AddN              r1, r1, r4
    JLessN            L2, r1, r3
    Ret               r0


text:
Q: How to insert appendix after references in Rmd using Rstudio? I am using Rstudio, to create a pdf / html document from an Rmd file. The header looks sth like this:
title: "Title"
author: "Me"
date: "`r format(Sys.time(), '%B %d, %Y')`"
bibliography: bibliography.bib
output:
  html_document:
    toc: true
    number_sections: true

Now, I have some sections, and then include the references. After that, an appendix should follow, but I encounter the exact same problem as described here: Pandoc insert appendix after bibliography
There is a fixed solution in this thread, but I have no idea how I can do that within RStudio directly. To get the document, I just press the "Knit html" button, and do not run any pandoc commands myself. So where should I put the
--include-after-body

part, and how should the appendix rmd file look like?

A: As noted in the rmarkdown manual, you could use this syntax:
---
output:
  html_document:
    includes:
      after_body: appendix.md
---

This is equivalent to the general way to add arbitrary pandoc arguments to a Rmd file:
---
output:
  html_document:
    pandoc_args: ["--include-after-body=appendix.md"]
---

A: The following might be easier; works if you knit to PDF, Word or HTML:
Everything I wanted to say in the main document.

# References

\newpage
# Appendix

Some details that will bore the readers of the main document.

In the original post, this was also posted as an answer (few years after current question was asked): see https://stackoverflow.com/a/44294306/8234333 and https://stackoverflow.com/a/16428699/8234333


text:
Q: Post thumbnail with checkbox in WordPress I try to make a checkbox in WordPress admin. I would like if the checkbox is checked, the post thumbnail is aperar. But my code is not functional. What is the problem?
Thanks a lot.
My checkbox code:
add_action('add_meta_boxes', 'add_ot_meta_box');
function add_ot_meta_box() {
    add_meta_box('ot-meta-box', esc_html__('Post status', 'post_status'), 'ot_meta_box_markup', 'page', 'side', 'high', null);
    add_meta_box('ot-meta-box', esc_html__('Post status', 'post_status'), 'ot_meta_box_markup', 'post', 'side', 'high', null);
}
//create the boxes html markup
function ot_meta_box_markup() {
    global $post;
    $checkbox_value = get_post_meta($post->ID, 'ot-meta-box-checkbox', true);
    wp_nonce_field(basename(__FILE__), 'ot-meta-box-nonce');
    ?>

            <input id="ot-meta-box-checkbox" type="checkbox" name="ot-meta-box-checkbox" value="1" <?php checked( $checkbox_value, 1); ?>/>
            <?php esc_html_e('Post status') ?>

    <?php
}
// save checkbox meta
function save_ot_meta_box($post_id) {
    if (!isset($_POST['ot-meta-box-nonce']) || !wp_verify_nonce($_POST['ot-meta-box-nonce'], basename(__FILE__)))
        return $post_id;
    if(!current_user_can("edit_post", $post_id))
        return $post_id;
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
    if( isset( $_POST['ot-meta-box-checkbox'] ) ){
        update_post_meta( $post_id, 'ot-meta-box-checkbox', true );
    } else{
        update_post_meta( $post_id, 'ot-meta-box-checkbox', false );
    }
}
add_action('save_post', 'save_ot_meta_box', 10, 3);

And my callback code in single:
<?php $otoptions = get_option('ot-meta-box-checkbox');
if ( '' !== get_the_post_thumbnail() && ($otoptions['ot-meta-box-checkbox'] !== '1') && is_single() ) : ?>

            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail( 'my-featured-image' ); ?>

    <?php endif; ?>

A: Ok, I found it:
<?php $checkbox_value = get_post_meta($post->ID, 'ot-meta-box-checkbox', true);
if ( '' !== get_the_post_thumbnail() && ($otoptions['ot-meta-box-checkbox'] !== '1') && is_single() ) : ?>

            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail( 'my-featured-image' ); ?>

    <?php endif; ?>


text:
Q: save file to folder from webService Good afternoon, I have the following data in a table in Sql
Comprobante Categoria
    603552       A
    624997       A
    651880       A
    672298       C
    615985       C
    613804       C
    617970       A
    625688       A
    689463       B
    611686       B

Then generate a console application that queries the WebService by taking the voucher number and downloading a .pdf, but it blocks me, this application has to generate a folder by Category by taking the value of the sql query from the Vouchers table and inside each folder download the invoice corresponding to that category so the invoices are sorted by category within each folder. I appreciate all the help.
static void Main(string[] args)
        {
            string url = null;
string strSQL = "SELECT numeroComprobante,categoria FROM Comprobantes";

            SqlConnection con = new SqlConnection("********");
            SqlCommand cmd = new SqlCommand(strSQL, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                var request = new Services.consultarDocumento()
                {
                    request = new Services.requestConsultaDocumento()
                    {

                        numeroComprobante = reader["numeroComprobante"],
                    }

                };

            var address = new EndpointAddress(new Uri("*********"));

            BasicHttpBinding binding = new BasicHttpBinding();
            binding.Name = "basicHttpBinding";
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.Security.Mode = BasicHttpSecurityMode.None;

            var client = new Services.ConsultaDocumentoClient(binding, address);

            var response = client.consultarDocumento(request);

            var Factura= @return.Documento;
            }

            reader.Close();
            con.Close();

    }
  }


text:
Q: How to add text before the subequations? I am translating a book into Chinese, and it doesn't provide the latex file of the book.
How to add text before the subequations?

This is my code for it
\parbox{8.5em}{
    predictor: \\
    Kalman gain: \\
    corrector:
}
\parbox{8.5em}{
\begin{subequations}
\begin{align}
    \check{\mathbf{P}}_k &= ...\\
    \check{\mathbf{x}}_k &= ...\\
    \mathbf{K}_k  &= ...\\
    \hat{\mathbf{P}}_k  &= ...\\
    \hat{\mathbf{x}}_k  &= ...
\end{align}
\end{subequations}
}

It's not the same as the version as the book shown..

A: A quick solution using eqnarray (not very recommended):
\documentclass{article}
\usepackage{amsmath,multirow}
\begin{document}

\begin{subequations}
\begin{eqnarray}
 \multirow{2}{*}{predictor:}  &\Check{\mathbf{P}}_k = ...\\
                              &\Check{\mathbf{x}}_k = ...\\
 \text{Kalman gain:}          &\mathbf{K}_k       = ...\\
 \multirow{2}{*}{corrector:}  &\hat{\mathbf{P}}_k = ...\\
                              &\hat{\mathbf{x}}_k = ...
\end{eqnarray}
\end{subequations}

\end{document}

A better option using align:
\begin{subequations}
\newcommand{\hleft}{\hspace{-6em}}
\begin{align}
 \multirow{2}{*}{predictor:} &\hleft& \Check{\mathbf{P}}_k &= ...\\
                             &\hleft& \Check{\mathbf{x}}_k &= ...\\
 \text{Kalman gain:}         &\hleft& \mathbf{K}_k         &= ...\\
 \multirow{2}{*}{corrector:} &\hleft& \hat{\mathbf{P}}_k   &= ...\\
                             &\hleft& \hat{\mathbf{x}}_k   &= ...
\end{align}
\end{subequations}

A: Two solutions with \alignat and mathtools, and some manual adjustments:
\documentclass{article}
\usepackage{array}
\usepackage{mathtools}

\begin{document}

\begin{subequations}
  \begin{alignat}{2}
                                                                       & & \check{\mathbf{P}}_k & = ... \\[-1.2ex]
    \ArrowBetweenLines[\llap{\raisebox{-0.8ex}[0pt][0pt]{predictor:}}] & \qquad & \check{\mathbf{x}}_k & = ... \\[0.5ex]
    \llap{Kalman gain:\quad} & & \mathbf{K}_k & = ... \\
                                                                       & & \hat{\mathbf{P}}_k & = ... \\[-1.2ex]
    \ArrowBetweenLines[\llap{\raisebox{-0.8ex}{corrector:}}] & & \hat{\mathbf{x}}_k & = ...
  \end{alignat}
\end{subequations}

\begin{subequations}
  \begin{alignat}{2}
                                                                                & & \check{\mathbf{P}}_k & = ... \\
                                                                                & & \check{\mathbf{x}}_k & = ... \\
    \llap{\raisebox{1.2ex}[0pt][0pt]{\setlength{\extrarowheight}{3ex}\begin{tabular}{r}predictor: \\[-0.5ex]Kalman gain: \\corrector:
        \end{tabular}}} & \qquad & \mathbf{K}_k & = ... \\
                                                                                & & \hat{\mathbf{P}}_k & = ... \\
                                                                                & & \hat{\mathbf{x}}_k & = ...
  \end{alignat}
\end{subequations}

\end{document}


text:
Q: How to load a local web page in javascript I'm trying to load a local web page executing:
var html = document.open('google.html');
document.documentElement.innerHTML = html;

It loads the page but it's not well formatted and images won't display. How could I load the entire contents?
Thanks

A: Most likely this is because external resources (images, style sheets, js files etc) are allowed to have relative urls. Any relative urls need to be fully qualified for the page to load properly.

A: If you want to replace the content of the page by another one, simply do
document.location.href="http://google.com";

If you want to open a local page named google.html do
document.location.href=document.location.href.splitOnLast('/')[0]+"/google.html";

This will ensure that linked resources can be loaded as the relative paths will be accorded to the location of the page. Don't change the content yourself.


text:
Q: Does ng build avoid node_modules code duplication? We a have a large angular application and each module that the app uses is in a seperate repo and is build to be imported in the main application for example.
I have a npm library lets call it lib1. Now my two modules module1 and module2 use that library.
I make a build using ng build of module1 and module2. Then I add these modules in my main app in the app.module.ts file and use them in the app. Now If I build my main app will it include the minified code of lib1 twice or the compiler will recognize and package the lib1 only once to be used by the app. My main concern is the package size. Is it going to increase? Would it be better if I don't keep the modules in separately and directly include their code in the main rather than their builds and build the main app once.

A: I've tested that it avoids the duplication, so for example if you are using lodash in multiple modules and then you include those modules into the main app then the lodash could should only be included once as long as the version of lodash is the same, otherwise not. Hence it's important to keep your versions same for all the modules

A: So after testing myself I've seen that it avoids the duplication, so for example if you are using lodash in multiple modules and then you include those modules into the main app then the lodash could should only be included once as long as the version of lodash is the same, otherwise not. Hence it's important to keep your versions same for all the modules


text:
Q: Enable ACL on ArchLinux Hi i'm trying to enable ACL on my filesystem. this are the steps

*

*install acl with # pacman -S acl

*edit /home entry on /etc/fstab

/dev/sdb4    /home       ext4        defaults,acl,noatime        0 2

*

*remount partition # mount -o remount /home
even after reboot the acl is not displayed for the mount command
/dev/sda4 on /home type ext4 (rw,noatime,data=ordered)

A: I don't think you have to explicitly set ACL as a mount option to get it to work. None of my mounts have it explicitly set:
$ more /etc/fstab
/dev/mapper/vg_grinchy-lv_root /                       ext4    defaults        1 1

Here's my mount info:
$ mount
/dev/mapper/vg_grinchy-lv_root on / type ext4 (rw)

And yet I'm able to make use of ACL functionality on the above mounted partition.
Accessing the mounted partition:
$ df -h .
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_grinchy-lv_root
                       50G   28G   20G  58% /

Am able to run getfacl:
$ getfacl .
# file: .
# owner: root
# group: root
# flags: --t
user::rwx
group::rwx
other::rwx


text:
Q: groovy pass map to javascript from controller I am fairly new to Grails MVC and javascript.
I am encountering a problem wherein i want to pass a map object from the controller to a javascript function.
Currently two parameters are passed to the javascript function which are comma seperated and this works fine
eg. someControllerFunction() {

    variableLink = "j-javaScriptFunction-${stringArgs1},${stringArgs2}" // This is a link for an ajax call

}

The javascript function structure looks like this
function someJavaScriptFunction (details) {

    var d = details.split(",");
    var strintArgs1 = d[0];
    var stringArgs2 = d[1];

    ajax":{
                    "url":"${request.contextPath}/controller/methodInController?strintArgs1=" + strintArgs1 + "&stringArgs2=" +stringArgs2
                    },
}

The Controller function which is called in the ajax currently looks like this
methodInController (String strintArgs1,String strintArgs2){

    //some operation
}

Now i want to pass a map object from the controller function to the javascript function but i am not able to as the javascript considers the map as an invalid String object.
Below are the changes i have made to the three functions but i am getting an error during the ajax call saying "Uncaught SyntaxError: Unexpected string"
eg. someControllerFunction() {

    variableLink = "j-javaScriptFunction-${stringArgs1},${stringArgs2},${mapArg}" // This is a link for an ajax call

}

The map object looks like this
mapArg = [a:[],b:[],c:[],d:[]]

The javascript function structure looks like this
function someJavaScriptFunction (details) {

    var d = details.split(",");
    var strintArgs1 = d[0];
    var stringArgs2 = d[1];
    var mapArg = d[2];

    ajax":{
                    "url":"${request.contextPath}/controller/methodInController?strintArgs1=" + strintArgs1 + "&stringArgs2=" +stringArgs2 + "&mapArg=" +mapArg
                    },
}

The Controller function which is called in the ajax currently looks like this
methodInController (String strintArgs1, String strintArgs2, Object mapArg){

    //some operation
}

It might be something to do with the way i am passing it to the javascript function but i am not able to figure out the exact reason.
Could anyone please help me to understand what am i doing wrong.
Thanks in advance

A: It looks like you might have to cast the map to JSON first (which would explain why its a string). See this answer: https://stackoverflow.com/a/2064341/1902587


text:
Q: If i run this program even if i give the input as 0 it countinuosly getting the values in it? #include<stdio.h>
#include<conio.h>
#include<malloc.h>

void main()
{
    struct node
    {
        int data;
        struct node *next;
    };
    struct node *head,*temp;
    int x;
    clrscr();
    head=(struct node *) malloc (sizeof(struct node));
    temp=head;
    while(temp!=NULL)
    {
        scanf("%d",x);
        temp->data=x;
        if(x==0)
        {temp->next=NULL;}
        else
        {temp->next=(struct node *) malloc (sizeof(struct node));}
        temp=temp->next;
    }
}

I was writing a code for a simple linke list program ... I can successfully run the program but when I press 0 the program is not stopping..

A: Firstly, your scanf is wrong. it needs to be passed by reference:
scanf("%d", &x);

Secondly, you should set x to something other than 0 before scanf'ing it, just in case. The way it is written, you have no exit condition in your loop.
You could try using gdb and stepping it line by line if you want to get right into it.
Hope this helps


text:
Q: Gradle Build - Execution failed for task ':sonarqube' can't be indexed twice I am getting an error "File can't be indexed twice" in gradle build for sonar. Do i have to add any inclusion/exclusion property for sonar? Any help greatly appreciated.
If I take out "src/main/java" in test under sourceSets, I am getting compilation error for junit test cases.
This is how my build.gradle file content look,
group = 'groupid'
apply plugin: 'gradleFortify'
apply plugin: 'org.sonarqube'
apply plugin: 'eclipse'
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'groovy'
//apply plugin: "java-library-distribution"
//apply plugin: 'distribution'

version=version
sourceCompatibility = 1.8

repositories {
        maven {
        url "artifactory"
            credentials {
            }
        }
        sonarqube {
            properties {
                property 'sonar.sourceEncoding', 'UTF-8'
                property "sonar.exclusions", ["**/*Test.java"]
            }
        }
}

buildscript {
    repositories {
        maven {
        url "artifactory"
            credentials {
            }
        }
    dependencies {
        classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7'
        classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.0'

    }
}

sourceSets {
    main {
        java {
            srcDirs = ['src/main/java']
        }
    }
    test {
        java.srcDirs = ['src/test/java','src/main/java']
    }
}

dependencies{

}
 task preclean(type: Delete) {
     delete 'build'
 }
 task jcompile(type: JavaCompile) {
     dependsOn preclean
     source = fileTree(dir: 'src/main/java', include: '**/*.java')
     destinationDir = file('build/classes')
     sourceCompatibility = '1.8'
     targetCompatibility = '1.8'
     classpath = configurations.runtime
 }

 task copyResources( type: Copy ) {
 }

 task copyClasses( type: Copy ) {
 }

 jar {
    dependsOn jcompile
    archiveName = 'prj1.jar'
    manifest {
        attributes('Implementation-Title': project.name,
                   'Implementation-Version': project.version)
    }
     into('lib') {
         println "includeInJar: " + configurations.runtime.collect { File file -> file }
         from configurations.runtime
     }
 }
// jar.finalizedBy(jarTask) { }

sonarqube {
    properties {
        property "sonar.projectName", "prj-${version}"
        property "sonar.projectKey", "prj-${version}"
    }
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}
jacocoTestReport {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it, includes: ['com/**'])
        })
    }
}

A: The issue described is most likely caused by custom tasks for what Gradle offers out of the box:

*

*Task preclean deletes probably too much. Use clean instead.

*Task jcompile compiles the main Java sources which basically duplicates compileJava. The jar task, by default, already depends on compileJava.

I suggest the following:

*

*Remove sourceSets configuration since you're following the convention of using src/main/java and src/test/java.

*Remove custom tasks preclean and jcompile.

*Cleanup your build script and remove empty tasks copyClasses and copyResources as well as no-op assignment version=version.

*From there on, should you have requirements to customize the build, try to resort to what Gradle offers already. You may want to read Building Java & JVM projects first.


text:
Q: How to visualize matplotlib animation in Jupyter notebook I am trying to create a racing bar chart similar to the one in the link (https://towardsdatascience.com/bar-chart-race-in-python-with-matplotlib-8e687a5c8a41).
However I am unable to see the animation in my Jupyter notebook
code
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML

df = pd.read_csv('https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/fa018b25c24b7b5f47fd0568937ff6c04e384786/city_populations',
                 usecols=['name', 'group', 'year', 'value'])

current_year = 2018
dff = (df[df['year'].eq(current_year)]
       .sort_values(by='value', ascending=True)
       .head(10))

colors = dict(zip(
    ['India', 'Europe', 'Asia', 'Latin America',
     'Middle East', 'North America', 'Africa'],
    ['#adb0ff', '#ffb3ff', '#90d595', '#e48381',
     '#aafbff', '#f7bb5f', '#eafb50']
))
group_lk = df.set_index('name')['group'].to_dict()

fig, ax = plt.subplots(figsize=(15, 8))
def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max() / 200
    for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):
        ax.text(value-dx, i,     name,           size=14, weight=600, ha='right', va='bottom')
        ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')
        ax.text(value+dx, i,     f'{value:,.0f}',  size=14, ha='left',  va='center')
    # ... polished styles
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
    ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777')
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x', colors='#777777', labelsize=12)
    ax.set_yticks([])
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0, 1.12, 'The most populous cities in the world from 1500 to 2018',
            transform=ax.transAxes, size=24, weight=600, ha='left')
    ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right',
            color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
    plt.box(False)

draw_barchart(2018)

import matplotlib.animation as animation
from IPython.display import HTML
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1968, 2019))
HTML(animator.to_jshtml())

Below is what I tried using and the errors
HTML(animator.to_jshtml())  <-- Static output with buttons unable to visualize animation
plt.rcParams["animation.html"] = "jshtml"  <- no error and output
HTML(animator.to_html5_video())  <---Requested MovieWriter (ffmpeg) not available

Note I have FFmpeg installed in my system.
Can you help me with the issue


text:
Q: Copy an entire file to a specific location I have a problem whit copying a file from one location to another. I don't want to copy the content of the file, i need to copy the entire file also his name.
Something like this :
source= "C:\src\test.txt"
destination="C:\dest" //and in folder dest should appear the file test.txt
It's easy to copy the content of file but whit this i don't have any ideea and the internet doesn't help me.
If can someone help me it will be just awesome. Thx.
#include <iostream>
using namespace std;

int main()
 {
 size_t BUFFER_SIZE = 4096;

char buf[BUFSIZ];
size_t size;

FILE* source = fopen("data.in", "rb");
FILE* dest = fopen("data.out", "wb");

// clean and more secure
// feof(FILE* stream) returns non-zero if the end of file indicator for stream is set

while (size = fread(buf, 1, BUFSIZ, source)) {
    fwrite(buf, 1, size, dest);
}

fclose(source);
fclose(dest);

return 0;

}


text:
Q: For loop in forms I want my form to display 1,2,3,4,5
but all it does is replace the text again and again.
for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text = Convert.ToString(i);
}

I know it's because of the .Text that it always overrides itself. But how can i leave them in the form so it will display:
1
2
3
4
5

A: The problem is that in your loop, you're completely replacing the text with each iteration. So the text is left with whatever the last value of i was.
Try putting adding to the current text (with +=) and putting a new line (Environment.NewLine or "\n") between each number:
for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text += Environment.NewLine + Convert.ToString(i);
}

Or alternatively, a little Linq can make your life a lot easier:
richTextBox1.Text = string.Join(Environment.NewLine, Enumerable.Range(1, 5));

A: Try this:
for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text += Convert.ToString(i) + Environment.NewLine;
}

Edit:
Just noticed that you want to print one number per line.  \n is the NewLine character and will give you a carriage return on the end of the line.
Environment.NewLine is also a good choice, because it will give you the newline character based on the environment the app is running in.

A: append text, don't just assign it.
richTextBox1.Text += Convert.ToString(i);

this is equivelant of
richTextBox1.Text = richTextBox1.Text + Convert.ToString(i);

A: This will also do:
for (int i = 1; i <= 5; i++)
{
    richTextBox1.AppendText(i + Environment.NewLine);
}

A: richTextBox1.AppendText(i.ToString()+Environment.NewLine);


text:
Q: Merge или Rebase в GIT Как известно в GIT существует два основных способа объединить изменения из двух разных веток:

*

*Слияние (Merge);

*Перемещение комитов (Rebase).

Вопрос: зачем перемещать комиты (Rebase), когда есть операция Merge, которая приводит к тому же результату? Или я что-то не правильно понимаю?

A: Результат операций merge и rebase - разный. И я говорю не о состоянии файлов в последнем коммите, а об истории в репозитории.
merge порождает новый коммит-слияние, в то время как rebase изменяет сам переносимый коммит. Если точнее, то создается дубликат с такими же свойствами. Изменить коммит нельзя. Но если кроме переносимой ветки на коммит никто не ссылался, то он удаляется, и это выглядит как изменение.
Преимущество merge перед rebase в том, что легко отделить изменения по задаче, от изменений в процессе слияния. Но недостаток в том, что захламляется история.
Важность этих различий получается понять, когда нужно по относительно давней истории (т.е. от, что программисты сами уже не помнят) понять кто и главное зачем сделал конкретное изменение. Например, при помощи blame или bisect
Если над проектом я работаю один, и изменения достаточно просты - однозначно делаю rebase
Если изменения серьезные и гарантированны конфликты, то однозначно merge.
А вот если разработчиков несколько, но изменения просты, то тут нужно выбрать стратегию, удобную для всей команды.


text:
Q: Two-way binding Angular component property to AngularJS view So we have an application written in AngularJS, slowly migrating to Angular component-wise.
I'm now building a simple reusable component that is basically a dropdown box with a label. This is of course in Angular - so I downgrade it into AngularJS, then use it in an AngularJS view.
How can I now two-way bind a property from the component (let's call it MyDropdown.CurrentValue) to a scope variable of the AngularJS view (let's call it $scope.numberOfCarsOwned)?
The component of course has both @Input() CurrentValue: any; and @Output() CurrentValueChange: EventEmitter<any>, bound to the inner dropdown box.
In Angular, I'd just go <MyDropdown [(CurrentValue)]="numberOfCarsOwned" />, but how do I do this when integrating the component (downgraded as a directive) into my AngularJS view?

A: So it turns out, once you know how to do it it's totally easy:
In the AngularJS view, you use it as if you were in Angular:
<MyComponent
  [(CurrentValue)]="numberOfCarsOwned"
></MyComponent>

This will automagically bind the CurrentValue (using the component's CurrentValueChange) to the view's $scope.numberOfCarsOwned.


text:
Q: How to handle Service unavailable scenarios with Jersey REST I have a jersey RESTful service integraed with Spring.The base url mapped in web.xml is /rest/*
My service class is below:
@Resource
@Scope("request")
@Path("/service/")
@Component
public class ServiceController {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getApiDetails() {
        return Response.ok("area").build();
    }

    @Path("/area")
    @GET
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces(MediaType.APPLICATION_JSON)
    public Response processConvertCurrency(
        @QueryParam("length") String length,
        @QueryParam("breadth") String breadth) {
        ......
    }
}

When the following url hit, it will show the available services
<baseurl>/rest/service

output : area

Also <baseurl>/rest/service/area?length=10&breadth20 will return its output correctly.
My requirement is that when someone hit <baseurl>/rest/service/volume it should output like
Service is unavailable message.

Since only area is available How can I do that.Please help..(currently 404 error is displayed)

A: JAX-RS (Jersey) will throw a NotFoundException if the resource isn't found. This exception will be mapped to a response containing a status code 404 Not Found (with no entity body), as this is normal REST behavior. But we are also allowed to change the response to our liking by creating an ExceptionMapper. There we can set an entity body. You might have something like
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class NotFoundExceptionMapper
        implements ExceptionMapper<NotFoundException> {
    final String html
            = "
"
            + "Service is unavailable message."
            + "
"
            + ""
            + "Check out Stackoverflow";

    @Override
    public Response toResponse(NotFoundException e) {
        return Response.status(Status.NOT_FOUND)
                .entity(html).build();
    }
}

We just need to register this provider with the Jersey (JAX-RS) application (possibly through the ResourceConfig).
It seems as long as we have a entity body with the response, we'll get

Instead of a

*

*See Exception Mapping

*Note: you could just as easily simply map 404 to an error page of your choosing, through the web.xml, without the need for any ExceptionMapper. Something like
<error-page>
    <error-code>404</error-code>
    <location>/error.html</location>
</error-page>

See here for more details

UPDATE

"One more doubt, when I set it, for all 404 same message. Can we customize too based on the request url or some otherway.(My intention is to provide different message for different services)"

You can inject different contexts into the ExceptionMapper. For instance UriInfo, and get the requested path
@Context
UriInfo uriInfo;

@Override
public Response toResponse(NotFoundException e) {
    String html
        = "
"
        + "Service is unavailable message."
        + "
"
        + ""
        + "Check out Stackoverflow";
    html += "
Requested URI: " + uriInfo.getAbsolutePath() + "
";
    return Response.status(Status.NOT_FOUND)
            .entity(html).build();
}

There are other contexts that can be injected. Whether they are inject-able into a class depends on the class (resource class / provider class) and its application scope (among other things). But here's a list of inject-able contexts (with the @Context annotation).

*

*javax.ws.rs.core.HttpHeaders

*javax.ws.rs.core.UriInfo

*javax.ws.rs.core.Request

*javax.servlet.HttpServletRequest

*javax.servlet.HttpServletResponse

*javax.servlet.ServletConfig

*javax.servlet.ServletContext

*javax.ws.rs.core.SecurityContext

*Possible more :-)


text:
Q: Spark Streaming - Calling REST API vs Building Functionality Natively for Spark Streaming We have a specific functionality for managing timeseries data. The funtionality is already offered as REST API and runs on Cloudfoundry. We want to offer the support for ingesting timeseries data using Spark Streaming and kafka so that the solution is more scalable and robust.
What are the disadvantages of calling the REST API from spark streaming intead building the functionality natively in spark.

A: I would argue that if your REST API can support the throughput from Spark Streaming, the REST API can support the throughput directly. In which case, you don't actually need Spark Streaming at all.  If what you need is a buffer for unexpected spikes, there are simpler ways to achieve that than Spark Streaming.
To address your question more directly, calling the REST API adds latency and an additional failure case to the Spark Streaming pipeline.  Implementing your logic in Spark Streaming directly adds code complexity and possible duplication. And both options add operational complexity.


text:
Q: How to update path from within instance method? var mongoose = require('mongoose');

var schema = new mongoose.Schema({
  name: String
});

// this is the instance method which should update the document name.
schema.method('changeName', function(name) {
  this.name = name;
});

var Model = mongoose.model('Person', schema);

var doc = new Model();
doc.name = 'initial value';

// this should change the doc's name to `new value`.
doc.changeName('new value');

doc.save(function(err, obj) {
  // this will print `initial value` while it should print `new value`.
  console.log(obj.name);
});

A: Test your codes as below
mongoose.connection.on('connected', function() {
    isSeenConnected = true;
    console.log('Establish connection to mongoDB');
    saveData();
});

var schema = new mongoose.Schema({
  name: String
});

// this is the instance method which should update the document name.
schema.method('changeName', function(name) {
  this.name = name;
});

var Model = mongoose.model('Person', schema);

function saveData() {
    var doc = new Model();
    doc.name = 'initial value';

    doc.changeName('new value');

    console.log(doc);
    doc.save(function(err, obj) {
      console.log(obj.name);
    });
}

Output:
Establish connection to mongoDB
{ name: 'new value', _id: 56adb56e7bb2f49f02d18d8e }
Open connection to mongoDB
new value

It seems work well...