text:
Q: How to refresh an event changed into fullcalendar bootstrap? I change an event into fullcalendar bootstrap into modal then clik on event.
I change the title, but then click on submit modal button the event isn't refresh, I need F5 to reload page..
How can I refresh my event changed automatically then click submit button?
My code is:
$('#submitButtonEdit').on('click', function(e){
    // We don't want this to act as a link so cancel the link action
    e.preventDefault();
    doSubmitEdit();
});

function doSubmitEdit(){
    $("#createEventModalEdit").modal('hide');
    console.log($('#apptStartTime').val());
    console.log($('#apptEndTime').val());
    console.log($('#apptAllDay').val());
    console.log($('#id').val());

    var title = $('#patientName2').val();
    var start = $('#apptStartTime').val();
    var end = $('#apptEndTime').val();
    var allDay = $('#apptAllDay').val();
    var idEvent = $('#id').html();

    $.ajax({
        url: 'process.php',
        data: 'type=changetitle&title='+title+'&eventid='+idEvent,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                var event_obj = $('#calendar').fullCalendar('clientEvents', idEvent);
                $('#calendar').fullCalendar('updateEvent', event_obj);
            }
        },
        error: function(e){
            alert('Error processing your request: '+e.responseText);
        }
    });

    $("#calendar").fullCalendar('renderEvent', {
        title: $('#patientName2').val(),
        start: new Date($('#apptStartTime').val()),
        end: new Date($('#apptEndTime').val()),
        allDay: ($('#apptAllDay').val() == "true"),
    }, true);
}

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

Crear tarea

        <form id="createAppointmentForm" class="form-horizontal">

                Tarea:

                    <input type="text" name="patientName2" id="patientName2" tyle="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="["Value 1","Value 2","Value 3"]">
                    <input type="hidden" id="apptStartTime"/>
                    <input type="hidden" id="apptEndTime"/>
                    <input type="hidden" id="apptAllDay" />

                Inicio:

                Fin:

                Inicio:

        </form>

        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
        <button type="submit" class="btn btn-primary"     id="submitButtonEdit">Save</button>

A: Pseudo code:
Get the event object
Open Modal, edit
update the event Object with the data from the modal
update Calendar with event Object
Send out Ajax

Remarks:

*

*$('#calendar').fullCalendar('clientEvents', idEvent); returns an
array of events, even if filtered for one ID.

*$("#calendar").fullCalendar('renderEvent', {... creates a new event on the timeline

Some changes:
function doSubmitEdit(){
    // get event object
    var event_obj_arr = $('#calendar').fullCalendar('clientEvents', idEvent);
    var event_obj = event_obj_arr[0];

    // edit
    $("#createEventModalEdit").modal('hide');
    console.log($('#apptStartTime').val());
    console.log($('#apptEndTime').val());
    console.log($('#apptAllDay').val());
    console.log($('#id').val());

    // update event object properties
    event_obj.title = $('#patientName2').val();
    event_obj.start = moment($('#apptStartTime').val());
    event_obj.end = moment($('#apptEndTime').val());
    event_obj.allDay = $('#apptAllDay').val() || false;
    // var idEvent = $('#id').html(); NEVER CHANGE THIS!

    // update calendar, you may put this line into success method
    $('#calendar').fullCalendar('updateEvent', event_obj);

    // post to server
    $.ajax({
        url: 'process.php',
        data: 'type=changetitle&title='+title+'&eventid='+idEvent,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                // nothing to do here
            }
        },
        error: function(e){
            alert('Error processing your request: '+e.responseText);
        }
    });
}

==> this is not yet tested!


text:
Q:  Backgrounds floating apart/ over each other I'm trying to make a landing page with several different sections like chartbeat.com. I've done the following in my HTML:

        This is the Payroll Section

        This is the Point of Sale Section

and this is what my CSS looks like:
    .payroll {
    background-image: url('../img/payroll_bg.jpg');
    background-repeat: repeat-x;
    height: 100%;
}

.pos {
    background-image: url('../img/pos_bg.jpg');
    background-repeat: repeat-x;
    height: 100%;
}

The problem is the sections are floating apart, leaving a large gap between them. See picture. If I shrink the window, or inspect element, the sections float up to overlap each other.
Any ideas? Thanks!

A: create a .wrapper div and use this:
.wrapper {
width:100%; /* you can define as you want */
height:100%; /* you can define as you want */
position:relative;
}
.payroll {
background-image: url('../img/payroll_bg.jpg');
background-repeat: repeat-x;
height: 100%;
position:absolute;
top:0;
left:0;
width:0 auto;
}
.pos {
background-image: url('../img/pos_bg.jpg');
background-repeat: repeat-x;
height: 100%;
position:absolute;
top:0;
left:0;
opacity:0.9;
width:0 auto;
}

A: I think the problem is being caused by your 100% heights. You need to set a height on the parent element because any percentage dimensions are based on the size of it.
Moving away from percentages, like you have done, would also do the trick.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make style=verbose's short citations for @online more verbose I need to change the short citation. Right now it looks as follows:

It should look like:

Gates, Bill and Melinda Gates Foundation, May 4. 2018, "Save the world..."

The "..." should appear after 3 or 4 words if that is technically possible.
How can I do that?
 \RequirePackage{filecontents}
    \begin{filecontents*}{\jobname.bib}
    @online{gates,
        author       = {Bill Gates},
        title        = {Save the world!},
        url          = {https://www.gatesfoundation.org/de/},
        date         = {2016-07-04},
        organization = {Bill and Melinda Gates Foundation},
    }
    \end{filecontents*}

\documentclass{article}

\usepackage[style=verbose]{biblatex}
\addbibresource{\jobname.bib}

\begin{document}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\footcite{gates} sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. \footcite{gates}

\printbibliography
\end{document}

A: Similarly to Custom type disappears in subsequent citations you need to branch the code for cite:short to obtain a different format for @online entries. A short version of the title can be specified in the shorttitle field. But that would require manual intervention, with Biber's sourcemapping you can automate that. I strongly suggest to scrutinise the output carefully in that case since the code is quite naive and chops off everything at the third word.
The MWE builds on the code from Move date before title in bibliography using biblatex to make the output for the full citation match the style of the short citation.
\documentclass{article}

\usepackage[style=verbose, autocite=footnote]{biblatex}

\DeclareFieldFormat[online]{shorttitle}{\mkbibquote{#1\dots\isdot}}
\newbibmacro*{cite:short:online}{%
  \printnames{labelname}%
  \setunit{\addcomma\space}%
  \printlist{organization}%
  \setunit{\addcomma\space}%
  \printdate
  \setunit{\addcomma\space}%
  \printtext[bibhyperlink]{%
    \iffieldundef{shorttitle}
      {\printfield[citetitle]{labeltitle}}
      {\printfield{shorttitle}}}}

% cite:short is really 'cite:subsequent'
\renewbibmacro*{cite:short}{%
  \ifbibmacroundef{cite:short:\strfield{entrytype}}
    {\printnames{labelname}%
     \setunit*{\printdelim{nametitledelim}}%
     \printtext[bibhyperlink]{%
       \printfield[citetitle]{labeltitle}}}
    {\usebibmacro*{cite:short:\strfield{entrytype}}}}

\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite=false]{
      \step[fieldsource=title, match=\regexp{\A(\w+\s+){2}(\w+)}, final]
      \step[fieldset=shorttitle, origfieldval, final]
      \step[fieldsource=shorttitle, match=\regexp{\A(\w+\s+)(\w+\s+)(\w+).*}, replace={$1$2$3}]
    }
  }
}

\DefineBibliographyStrings{english}{
  urlseen = {visited at}
}

\DeclareFieldFormat{urldate}{\bibstring{urlseen}\space#1}

\DeclareListWrapperFormat{organization}{\mkbibemph{#1}}

\DeclareBibliographyDriver{online}{%
  \usebibmacro{bibindex}%
  \usebibmacro{begentry}%
  \usebibmacro{author/editor+others/translator+others}%
  \newunit\newblock
  \printlist{organization}%
  \newunit\newblock
  \usebibmacro{date}%
  \newunit\newblock
  \usebibmacro{title}%
  \newunit
  \printlist{language}%
  \newunit\newblock
  \usebibmacro{byauthor}%
  \newunit\newblock
  \usebibmacro{byeditor+others}%
  \newunit\newblock
  \printfield{version}%
  \newunit
  \printfield{note}%
  \newunit\newblock
  \iftoggle{bbx:eprint}
    {\usebibmacro{eprint}}
    {}%
  \newunit\newblock
  \usebibmacro{url+urldate}%
  \newunit\newblock
  \usebibmacro{addendum+pubstate}%
  \setunit{\bibpagerefpunct}\newblock
  \usebibmacro{pageref}%
  \newunit\newblock
  \iftoggle{bbx:related}
    {\usebibmacro{related:init}%
     \usebibmacro{related}}
    {}%
  \usebibmacro{finentry}}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@online{gates,
  author       = {Bill Gates},
  title        = {Save the world!},
  url          = {https://www.gatesfoundation.org/de/},
  urldate      = {2016-07-04},
  organization = {{Bill and Melinda Gates Foundation}},
}
@online{gates2,
  author       = {Bill Gates},
  title        = {Save the moon with even longer titles},
  shorttitle   = {Save the moon},
  date         = {2016-05-04},
  url          = {https://www.gatesfoundation.org/de/},
  urldate      = {2016-07-04},
  organization = {Bill {and} Melinda Gates Foundation},
}
@online{ex:one,
  author       = {Anne Elk},
  title        = {One},
  url          = {https://example.com/~elk/1},
}
@online{ex:two,
  author       = {Anne Elk},
  title        = {Two Words},
  url          = {https://example.com/~elk/2},
}
@online{ex:three,
  author       = {Anne Elk},
  title        = {Three Words Title},
  url          = {https://example.com/~elk/3},
}
@online{ex:four,
  author       = {Anne Elk},
  title        = {Four Words in Title},
  url          = {https://example.com/~elk/4},
}
@online{ex:five,
  author       = {Anne Elk},
  title        = {Five Words in a Title},
  url          = {https://example.com/~elk/5},
}
@online{ex:long,
  author       = {Anne Elk},
  title        = {This Title Is Very Long to Test the Feature},
  url          = {https://example.com/~elk/long},
}
@online{ex:override,
  author       = {Anne Elk},
  title        = {A Long Title That Will Be Overridden},
  shorttitle   = {A Different Title},
  url          = {https://example.com/~elk/over},
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\begin{document}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\autocite{gates} sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. \autocite{gates2}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\autocite{gates} sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. \autocite{gates2}

Lorem\autocite{ex:one} ipsum\autocite{ex:one}.
Lorem\autocite{ex:two} ipsum\autocite{ex:two}.
Lorem\autocite{ex:three} ipsum\autocite{ex:three}.
Lorem\autocite{ex:four} ipsum\autocite{ex:four}.
Lorem\autocite{ex:five} ipsum\autocite{ex:five}.
Lorem\autocite{ex:override} ipsum\autocite{ex:override}.
Lorem\autocite{ex:long} ipsum\autocite{ex:long}.

\printbibliography
\end{document}

In the match–replace RegExp I went with the naive
match=\regexp{\A(\w+\s+)(\w+\s+)(\w+).*}, replace={$1$2$3}

if you want a more sophisticated solution that can be extended more easily, you could try
match=\regexp{\A((?:\w+\s+){2})(\w+).*}, replace={$1$2}

where ((?:\w+\s+){2}) captures the first 2 words and the (\w+) the following word.


text:
Q: ctest and MPI parallel tests I'm trying to build some tests with googleTest which should test some MPI parallel code. Ideally I want our CI server to execute them through ctest.
My naive approach was to simply call ctest with MPI:
mpirun -n 3 ctest

However, this results in even trivial tests failing as long as at least two are executed.
Example of a trivial tests:
TEST(TestSuite, DummyTest1) {
  EXPECT_TRUE(true);
}
TEST(TestSuite, DummyTest2) {
  EXPECT_TRUE(true);
}

Am I supposed to launch ctest in some other way? Or do I have to approach this completely differently?
Additional info:

*

*The tests are added via gtest_discover_tests().

*Launching the test executable directly with MPI (mpirun -n 3 testExe) yields successful tests but I would prefer using ctest.

*Version info:

*

*googletest: 1.11.0

*MPI: OpenMPI 4.0.3 AND MPICH 3.3.2

A: According to this CMake Forum post, which links to a Merge Requests and an issue in the CMake GitLab repository, gtest_discover_tests() currently simply doesn't support MPI.
A possible workaround is to abuse the CROSSCOMPILING_EMULATOR property to inject the wrapper into the test command. However, this changes the whole target and not only the tests so your mileage may vary.
set_property(TARGET TheExe PROPERTY CROSSCOMPILING_EMULATOR '${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 3')
gtest_discover_tests(TheExe)

See the forum post for a full minimal example.


text:
Q: Redis store location of users strategy I want to store users locations(long,lat) in redis database. In my initial idea the keys will be users ids. I need 2 functionality: set location , get all locations. How should I perform it, or in which structure should I store it to easy and fast access.

A: Looks like SETS is an good idea (if need location uniqueness):

*

*UserId as key.

*SADD for set location (require O(N) where N is the number of members to be added)

*SMEMBERS for get all locations feature.

*Hold long, lat as some delimiter separated string or serialized value (json for example).

PHP sample
$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->sAdd('locations:' . $userId, $location);
...
$redis->sAdd('locations:' . $userId, $location2);
...
$redis->sAdd('locations:' . $userId, $location2);
...
$userLocations = $redis->sMembers('locations:' . $userId);

You did not say this, but if do not need uniqueness of locations the LISTS would be best choise:

*

*RPUSH for set location (require O(1))

*LRANGE for get all locations feature.

*Key and value format like in SETS case.

PHP sample
$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->rPush('locations:' . $userId, $location);
...
$redis->rPush('locations:' . $userId, $location2);
...
$redis->rPush('locations:' . $userId, $location2);
...
$userLocations = $redis->lRange('locations:' . $userId, 0, -1);

If user has only one location HASH would be best choise:

*

*One key for all users, for example locations

*HSET where field is your userId and value is serialized data

PHP sample
$location = json_encode(array('long' => '...', 'lat' => '...'));
$redis->hSet('locations', $userId, $location);
...
$userLocation = json_decode($redis->hGet('locations', $userId));


text:
Q: Embed an image in Email content - Django I am using Django's Email message module to trigger an email with an embedded image. Currently i have that image in my static folder.I tried using the html code directly in python to trigger the email. But the image is not getting embedded in the triggered email. I have tried by specifyjng the image source attribute as static path as well as a url. Could someone help? Below is the code that I have used.
Code :
recipient_list = ['a...@gmail.com']
from_email = 'a...@gmail.com'
message = ''
path = "{% static 'images/Welcome_image.jpg' %}" //Using this image in the below html also tried specifying the source as an url that points to the url path. Like https://abc/images/Welcome_imagr.jpg
message += "
\

\

\
                    \

\

\

\
                                \
                                    \    //Using this image here but it is not rendered properly.
                                	\

\

\
                                \

\

\

\
                                                Hi User,

\
                                                    Welcome to the world.\
                                                	\

\

\

\
                                	\

\

\

\
                    	\

\

\

"%(path)

subject = "Welcome to the place!"
try:
    msg = EmailMessage(subject, message, from_email, recipient_list)
    msg.content_subtype = "html"  # Main content is now text/html
    if any(recipient_list):
        msg.send()
except Exception:
    print("Exception while sending mail")

A: I have tried the below code and it worked:
Python:
def send():
msg = EmailMessage()

# generic email headers
msg['Subject'] = 'Welcome'
msg['From'] = 'abc@gmail.com'
recipients = ['abc@gmail.com']

# set the plain text body
msg.set_content('This is a plain text body.')

# now create a Content-ID for the image
image_cid = make_msgid(domain='')
# if `domain` argument isn't provided, it will
# use your computer's name

# set an alternative html body
msg.add_alternative("""\

                                          Hi {name},

                                          Welcome!

""".format(image_cid=image_cid[1:-1],name='ABC'), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off

# now open the image and attach it to the email
with open('/path/image.jpg', 'rb') as img:
    # know the Content-Type of the image
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

    # attach it
    msg.get_payload()[1].add_related(img.read(),
                                     maintype=maintype,
                                     subtype=subtype,
                                     cid=image_cid)
server = smtplib.SMTP(host=<hostname>, port=25)

server.starttls()
# send the message via the server.
server.sendmail(msg['From'], recipients, msg.as_string())

server.quit()


text:
Q: RDS failover instance size Is there a way to check the specs (i.e aws rds describe-db-instances) of a multi-az RDS failover instance?
I understand that the instance is inaccessible, but yet is it possible? I see the documentation for describe-db-clusters, but the instance is not listed there


text:
Q: await returns pending promise in this sample rez contains pending Promise. I need to get it resolved with other code paused till it's get resolved:
 function getCoordinates() {
    return new Promise(function (resolve, reject) {
        navigator.geolocation.getCurrentPosition(resolve, reject);
    });
}

async function getAddress() {
    await getCoordinates();
}
const  rez =  getAddress();
alert('wait for rez');

I know I can do something like getAddress().then(function () {  alert('wait for rez')} ); but is there a way to continue not inside of then scope?

A: You need to await the async operation as well:
(async function(){
  function getCoordinates() {
      return new Promise(function (resolve, reject) {
          navigator.geolocation.getCurrentPosition(resolve, reject);
      });
  }

  async function getAddress() {
      await getCoordinates();
  }
   const rez = await getAddress();
   alert('wait for rez');
})()

A: As was commented functions wich calls promise needs to be async otherwise it returns pending promise.
$(window).load(async function () {
    var rez = await getCoordinates();
    alert(rez.coords.latitude);});

function getCoordinates() {
    return new Promise(function (resolve, reject) {
    navigator.geolocation.getCurrentPosition(resolve, reject);
});};


text:
Q: Android ignoring Locale change, using default strings.xml My app supports two languages, default is English and other one is simplified-chinese. I have created two values folder (values and values-zh-rSG) and have placed strings.xml files that contains strings respective to language.
In One of my Activity , user can change default language from English to chinese or chinese to English and than I reload the MainActivity again.
Locale is changed as when I check in MainActivity it displays simplified-chinese using following code:
Configuration config = getResources().getConfiguration();
Log.d("checknl",config.getLocales().get(0).getDisplayName()) ;

But somehow, strings.xml from values-zh-rSG is ignored. It is always loading in English.
Please See: My build.gradle file doesn't contain "resConfigs "en"" in build.gradle (app) file.
I have tested this app on Android api 22 to 26. But it doesnt work in any.


text:
Q: Magento 2. Improve performance of UI Grid
*

*I have a UI Grid that uses a collection with multiple joins (~7-8)

*

*I know joins are a huge performance drawback. But I would think that pagination fixes the performance issue.

*From around ~20k rows in my main table the grid loads really slow.

Questions

*

*Does Magento loads all the items despite pagination?

*Is there any way to improve the performance of my grid? (a flat table or an index is not a viable solution in this particular case)

Any pointers are highly appreciated
Thank you.


text:
Q: Does QItemSelectionModel store the order of selection So I use QItemSelectionModel::selectedRows to get my selection. However, it seems that the order of the selection is dependant on the order in which the user selected it first.
Example:
If I have rows 1,2,3,4,5,6,7,8,9,10
Test case:
I select first row 5 then row 1, then row 2.
Then I call the QItemSelectionModel::selectedRows(); The QModelIndexList will contain the contents as per the order of selection, respectively, (5,1,2). However I wouldn't really assume that it should have an arbitrary order, rather the order relative to the row number like: (1,2,5).
Is there something I am doing wrong? Do I have to specify somewhere to get it in an ascending order of row count(1,2,5) instead of (5,1,2)?


text:
Q: Scrolling text became a real pain..? Hi I am working on c# 2005 with a scrolling application.At first I use some of these
http://www.codeproject.com/KB/miscctrl/csmarquee.aspx
http://www.codeproject.com/KB/miscctrl/ScrollingTextControlArtic.aspx
but all of them cannot help me much.My application contains 7timers.At the time of running it
the scrolling panel looks so irritating(read not at all smooth).
 so I finally tried with a simple panel ,a label and a timer,this also not working (i mean not smooth).
Can there be any other way rather then using timer,to scroll a text.

A: Hard to say what is wrong with your scrolling without any code but you will get much smotther scrolling by using Double Buffering. Read more here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.doublebuffered
But there is limitation how much "animation" you can do with windows forms and have it smooth. Using DirectX or Silverlight will be better for graphics.

A: Using a timer to control the rate of scroll should be OK. It sounds like you might not be double buffering your controls which is the usual cause of jerky animation. See this article, among many, on using double buffering for controls.
But first just try and set the DoubleBuffered property to true on your form. That setting alone may fix your animation.


text:
Q: Write csv data in cpp at each iteration I've 3 columns that change at each iteration (clock cycle). I want to store each value of those columns in a csv file. The csv file is Positions.csv.
SUppose the variable I want to store are in: columnA, columnB and columnC variables.
My file will be empty, at each cycle it will be filled with the columnA,columnB and columnC values.
My following code doesn't work, In output file I've just one row.
I want to append at the end of the file columnA,columnB an columnC. I receive different values for those variable at each cycle.
I need a way to append row in a csv file.
    double columnA , columnB, columnC;
      // LOG START
      std::ofstream coordscsv;
      std::string filename = "Positions.csv";
      coordscsv.open(filename);
      //**************
      std::ifstream  data("Positions.csv");

      std::string line;
      while (std::getline(data, line))
      {
          std::stringstream  lineStream(line);
          std::string        cell;
          while (std::getline(lineStream, cell, ','))
          {
              coordscsv << cell;
          }
      }
      coordscsv <<  columnA << ", " << columnB << ", " << columnC << "\n";
      coordscsv.close();

A: The default argument to ifstreams constructor is ios_base::in. To append to a file you want ios_base::app.
However, you shouldn't open and close the file in every iteration anyhow. Open it once and unless you want to diagnose errors on closing it you don't need to call close() explicitly (the destructor does that already).


text:
Q: How to use a DLL create from txt and compiled with Developer Command Prompt? I generate cs files ( classes ) with the same namespace (EDR_Config). After I generate them, I compile them using Developer Command Prompt for VS2012.
The command line is :
             csc /target:library /out:EDR_Config.DLL AssemblyInfo.cs
            EdrClassInitializator_CFG.cs EdrEquationsDecoder_CFG.cs EdrTreeCreator_CFG.cs
Everything looks great till I add a reference to the c# project. When I try to write
using EDR_Config;
it tell me: Error   1   The type or namespace name 'EDR_Config' could not be found (are you missing a using directive or an assembly reference?)
Why is that happening? Or how can I solve it?


text:
Q: Turn string into array of objects I would like to spilt the string by '|' and ':' and end up with an object with a key value relationship inside of an array.
It would look like this
[{key1 : red, key2 : five},{key1 : blue, key2 : six},{key1 : yellow, key2 : nine}, {key1 : black, key2 :ten}]

This is what I have so far
var  x = "red:five|blue:six|yellow:nine|black:ten"
     datesArray = [],
     datesObj = {},
     keys = ['key1','key2'],
     dates = x.split('|');

for (var i = 0; i < dates.length; i++) {
    datesArray.push(dates[i].split(':'));
}

for(var x = 0; x < datesArray.length; x++){
    datesObj[keys[0]] = datesArray[x][0]
    datesObj[keys[1]] = datesArray[x][1]
}

console.log(datesObj);

http://jsfiddle.net/zPS7h/4/
Any help is appreciated !

A: Something like this?
http://jsfiddle.net/zPS7h/15/
var x = "red:five|blue:six|yellow:nine|black:grey";

var  datesArray = [],
     keys = ['key1','key2'],
     dates = x.split('|');

for (var i = 0; i < dates.length; i++) {
    var values = dates[i].split(':');
    var dateObj = { keys[0]: values[0], keys[1]: values[1] };
    datesArray.push(dateObj);
}

console.log(datesArray);

A: Something like this would work:
s = "red:five|blue:six|yellow:nine|black:ten";
groups = s.split("|");
result = {};
for (i = 0; i < groups.length; i++) {
  t = groups[i].split(":");
  result[i] = { "key1": t[0], "key2": t[1] };
}
console.log(result);

A: var  x = "red:five|blue:six|yellow:nine|black:ten"
     datesArray = [],
     datesObj = {},
     keys = ['key1','key2'],
     dates = x.split('|');

for (var i = 0; i < dates.length; i++) {
    datesArray.push(dates[i].split(':'));
}

var arr = [];

for(var x = 0; x < datesArray.length; x++){
    datesObj[keys[0]] = datesArray[x][0]
    datesObj[keys[1]] = datesArray[x][1]
    arr.push(datesObj);
}

console.log(arr);

A: In ECMA5 you could do something like this using Array.prototype.map.
Javascript
var x = 'red:five|blue:six|yellow:nine|black:ten',
    y = x.split('|').map(function (group) {
        var vals = group.split(':');

        return {
            key1: vals.shift(),
            key2: vals.shift()
        };
    });

console.log(JSON.stringify(y));

Output
[{"key1":"red","key2":"five"},{"key1":"blue","key2":"six"},{"key1":"yellow","key2":"nine"},{"key1":"black","key2":"ten"}]

On jsFiddle


text: Q: Electron vue app - using private repo to update app I'm trying to use electron auto updater feature in my app. The publishing process works fine, I've configured my vue.config.js file correctly and inside a .env file I have my token stored. The problem is whith the bundled app, it will not open and will show a blank screen because to check for update it need the github token. I don't want to ship the token with the app source code and I don't have idea of how to solve this problem. Can anyone suggest me a reilable solution? I've read this old github issue but my vue electron app stop working if I obfuscate the code.


text:
Q: CSS - Overflow and Positioning I saw a similar post dealing with this issue, but my problem is a wee bit different.
In the issue outlined HERE, the concept is that an OUTER div be positioned relative, and the INNER div be positioned ABSOLUTE, and the overflow:hidden would be preserved.
My issue is that BOTH divs, INNER and OUTER are positioned absolute.  How can I still preserve the overflow: hidden on the OUTER div?

A: Not sure of your question, but is that what you try to achieve?
See this jsfiddle
CSS:
#outer {
    position: absolute;
    top: 10px;
    left: 10px;
    height: 80px;
    width: 50px;
    overflow: hidden;
}

#inner {
    position: absolute;
    top: 10px;
    left: 10px;
    height: 50px;
    width: 50px;
}

with the html:

        // Your stuff here

A: position: absolute;
If you apply position: absolute; to any block element(ex: div class="inner" ), the container block( ex: div class="outer"  ) can't determine the dimensions of that element.
overflow: hidden;
Applying overflow: hidden; to any element means, it detect the real dimensions of that element. If that element have given dimensions( width: 200px; height: 200px; ) Overflow: hidden; determine the dimensions of the element as 200px,200px. If the element dose not specify the dimensions, Overflow: hidden determine the area of total ingredients as the dimensions of that element.
So in your case, You would apply a fixed width and a fixed height to your outer block. Otherwise you can't apply both overflow hidden, and position absolute to outter block in the same time.
If it is not possible to applying fixed width and height, css hs small tricks depending on the design. If you might explain the design more, I may explain more.


text:
Q: How to catch a request from the network tab with javascript? When I click on a "Load more" button in the website, there are new variations loaded. You can spot them on the "Network" tab in the inspector of google chrome
See here the output when I clicked, the new color options are shown
Once a request with a status are logged in this "network" tab. Is it possible to add a listener or some sort to a specific log of this, for example: once the "Rectangle-Copy-14.png" is logged, call a function.
Asking this for this project but also for in the future, I don't use a lot of javascript in this project but for in the future I will.

A: If the browser supports it, you could use the resource timing API. I would assume you would have to keep listening to the resources of performance, like :
 performance.getEntriesByType("resource")

Then you can filter this entries by name or type :
resources.filter(resource => resource.name == "Rectangle-Copy-14.png")

If the filter returns a PerformanceResourceTiming with a responseEnd you can then establish that the resource has been loaded and do whatever after.


text:
Q: Encrypting / Decrypting file with Mcrypt Trying to write a couple of functions that will encrypt or decrypt a file and am using the class found here to try and accomplish this:
http://www.itnewb.com/v/PHP-Encryption-Decryption-Using-the-MCrypt-Library-libmcrypt
The encryption function below seems to work, in that it appears to encrypt the file and place it in the intended directory.  I'm trying to decrypt the file now, and it just dies with the message "Failed to complete decryption" (which is coded in there...)  There's nothing in the php error logs, so I'm not sure why it's failing, but as mcrypt is entirely new to me, I'm more than inclined to believe I'm doing something wrong here...
Here are the functions:
//ENCRYPT FILE
    function encryptFile() {
        global $cryptastic;
        $pass = PGPPASS;
        $salt = PGPSALT;
        $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key.");

        if ($handle = opendir(PATH.'/ftpd')) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    $newfile = PATH.'/encrypted/'.$file.'.txt';
                    $msg = file_get_contents(PATH.'/ftpd/'.$file);
                    $encrypted = $cryptastic->encrypt($msg, $key) or die("Failed to complete encryption.");
                    $nfile = fopen($newfile, 'w');
                    fwrite($nfile, $encrypted);
                    fclose($nfile);
                    unlink(PATH.'/ftpd/'.$file);

                }
            }
            closedir($handle);
        }

//DECRYPT FILE
    function inFTP() {
        global $cryptastic;
        $pass = PGPPASS;
        $salt = PGPSALT;
        $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key.");

        if ($handle = opendir(PATH.'/encrypted')) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    $newfile = PATH.'/decrypted/'.$file;
                    $msg = PATH.'/encrypted/'.$file;
                    $decrypted = $cryptastic->decrypt($msg, $key) or die("Failed to complete decryption.");
                    $nfile = fopen($newfile, 'w');
                    fwrite($nfile, $decrypted);
                    fclose($nfile);
                    //unlink(PATH.'/encrypted/'.$file);

                }
            }
            closedir($handle);
        }
        //$crypt->decrypt($file);
    }

A: Since mcrypt is abandonware and no longer recommended to be used, here's an example using openssl.
class AES256Encryption
{
    public const BLOCK_SIZE = 8;
    public const IV_LENGTH = 16;
    public const CIPHER = 'AES256';

    public static function generateIv(bool $allowLessSecure = false): string
    {
        $success = false;
        $random = openssl_random_pseudo_bytes(openssl_cipher_iv_length(static::CIPHER));
        if (!$success) {
            if (function_exists('sodium_randombytes_random16')) {
                $random = sodium_randombytes_random16();
            } else {
                try {
                    $random = random_bytes(static::IV_LENGTH);
                }
                catch (Exception $e) {
                    if ($allowLessSecure) {
                        $permitted_chars = implode(
                            '',
                            array_merge(
                                range('A', 'z'),
                                range(0, 9),
                                str_split('~!@#$%&*()-=+{};:"<>,.?/\'')
                            )
                        );
                        $random = '';
                        for ($i = 0; $i < static::IV_LENGTH; $i++) {
                            $random .= $permitted_chars[mt_rand(0, (static::IV_LENGTH) - 1)];
                        }
                    }
                    else {
                        throw new RuntimeException('Unable to generate initialization vector (IV)');
                    }
                }
            }
        }
        return $random;
    }

    protected static function getPaddedText(string $plainText): string
    {
        $stringLength = strlen($plainText);
        if ($stringLength % static::BLOCK_SIZE) {
            $plainText = str_pad($plainText, $stringLength + static::BLOCK_SIZE - $stringLength % static::BLOCK_SIZE, "\0");
        }
        return $plainText;
    }

    public static function encrypt(string $plainText, string $key, string $iv): string
    {
        $plainText = static::getPaddedText($plainText);
        return base64_encode(openssl_encrypt($plainText, static::CIPHER, $key, OPENSSL_RAW_DATA, $iv));
    }

    public static function decrypt(string $encryptedText, string $key, string $iv): string
    {
        return openssl_decrypt(base64_decode($encryptedText), static::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
    }
}

$text = '8SViI0Gz4r-p7A15YxkwjOBFuW*@NTtbm{U]D&E=~6yLM+adX'P;h3$,KJ%/eo>}<Rs:2#gZ.9fqn"Cv_^[(H\c!)?`Ql';
$key = 'secretkey';
$iv = AES256Encryption::generateIv();
$encryptedText = AES256Encryption::encrypt($text, $key, $iv);
$decryptedText = AES256Encryption::decrypt($encryptedText, $key, $iv);

printf('Original Text: %s%s', $text, PHP_EOL);
printf('Encrypted: %s%s', $encryptedText, PHP_EOL);
printf('Decrypted: %s%s', $decryptedText, PHP_EOL);

Output:
// Long string with lots of different characters
Original Text: 8SViI0Gz4r-p7A15YxkwjOBFuW*@NTtbm{U]D&E=~6yLM+adX'P;h3$,KJ%/eo>}<Rs:2#gZ.9fqn"Cv_^[(H\c!)?`Ql
Encrypted    : rsiF4PMCMyvAp+CTuJrxJYGoV4BSy8Fy+q+FL8m64+Mt5V3o0HS0elRkWXsy+//hPjzNhjmVktxVvMY55Negt4DyLcf2QpH05wUX+adJDe634J/9fWd+nlEFoDutXuhY+/Kep9zUZFDmLmszJaBHWQ==
Decrypted    : 8SViI0Gz4r-p7A15YxkwjOBFuW*@NTtbm{U]D&E=~6yLM+adX'P;h3$,KJ%/eo>}<Rs:2#gZ.9fqn"Cv_^[(H\c!)?`Ql

Old Answer
Try this PHP5 class for encryption using mcrypt. In this case it's using AES encryption. You'll want to change the key for each site you use it on. If you don't use it at least it may guide you on writing your own version of it.
<?php

class Encryption
{
    const CIPHER = MCRYPT_RIJNDAEL_128; // Rijndael-128 is AES
    const MODE   = MCRYPT_MODE_CBC;

    /* Cryptographic key of length 16, 24 or 32. NOT a password! */
    private $key;
    public function __construct($key) {
        $this->key = $key;
    }

    public function encrypt($plaintext) {
        $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
        $ciphertext = mcrypt_encrypt(self::CIPHER, $this->key, $plaintext, self::MODE, $iv);
        return base64_encode($iv.$ciphertext);
    }

    public function decrypt($ciphertext) {
        $ciphertext = base64_decode($ciphertext);
        $ivSize = mcrypt_get_iv_size(self::CIPHER, self::MODE);
        if (strlen($ciphertext) < $ivSize) {
            throw new Exception('Missing initialization vector');
        }

        $iv = substr($ciphertext, 0, $ivSize);
        $ciphertext = substr($ciphertext, $ivSize);
        $plaintext = mcrypt_decrypt(self::CIPHER, $this->key, $ciphertext, self::MODE, $iv);
        return rtrim($plaintext, "\0");
    }
}

Usage:
$key = /* CRYPTOGRAPHIC!!! key */;
$crypt = new Encryption($key);
$encrypted_string = $crypt->encrypt('this is a test');
$decrypted_string = $crypt->decrypt($encrypted_string); // this is a test

Notes:

*

*This class is not safe for use with binary data (which may end in NUL bytes)

*This class does not provide authenticated encryption.

A: While Johns answer is good, using base64 encoding just to fix the binary safety issue is overkill and will make your encrypted files 33% larger than the original.  Here is my PHP Implementation of the AES Crypt file format which solves all the above issues transparently.
https://github.com/philios33/PHP-AES-File-Encryption
It is binary safe and includes authenticated encryption.  Since it uses the open source aes crypt file format (.aes) it is fully compatible with other .aes software.
https://www.aescrypt.com/
The interface is pretty simple whether you are encrypting or decrypting.  You just give it a source file and password.

A: You should not be using Mcrypt to encrypt/decrypt data. As shown in your question, and in the accepted answer, the data is not authenticated, which means it will fall victim to chosen ciphertext attacks.
Further, a great deal of effort has been done to make sure that developers put together cryptographic primitives correctly. As such, instead of Mcrypt, you should be using libsodium for your PHP projects. libsodium is a fork of NaCl. NaCl/libsodium is written to remove a lot of the cryptographic pitfalls that developers find themselves in, such as timing attacks with verification of MAC tags.
Mcrypt is deprecated in PHP 7.1, and libsodim is the preferred way to handle cryptography in PHP.
Using libsodium in your PHP project is easy, and secure. Scott Arciszewski has written an extensive ebook on using libsodium with PHP at https://paragonie.com/book/pecl-libsodium. It's worth the read for anyone doing PHP cryptography.

A: CakePHP has a pretty good implementation of rijndael.  I'm not posting code directly here because not sure the legal ramifications.
Here are the api docs for the Security::rijndael() method.
If encoding a file, you will want to base64_encode() before calling this method with 'encrypt', and base64_decode() after calling this method with 'decrypt'


text:
Q: Should REST API combine information from multiple tables into JSON response? I am looking for a discussion on REST API standard patterns.  I have an implementation in a NoSQL style ... that is, there is one table that contains objects (Agenda Items) which each have a list of references to records in another table (Documents).  In the UI I am building, a user can select an existing Attachment, and attach it to the Agenda Item.  You can not, in this UI, create new Document objects, only refer to existing ones.  Since this is a NoSQL implementation, I am not joining the tables on the doc_id, but manipulating them as separate tables.
There are two ways to implement the REST api.  First is denormalized where one request gets the Agenda Item records, and a second request gets the Documents.  Using the doc_id from the Agenda Item, in client you find the associated document information.
[
   {
    "name": "Agenda Item 1",
    "attachments": ["11556", "87544"]
    },
   {
    "name": "Agenda Item 2",
    "attachments": ["33445", "87544"]
    }
]

and the document list is:
[
   {
    "name": "Design Spec A.ppt",
    "id": "11556"
   },
   {
    "name": "Design Guidelines.doc",
    "id": "33455"
   },
   {
    "name": "User Studies.xls",
    "id": "87544"
   },
]

The second approach is to construct the REST such that the JSON representation of the Agenda Item includes all the document details within one request.  I will call this trashy because there is extra information that did not come from the table.
[
   {
    "name": "Agenda Item 1",
    "attachments": [{
        "name": "Design Spec A.ppt",
        "id": "11556"
      },
      {
        "name": "User Studies.xls",
        "id": "87544"
      }]
    },
   {
    "name": "Agenda Item 2",
    "attachments": [{
        "name": "Design Guidelines.doc",
        "id": "33455"
      },
      {
        "name": "User Studies.xls",
        "id": "87544"
      }]
    }
]

The latter format is

*

*convenient for the client because in a single request you get all the information you need to present a nice display to the user.

*inefficient because the information about one document is sent twice. (It might be in general a lot more information than this example.)

*trashy because if you POST this same format back in an update command, the extra details about the document should be ignored -- only the id is relevant for updates.  If you were to change the name of a document in this structure, presumably that document would NOT be updated with the new name.  Because the document appears twice in this structure, there is the potential that it has a different name at different points.

Seems that the rule might be that you add in the extra document information when GETTING the information, and ignore that extra information when PUTTING or POSTING the JSON structure.
A third option is the hybrid:  You get the fat filled-in form, but you PUT back the lean denormalized form.  I would prefer not to have two different formats for the same object.  I am using AngularJS and the fetched JSON objects translate directly in JS object trees, and it is mighty convenient to put the exact same thing back.
I have implemented both, and both approaches work, but I would like pointed to a discussion about: what is the wisdom of each approach?
Also, when using AngularJS, it is very convenient to put additional members into collection for the UI, for example a "selected" flag.  Again, maybe I am too lazy, but stripping this selected flag out of each record before posting back for updates is a bother, and if I can assume that extra 'trashy' data members will be ignored it makes the coding a lot easier.  Is it OK to assume that your REST API will ignore extra elements?

A: There is really no need to strip out any elements/fields of a document before posting an update - you just include what you need to update in the json and fire it. What is not included will stay in the database.
So - really, there are no "trashy" data members. The second approach is better - the first is more of a hangover from relational databases.
However, the first approach can be better performance wise in situations where updates are frequent.


text:
Q: Apple source code - require( error == nil, bail ) causing errors I'm trying to use some of Apple's source code, but the code is littered with these statements:
require( error == nil, bail );

which are causing all kinds of errors when used in an ARC project ("Goto into protected scope").
How can I work around this code?
Here is an example:
- (void)setupAVCapture
{
    NSError *error = nil;

    AVCaptureSession *session = [AVCaptureSession new];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        [session setSessionPreset:AVCaptureSessionPreset640x480];
    else
        [session setSessionPreset:AVCaptureSessionPresetPhoto];

    // Select a video device, make an input
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    require( error == nil, bail ); //ERROR: "Goto into protected scope"

    isUsingFrontFacingCamera = NO;
    if ( [session canAddInput:deviceInput] )
        [session addInput:deviceInput];

    // Make a still image output
    self.stillImageOutput = [AVCaptureStillImageOutput new];
    [self.stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:(__bridge void *)(AVCaptureStillImageIsCapturingStillImageContext)];
    if ( [session canAddOutput:self.stillImageOutput] )
        [session addOutput:self.stillImageOutput];

    // Make a video data output
    self.videoDataOutput = [AVCaptureVideoDataOutput new];

    // we want BGRA, both CoreGraphics and OpenGL work well with 'BGRA'
    NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject:
                                       [NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
    [self.videoDataOutput setVideoSettings:rgbOutputSettings];
    [self.videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; // discard if the data output queue is blocked (as we process the still image)

    // create a serial dispatch queue used for the sample buffer delegate as well as when a still image is captured
    // a serial dispatch queue must be used to guarantee that video frames will be delivered in order
    // see the header doc for setSampleBufferDelegate:queue: for more information
    videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL);
    [self.videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];

    if ( [session canAddOutput:self.videoDataOutput] )
        [session addOutput:self.videoDataOutput];
    [[self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:NO];

    effectiveScale = 1.0;
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    [self.previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    CALayer *rootLayer = [self.previewView layer];
    [rootLayer setMasksToBounds:YES];
    [self.previewLayer setFrame:[rootLayer bounds]];
    [rootLayer addSublayer:self.previewLayer];
    [session startRunning];

bail:
    session = nil;
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Failed with error %d", (int)[error code]]
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Dismiss"
                                                  otherButtonTitles:nil];
        [alertView show];
        [self teardownAVCapture];
    }

}

A: Add open and close braces to mention the  scope
require( error == nil, bail );
{

}
bail:
{

}

Example:
require( error == nil, bail );
    {

        isUsingFrontFacingCamera = NO;
        if ( [session canAddInput:deviceInput] )
            [session addInput:deviceInput];

        // Make a still image output
        stillImageOutput = [AVCaptureStillImageOutput new];
        [stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:(__bridge void *)(AVCaptureStillImageIsCapturingStillImageContext)];
        if ( [session canAddOutput:stillImageOutput] )
            [session addOutput:stillImageOutput];

        // Make a video data output
        videoDataOutput = [AVCaptureVideoDataOutput new];

        // we want BGRA, both CoreGraphics and OpenGL work well with 'BGRA'
        NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject:
                                           [NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
        [videoDataOutput setVideoSettings:rgbOutputSettings];
        [videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; // discard if the data output queue is blocked (as we process the still image)

        // create a serial dispatch queue used for the sample buffer delegate as well as when a still image is captured
        // a serial dispatch queue must be used to guarantee that video frames will be delivered in order
        // see the header doc for setSampleBufferDelegate:queue: for more information
        videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL);
        [videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue];

        if ( [session canAddOutput:videoDataOutput] )
            [session addOutput:videoDataOutput];
        [[videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:NO];

        effectiveScale = 1.0;
        previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        [previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
        [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
        CALayer *rootLayer = [previewView layer];
        [rootLayer setMasksToBounds:YES];
        [previewLayer setFrame:[rootLayer bounds]];
        [rootLayer addSublayer:previewLayer];
        [session startRunning];
    }

bail:
    {

        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Failed with error %d", (int)[error code]]
                                                                message:[error localizedDescription]
                                                               delegate:nil
                                                      cancelButtonTitle:@"Dismiss"
                                                      otherButtonTitles:nil];
            [alertView show];

            [self teardownAVCapture];
        }
    }


text:
Q: Can't understand SecurityManager.IsGranted() I intentionally reduced the permission for a method to see whether IsGranted method works, but it doesn't. Here's my code:
[FileIOPermission(SecurityAction.Deny, Read = "d:\\faz.txt")]
void aMethod()
{
  Console.WriteLine(SecurityManager.IsGranted(new
    FileIOPermission(FileIOPermissionAccess.Read,"d:\\faz.txt")));

}

The method returns true even if the method never given that permission. Can some one please explain about this issue.

A: I dont think you are using it correctly. You need to NOT create a new instance of FileIOPermission and use the one applied to the method.
Which leads to another issue. If your security is working correctly, how can that method execute?


text:
Q: swap two elements in 2d array I have an array of the shape (10296, 6). I want to swap the two last elements in the subarray.
a = [[1, 2, 3, 4, 5, 6][1, 2, 3, 4, 5, 6]...

So that 5 and 6 of each array is swapped into:
a = [[1, 2, 3, 4, 6, 5][1, 2, 3, 4, 6, 5]...

A: Try advanced slicing in numpy. Read more here -
import numpy as np

a = np.array([[1, 2, 3, 4, 5, 6],
              [1, 2, 3, 4, 5, 6]])

a[:,[4, 5]] = a[:,[5, 4]]

array([[1, 2, 3, 4, 6, 5],
       [1, 2, 3, 4, 6, 5]])


text:
Q: Can send data but request.getParameter always == null There are my code from java eclipse keplero, my project was a servlet(server) that communicate with extension of chrome(client) via XMLRequest. I have used GET and POST and servlet can comunicate the string in between case but request.getParameter was in every case null.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>XMLFinal</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method = "get" action = "main">
Data: <input type="text" name="data">
<input type="submit" value = "send">
</form>
</body>
</html>

main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import netscape.javascript.JSObject;

/**
 * Servlet implementation class main
 */
@WebServlet("/main")
public class main extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
public main() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */

//server funziona in invio, il segnale in ricezione non funziona ancora
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //guardare file index.html
    System.out.println(request.getParameter("data"));

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    //
    response.getWriter().write("GET");

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    //guardare file index.html
    System.out.println(request.getParameter("data"));

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    //invio segnale funzionante
    response.getWriter().write("POST2");
}

private void getHeadersInfo() {
    // TODO Auto-generated method stub
}
}

I have improve in login page to create a simple form and that run perfectly but i need data from js client :
loadXMLRequest();

function loadXMLRequest()
{
    var xmlhttp;

//da testare su Chrome Firefox Opera IE 7 o superiore
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();

    //arrivo del segnale
    xmlhttp.open("GET","http://localhost:8080/XMLFinal/main?ciao",true);
    xmlhttp.setRequestHeader("Content-Type","text/plain");
    alert("questi sono  i dati da inviare : ciao"");

    xmlhttp.send();
    alert("Message sent");

    //apertura pagina web risposta giunta ed in elaborazione
    //window.open(xmlhttp.responseText);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==0)
        {
            alert("request not initialized");
        }

        if (xmlhttp.readyState==1)
        {
            alert("server connection established");
        }

        if (xmlhttp.readyState==2)
        {
            alert("request received");
        }

        if (xmlhttp.readyState==3)
        {
            alert("processing request");
        }

        if (xmlhttp.readyState==4)
        {
            alert("request finished and response is ready");
            alert(xmlhttp.responseText);

            //nessun dato ricevuto possibile shutdown del server
            if(xmlhttp.responseText=="")
            {

            }
            else
            {
                //windows.open(xmlhttp.responseText);
            }
        }

        if (xmlhttp.readyState==200)
        {
            alert("OK");
            alert(xmlhttp.responseText);
        }

        if (xmlhttp.readyState==404)
        {
            alert("Page not found");
        }
    }

}
else
{
    //per IE 6 o inferiore
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    alert("Microsoft alert");
}

}

A: The Name is the Key
Your code says
System.out.println(request.getParameter("http"));

and your form says
<input type="text" name="data">

Change the first to
System.out.println(request.getParameter("data"));

or the second to
<input type="text" name="http">

A: You are making a Get call i.e.,
xmlhttp.open("GET","http://localhost:8080/XMLFinal/main?ciao",true);

So from servlet it will call doGet(-,-) method, but under doGet(-,-) method you have written
System.out.println(request.getParameter("http"));

which should be replaced like
System.out.println(request.getParameter("data"));

Which you have correctly written in doPost(-,-) method.
But i always prefer not to write redundant code. in both doGet() & doPost(), instead you can write code in a common method and call the same method from both the do*** methods. i.e.,
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

Hope this will helps you.


text:
Q: Rails returning strange invalid information in view but not console I know for a fact (having checked through the console) that the output should be three songs, but for some reason I keep getting a fourth song added to every page. The song is different on every occasion, and I'm baffled as to why this is happening. Any help is much appreciated!
In my controller
  def edit
    @songs = Song.all(order: 'title')
    @song = Song.find(params[:id])
    @setlist = Setlist.find(params[:id])
    @allocations = @setlist.allocations
  end

The full view code, as requested:
First the view for the actual edit page:

Edit a Setlist

      <%=form_for(@setlist) do|f|%>

         <%=f.label :date, "Set a date" %>
         <%=f.date_select :date%>

         <%=f.label :morning, "Morning" %>
         <%=f.radio_button :morning, true %>
         <%=f.label :morning, "Evening" %>
         <%=f.radio_button :morning, false %>

Library

          <%= render 'library' %>
          <%= render 'currentSet' %>

         <%=f.submit "Save Setlist", class: "btn btn-large btn-primary" %>
      <% end %>

The current set partial (ignore the library partial, as it's a nested form with nothing added yet):

Current Setlist

         Title
         Artist
         Root Key
         Remove

         <% if(@allocations.empty?) %>

NO SONGS

         <% else %>
            <%= render @allocations %>
         <%end%>

And allocations:

    <%= allocation.song.title %>
    <%= allocation.song.artist %>
    <%= allocation.song.key %>
    <%= link_to "Remove Song", allocation, method: :delete %>

I'm not sure if this is relevant but I've also added the actual rendered html for examination:

    S
    A
    K
    Remove Song...

    S
    A
    K
    Remove Song

The part I'm finding wierd is that the last entry differs from all the others in that the url doesn't have an allocation id i.e. /allocations/9 in the second last one vs /allocations in the last one.

A: Just to close this one off then:
  def edit
    @songs = Song.all(order: 'title')
    @song = Song.find(params[:id])
    @setlist = Setlist.find(params[:id])
    @allocations = @setlist.allocations
  end

Use the appropriate :id's in your Song and Setlist finders (i.e. not the same one).


text:
Q: Not able to access Datastore Resources from GKE I  have  deployed  an  app in  GKE which  makes  a  backend  call  to  datastore to  perform  crud  operations.Added cloud  datastore  owner  role to  the  Service  account  on  which  gke  is  hosted.
when i  request  any  of  the  endpoint  which  makes  call  to  the  backend datastore  i  am  getting  below  excpetion:
com.google.cloud.datastore.DatastoreException: Unauthenticated. at com.google.cloud.datastore.spi.v1.HttpDatastoreRpc.translate(HttpDatastoreRpc.java:138) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.spi.v1.HttpDatastoreRpc.translate(HttpDatastoreRpc.java:123) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.spi.v1.HttpDatastoreRpc.lookup(HttpDatastoreRpc.java:173) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl$3.call(DatastoreImpl.java:416) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl$3.call(DatastoreImpl.java:413) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105) ~[gax-1.58.2.jar:1.58.2] at com.google.cloud.RetryHelper.run(RetryHelper.java:76) ~[google-cloud-core-1.93.9.jar:1.93.9] at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50) ~[google-cloud-core-1.93.9.jar:1.93.9] at com.google.cloud.datastore.DatastoreImpl.lookup(DatastoreImpl.java:412) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl$ResultsIterator.loadResults(DatastoreImpl.java:387) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl$ResultsIterator.<init>(DatastoreImpl.java:383) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl.get(DatastoreImpl.java:373) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl.get(DatastoreImpl.java:336) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreHelper.fetch(DatastoreHelper.java:73) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at com.google.cloud.datastore.DatastoreImpl.fetch(DatastoreImpl.java:353) ~[google-cloud-datastore-1.105.0.jar:1.105.0] at org.springframework.cloud.gcp.data.datastore.core.DatastoreTemplate.findAllById(DatastoreTemplate.java:249)

One  thing  i  noticed is  that  when  the  application  start  it  uses  default  compute  engine  credentials  to  authenticate
I  am  not  sure  on  how  to  fix  this , searched  for  few  solutions  and  came  to  know  that  we  need  to  add  GOOGLE_APPLICATION_CREDENTIALS env  variable  in  deployment.yaml
spec:
 containers:
 - name: app
   image: eu.gcr.io/google_project_id/springapplication:v1
   volumeMounts:
   - name: google-cloud-key
     mountPath: /var/secrets/google
   env:
   - name: GOOGLE_APPLICATION_CREDENTIALS
     value: /var/secrets/google/credentials.json
   ports:
   - name: http-server
     containerPort: 8080
 volumes:
 - name: google-cloud-key
   secret:
     secretName: app-key

Is this  the  right  way, since  the  credentials  file  is  a  confidential  one  where  we  store  it ideally(I  am  using  Jenkins  to  deploy  apps)
Someone  please  guide  me  on  this.....

A: It's a problem at node level permission. When you create your cluster, and your node pool, you can choose the security of your node. And you can explicitly allow or deny the access to some API, such as Datastore. And by default Datastore is disabled.

You can check this in the Compute Engine that compose your GKE cluster:

If you don't want to delete your Cluster, you need to create a new node pool, to migrate your pod and to remove the old node pool.

Side remark. Don't you Service account key files. I recommend you to use workload identity for a better security


text:
Q: Is "mother tongue" exactly the same as "native language"? Someone just told me "mother tongue" is exactly the same as "native language".
I may be wrong, but I think the first one is not a good translation.
Am I wrong?

A: Multilingualism adds a questionable level of complexity to the established equations.If we were to define the terms based on today's demography then it sure is relevant to consider the following. And FYKI monolingualism is a thing of the past.
Wiki states:

"One can have two or more native languages, thus being a native
  bilingual or indeed multilingual. The order in which these languages
  are learned is not necessarily the order of proficiency. For instance,
  a French-speaking couple might have a daughter who learned French
  first, then English; but if she were to grow up in an English-speaking
  country, she would likely be most proficient in English."

Wiki defines the concerned terms by establishing a differential approach.
Defining mother tongue:
Based on origin: the language(s) one learned first (the language(s) in which one has
established the first long-lasting verbal contacts).
Based on internal identification: the language(s) one identifies with/as a speaker
of;
Based on external identification: the language(s) one is identified with/as a
speaker of, by others.
Based on competence: the language(s) one knows best.
Based on function: the language(s) one uses most.

A native speaker is defined according to the guidelines that:
The individual acquired the language in early childhood
The individual has intuitive knowledge of the language
The individual is able to produce fluent, spontaneous discourse
The individual is competent in communication
The individual identifies with or is identified by a language community
The individual does not have a foreign accent

A: Mother tongue and Native language have similar, meanings and are often actually interchangeable, however there is a subtle difference.
Native language refers to the language of the area the person grows up in.  For example, growing up in the United States, your native language would be English.  It's the language used every day everywhere you go by the vast majority of the people there.
Mother tongue refers to the language of the family you grew up in.  The language your parents spoke in the house, or to each other out-and-about if applicable.  Often, parents will use the same language as that of the region (parents in the U.S. speaking English) however it can differ.  Take for example a family of immigrants from Mexico to the United States.  In their house and with family/friends they may use Spanish.  But at school, restaurants, stores, etc they would use English.  In this case, the native language is English and the mother tongue is Spanish.
Typically, the two will refer to the same language, in which case they are interchangeable; however, in some cases they may differ.

A: As someone growing up in a Malaysian-Chinese household, I always consider my mother tongues to be the various Chinese dialects while my native languages are Malay (Bahasa Malaysia) and English, since the latter two I began learning concurrently and have been ever since. So for me, there are very distinctive, though as many of you have pointed out, subtle differences between the two.

A: "Mother tongue" and "native language" are set phrases that both refer to the language one has started learning from birth. One generally associates "mother" with "tongue" and "native" with "language" but it is sometimes found the other way round. "Language" and "tongue" are here synonyms.
I would say "mother" or "native" is not identical though. When using "native" the reference is more to the country/nation. When using "mother" the reference is to the parent (mother or father), which gives it a warmth and personal relationship that the word "native" doesn't have.
I've found a sentence that I think can explain what I mean about "native" and "mother" although native being used here in association with country:

As a parent living far from my native country I have often experienced
  the fear that my children would not learn their mother language well.

In this whole text the use of "mother tongue" is not identical and I doubt the person who wrote it would have used "native language" (or "native tongue") where she used "mother language".

A: Mother tongue and native language mean the same thing.  Both words share an etymology.  I missed this fact earlier and my thanks to the sharp-eyed commenters who caught it.


text:
Q: Solve with limit over multiple variables Very new to Mathematica so apologies for what is probably numpty question. The following returns no solutions. However, there is a solution! If I set a = 1 I get the solution b = 1/2. Can you explain how I'm misusing Solve?
f[x_] := Log[1/x + 1]^(-1);
Solve[Limit[Abs[f[x] - (x + b)], x -> Infinity] == 0, b]
(* out: {{b -> 1/2}} *)

contradicts
f[x_] := Log[1/x + 1]^(-1);
Solve[Limit[Abs[f[x] - (a x + b)], x -> Infinity] == 0, {a, b}]
(* out: {} *)

A: Maybe because you have value for the limit only when a=1
check this:
    Limit[Abs[f[x] - (a x + b)], x -> Infinity,
 Assumptions -> {a == 1, b \[Element] Reals}]

(*1/2 Abs[1 - 2 b]*)

Limit[Abs[f[x] - (a x + b)], x -> Infinity,
 Assumptions -> {a != 1, {a, b} \[Element] Reals}]
(*\[Infinity]*)


text:
Q: Как создать случайный двумерный массив numpy? Именно средствами numpy. Мне нужен массив вида a = [[b, c], [d, e] ... [x, z]] чтобы в нем были как положительные так и отрицательные числа.

A: import numpy as np

np.random.uniform(low=-100, high=100, size=(4, 2))

# вывод
array([
   [-81.458     , -81.53563001],
   [ 14.38820047,  79.58667144],
   [ 10.55146126, -73.9337667 ],
   [ 12.82037855,  71.93397549]])

Либо так
np.random.randint(-100, 100, (3, 2))

array([
   [ 68, -63],
   [ 41,  52],
   [ 54,  85]])

A: В этой статье был момент со случайной инициализацией весов нейросети:
rows = 10
cols = 2
array = 2 * numpy.random.random((rows, cols)) - 1
print(array)

Возможный вывод:
array([[-0.90498638,  0.49846144],
       [ 0.65269211, -0.83121061],
       [ 0.03048237,  0.27927699],
       [ 0.72069673, -0.81232947],
       [ 0.27523583,  0.95059816],
       [ 0.02586882,  0.96637237],
       [ 0.88832145, -0.14137144],
       [-0.39758786,  0.43305011],
       [ 0.32713238, -0.0213639 ],
       [-0.86635081, -0.63139956]])

Также важная цитата из нее же:

Заметьте, что она инициализируется случайным образом, и среднее
значение равно нулю. За этим стоит достаточно сложная теория. Пока
просто примем это как рекомендацию.


text:
Q: Does the 65C02S processor Reset Sequence require that its data pins be connected during reset? I have a 65C02S processor wired up and the address and data pins connected to an Arduino Mega so that I can print the state of the data bus and address bus for testing purposes. The 65C02 datasheet states that the RESB input should be held low for 2 clock cycles to initialize the microprocessor and start program execution. As part of the reset, the processor goes through an initialization sequence lasting seven clock cycles. Upon completion of the reset sequence, the program counter is loaded with the reset vector from locations FFFC (low byte) and FFFD (high byte). This is the start location for program control.
I expect to see these two addresses on the address bus after I have advanced the processor through its 7 clock cycles, but I don't see them. My question is: do the data pins (D0-D7) need to supply the processor with an instruction during the reset sequence to ensure that the processor puts the address of the reset vector on the address bus, or is the processor kaput? At the moment, the data pins are connected to the Arduino which is only reading the state of the pins.

A:
My question is: do the data pins (D0-D7) need to supply the processor
  with an instruction during the reset sequence to ensure that the
  processor puts the address of the reset vector on the address bus

You do not need to drive anything. The processor automatically reads the data from the specified vector location.

is the processor kaput?

Is the processor working fine? is the application running? if yes, processor ist nicht kaput (Processor has not gone bad)

*

*Please check the sampling for a few more samples. is the logging of address data bus fine after or during normal code sequence?


text:
Q: How to create json object using json simple with "dot" in name? My json object looks like this
 {
 name.raw:John
 }

How would I create the corresponding json simple object "name.raw". I am facing issues due to the dot in name

A: Name the variable name with a string
{'name.raw':'Jhon'}


text:
Q: (private static reference vs private reference) performance Ok so let's say we have a factory that produces instances of objects. The instances that this factory produces have a dependency on one reference.
I am trying to understand if there is any difference in declaring this reference in objects as private or as private static. What C# is doing behind the scene. Does declaring the reference static is more efficient in a data store manner.
Example code:
So we are talking about this
public class ShoesFactory {

    public ShoesFactory(Material soleMaterial){ // contractor
       ShoesOfTypeA.SetSoleMaterial(soleMaterial)
    }

    public ShoesOfTypeA GetShoesOfTypeA() {
       return new ShoesOfTypeA ();
    }
}

public class ShoesOfTypeA {
   private static Material soleMaterial;

   public static SetSoleMaterial(soleMaterial){
      ShoesOfTypeA.soleMaterial = soleMaterial;
   }

}

Vs this
public class ShoesFactory {

    private Material soleMaterial;
    public ShoesFactory(Material soleMaterial){ // contractor
       this.soleMaterial=soleMaterial;
    }

    public ShoesOfTypeA GetShoesOfTypeA() {
       return new ShoesOfTypeA (soleMaterial);
    }
}

public class ShoesOfTypeA {
   private Material soleMaterial;

   public ShoesOfTypeA(soleMaterial) { //constructor
      this.soleMaterial = soleMaterial;
   }
}

Edit :
As John Alexiou said in the comments initializing a field on the constructor of a different class is violates the principle of encapsulation so we moved initialization out of contractors
The question here is not about how to follow the SOLID design principles but
what is the performance differences of the above codes :)

A: Your problem is not performance, but design at this point.
I propose you have a single Shoe class with a property designating the type of shoe, and a single factory method to generate the shoes. Also, the material can be read on demand using a Lazy<Material> field, which calls some method (delegate) when it is first accessed.
class Program
{
    static void Main(string[] args)
    {
        var factory = new ShoeFactory(ReadMaterial);
        var b = factory.GetShoesOfType(ShoeType.B);
    }
    static Material ReadMaterial()
    {
        return new Material();
    }
}

public class Material
{
}
public enum ShoeType
{
    A,
    B,
    C
}

public sealed class Shoe
{
    public Shoe(Material material, ShoeType type)
    {
        Material=material;
        Type=type;
    }

    public Material Material { get; }
    public ShoeType Type { get; }
}

public class ShoeFactory
{
    private readonly Lazy<Material> soleMaterial;

    public ShoeFactory(Func<Material> materialFactory)
    {
        this.soleMaterial=new Lazy<Material>(materialFactory);
    }

    public Shoe GetShoesOfType(ShoeType type)
    {
        return new Shoe(soleMaterial.Value, type);
    }
}

The above design is straight forward, flexible and if you were to ask me about performance, like any other modern application the slowerst part is initializing classes, and by keeping the class structure simple you are helping the compiler do the appropriate optimizations on its own.


text:
Q: How to determine a type alias with Scala Reflection? With Scala Reflection in 2.10, how can one determine if a type is a type alias?
The following does not work:
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> typeOf[String].typeSymbol.asType.isAliasType
res46: Boolean = false

A: This is a bug: https://issues.scala-lang.org/browse/SI-6474 caused by the fact that Type.typeSymbol automatically dereferences aliases.
scala> showRaw(typeOf[String])
res0: String = TypeRef(SingleType(ThisType(scala), scala.Predef), newTypeName("String"), List())

scala> typeOf[String].typeSymbol
res1: reflect.runtime.universe.Symbol = class String

scala> typeOf[String].typeSymbol.asType.isAliasType
res2: Boolean = false

scala> val TypeRef(_, sym, _) = typeOf[String]
sym: reflect.runtime.universe.Symbol = type String

scala> sym.asType.isAliasType
res3: Boolean = true

A workaround, as partially provided by the REPL printout, is to perform manual pattern matching and extract the underlying symbol. An alternative is to cast to scala.reflect.internal.Types#Type and use typeSymbolDirect.

A: Note that, in addition of scala.reflect.internal.Types#Type, you need to avoid getClassByName(): following scala-dev issues 248, and PR 5482, Scala 2.12.1 will ensure that:

*

*companionClass returns a class, not a type alias,

*type aliases are not followed in getClassByName and friends.

This makes getClassByName fail / getClassIfDefined return NoSymbol when querying an alias.
The current behavior can confuse the classfile parser: when parsing a
  class, a cross-check verifies that pool.getClassSymbol(nameIdx)
  returns the symbol of the class currently being parsed.
  If there's a
  type alias that shadows the linked class, following the alias would
  return an unrelated class.


text:
Q: VB.NET Custom Complex Sort in least possible steps I also want to say I don't care which solution the algorithm generates as I know there is plenty of solutions for the same amount of moves.
I just want any solution that is the least possible moves for the current puzzle.
Thank you. There isn't really any pattern I can think off all I know is lowest numbers must go in front and biggest numbers must go in back, but the trick is it moves 2 numbers at once one from the front and one from the back together like Sort with a more modifiable stack together.
This game contains only 2 moves..

*

*Left Cyclic Rotation At Any Offset (except the last byte) Right

*Cyclic Rotation At Any Offset (except the last byte)

Here is the function code for that
Public Function CyclicRotationOffset(ByVal data() As Byte, ByVal beginOffset As Integer, ByVal leftDirection As Boolean) As Byte()

    'Left Direction = true
    '--------------------------------------------------------
    'Shifted cyclically rotation If [a, b, c] then [b, c, a]
    '--------------------------------------------------------
    'Left Direction = false
    '--------------------------------------------------------
    'Shifted cyclically rotation If [a, b, c] then [c, a, b]
    '--------------------------------------------------------

    If beginOffset = UBound(data) Then
        'last byte cannot do anything.
        Return data
    End If

    Dim newdata() As Byte
    ReDim newdata(UBound(data))

    If leftDirection = True Then
        newdata(UBound(newdata)) = data(beginOffset) '1st element will be last.
        For i = beginOffset To UBound(data) - 1
            newdata(i) = data(i + 1)
        Next i
    Else
        newdata(beginOffset) = data(UBound(data)) 'last element will be first.
        For i = beginOffset + 1 To UBound(data)
            newdata(i) = data(i - 1)
        Next i
    End If

    If beginOffset > 0 Then
        Buffer.BlockCopy(data, 0, newdata, 0, beginOffset)
    End If

    Return newdata
End Function

Here are two examples
----------------------------------------------
Data, Solved in 6 moves with brute force (and function).
2, 7, 3, 1, 6, 4, 5, 8, 9
----------------------------------------------
Brute Forced Rotations
3 Lefts, 3 Rights
----------------------------------------------
1, Left
2, Left
0, Right
6, Right
3, Left
5, Right
---------------------------------------------
2, 3, 1, 6, 4, 5, 8, 9, 7
2, 3, 6, 4, 5, 8, 9, 7, 1
1, 2, 3, 6, 4, 5, 8, 9, 7
1, 2, 3, 6, 4, 5, 7, 8, 9
1, 2, 3, 4, 5, 7, 8, 9, 6
1, 2, 3, 4, 5, 6, 7, 8, 9 <- Final one produces the sorted answer
----------------------------------------------

Here is a harder example (this one stumped me)
Solved in 7 moves (with brute force)
data=
3, 9, 7, 4, 2, 5, 1, 6, 8
answer=
1, 2, 3, 4, 5, 6, 7, 8, 9

4 Lefts, 3 Rights
moves taken
6, Left
0, Right
3, Left
7, Right
2, Left
3, Left
1, Right

3, 9, 7, 4, 2, 5, 6, 8, 1
1, 3, 9, 7, 4, 2, 5, 6, 8
1, 3, 9, 4, 2, 5, 6, 8, 7
1, 3, 9, 4, 2, 5, 6, 7, 8
1, 3, 4, 2, 5, 6, 7, 8, 9
1, 3, 4, 5, 6, 7, 8, 9, 2
1, 2, 3, 4, 5, 6, 7, 8, 9
Here is my code that finds the 6 move solution for the first puzzle, But for the second puzzle it doesn't handle it right so the solution itakes 14 moves instead of the optimal 7 moves.
Public Structure OffsetMove
    Dim moveId As Byte
    Dim randomOffset As Byte
    Public Sub New(ByVal moveId As Byte, ByVal randomOffset As Byte)
        Me.moveId = moveId
        Me.randomOffset = randomOffset
    End Sub
End Structure

Public Function SortDataCyclic(ByVal data() As Byte) As List(Of OffsetMove)
    Dim answer() As Byte
    ReDim answer(UBound(data))
    Buffer.BlockCopy(data, 0, answer, 0, data.Length)
    Array.Sort(answer)
    Dim newdata() As Byte
    ReDim newdata(UBound(data))
    Buffer.BlockCopy(data, 0, newdata, 0, data.Length)

    Dim i As Long = 0
    Dim j As Long = 0
    Dim k As Long = 0
    Dim l As Long = 0
    Dim solutionCount As Integer = 0
    Dim movesTaken As New List(Of OffsetMove)
    Debug.Print("---------------------------------------------")

    Dim sortedPairs As New List(Of Byte)

    While j < 8
        If sortedPairs.Count >= 3 Then
            'Insertion right cyclic rotations go here
            While l < 9
                k = 0
                While k < 9
                    If newdata(k) > newdata(8) Then Exit While
                    k += 1
                End While
                If k = 9 Then
                    'fully sorted already, nothing left to insert.
                    Exit While
                End If
                newdata = CyclicRotationOffset(newdata, k, False)
                movesTaken.Add(New OffsetMove(1, k))
                printDebug(newdata)

                l += 1
            End While

            'Exit the while, everything is sorted.
            Exit While
            '1, 2, x, x, x, x
        ElseIf j + 1 < 9 AndAlso _
            newdata(j + 1) = (newdata(j) + 1) Then
            sortedPairs.Add(j)
            j += 2
            '1, x, 2, x, x, x
        ElseIf j + 2 < 9 AndAlso _
            newdata(j + 2) = (newdata(j) + 1) Then
            newdata = CyclicRotationOffset(newdata, (j + 1), True)
            movesTaken.Add(New OffsetMove(0, (j + 1)))
            printDebug(newdata)
            j = 0
            'No pair pattern at all.
        Else
            newdata = CyclicRotationOffset(newdata, j, True)
            movesTaken.Add(New OffsetMove(0, j))
            printDebug(newdata)
        End If
    End While
    Return movesTaken
End Function

Public Sub printDebug(ByVal data() As Byte)
    Debug.Print(data(0) & ", " & data(1) & ", " & data(2) & ", " & data(3) & ", " & data(4) & ", " & data(5) & ", " & data(6) & ", " & data(7) & ", " & data(8))
End Sub

A: I used your code, and came up with different result sets than you did.  I think part of it has to do with your logic on the sortedPairs.Count in your while loop.  I was also getting confused by the differences between I,j,k and l.  So I rewrote your While loop using some slightly different logic.
    Dim currentNumber As Integer = 1
    Dim currentPositionOfNumber As Integer = 0

    While currentNumber - 1 < 8
        currentPositionOfNumber = GetIndexOfNumber(newdata, currentNumber)
        If currentNumber - 1 = currentPositionOfNumber Then
            'do nothing
        ElseIf currentNumber = currentPositionOfNumber Then
            'If the number needed to move is in the spot to the immediate right of where it needs to be, then just rotate left once
            newdata = CyclicRotationOffset(newdata, currentNumber - 1, True)
            movesTaken.Add(New OffsetMove(1, k))
            printDebug(newdata)
        ElseIf currentPositionOfNumber = 8 Then
            'if number needed to move is in last position, then rotate it to correct position
            newdata = CyclicRotationOffset(newdata, currentNumber - 1, False)
            movesTaken.Add(New OffsetMove(1, k))
            printDebug(newdata)
        ElseIf currentNumber = newdata(currentPositionOfNumber + 1) - 1 Then
            'if the number is not in any of the above positions, but the number immediately to it's right is the next higher, then just rotate left until the pair are in correct position
            Do Until GetIndexOfNumber(newdata, currentNumber) = currentNumber - 1
                newdata = CyclicRotationOffset(newdata, currentNumber - 1, True)
                movesTaken.Add(New OffsetMove(1, k))
                printDebug(newdata)
            Loop
        Else
            'rotate left once, then rotate right to correct position
            newdata = CyclicRotationOffset(newdata, currentPositionOfNumber, True)
            movesTaken.Add(New OffsetMove(1, k))
            printDebug(newdata)
            newdata = CyclicRotationOffset(newdata, currentNumber - 1, False)
            movesTaken.Add(New OffsetMove(1, k))
            printDebug(newdata)
        End If
        currentNumber += 1
    End While

I also have a function that finds where the currentNumber being evaluated resides in the array
Public Function GetIndexOfNumber(data() As Byte, number As Integer) As Integer
    For i = 0 To 8
        If data(i) = number Then Return i
    Next
End Function

With this, I get the following results...
Test 1 = 6 Moves
Test 2 = 7 Moves


text:
Q: Append a line to file when blank line appears Input:
 apple
 banana
 grapes

 apple
 banana
 grapes

 apple
 banana
 grapes

Expected Output:
 apple
 banana
 grapes
 orange
 melon

 apple
 banana
 grapes
 orange
 melon

 apple
 banana
 grapes
 orange
 melon

Code:
  String newLine=null;
  PrintStream output = new PrintStream(outputFile);
   BufferedReader br = new BufferedReader(new FileReader(outputFile));
        while((newLine=br.readLine())!=null && !newLine.isEmpty()){
            if(!newLine.contains("orange")){
                    output.println("orange");

            }
            if(!newLine.contains("melon")){
                    output.println("orange");

            }

        }
        out.close();
        br.close();

The code above given for your reference appends the new strings at the end of file.But i want to append it after every record.
Please suggest me the modifications.
What do I need to do in this case?

A: When you encounter the line containing "grapes" you need to append a new line for "orange" and "melon".  Try using this code:
String newLine = null;
PrintStream output = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
    while((newLine=br.readLine())!=null) {
        output.println(newLine);
        if (newLine.contains("grapes")) {
                output.println("orange");
                output.println("melon");
        }
    }
out.close();
br.close();

A: Use string.replaceAll
string.replaceAll("(?s)(?:\\n\\n|$)", "\\norange\\nmelon\\n\\n");

DEMO

A: As soon you read an empty line you need to output your orange and melon line. And additional when you reach the end of the file.
Find a snippet where you could start with.
create an new file with the addtional llines
String newLine;
try (PrintStream output = new PrintStream("fruits.out");
        BufferedReader br = new BufferedReader(new FileReader("fruits.in"))) {
    while ((newLine = br.readLine()) != null) {
        // reached an empty line
        if (newLine.isEmpty()) {
            output.println("orange");
            output.println("melon");
        }
        output.println(newLine);
    }
    // reached end of file
    output.println("orange");
    output.println("melon");
}

modify the input file
Path fileInOut = Paths.get("fruits.in");
Charset defaultCharset = Charset.defaultCharset();
List<String> linesIn = Files.readAllLines(fileInOut, defaultCharset);
List<String> linesOut = new ArrayList<>();
for (String line : linesIn) {
    if (line.isEmpty()) {
        linesOut.add("orange");
        linesOut.add("melon");
    }
    linesOut.add(line);
}
linesOut.add("orange");
linesOut.add("melon");
Files.write(fileInOut, linesOut, defaultCharset, StandardOpenOption.TRUNCATE_EXISTING);


text:
Q: Changing "Favorites" Tooltip in Java Help In my helpset file, I'm declaring a favorites view, using
<view>
  <name>Lesezeichen</name>
  <label>Lesezeichen</label>
  <type>javax.help.FavoritesView</type>
  <data></data>
</view>

This automatically adds an appropriate button to the toolbar (in the swing application). Unfortunately, the tooltip of the button reads "Add to favorites". I would like to replace this by my own text, but didn't find anything about this in the documentation or using a google search. Any ideas or pointers?
Disclaimer: I already posted this question to JavaRanch, didn't get an answer yet, though.

A: If you extract the src.jar (rename it to src.zip and extract) and open the java class jh2.0/src/src/javax/help/resources/Constants.java you will notice that in the section
// Tooltips for Actions

is located entry for localization:
{ "tooltip.FavoritesAction", "Add to Favorites"},

This constant is missing from the jh2.0/src/src/javax/help/resources/Constants_de.java which is used in your case. Just add the right translation, compile the source or just this class and add it to the jh.jar (you may treat the jar as a simple zip archive)
Yes, I know this is dirty hack, but generally JavaHelp is quite useful

A: Now this sounds weird.
The ResourceBundle mechanism supports to "override" the class resource content by using a .properties file with the resource bundle.
Try placing the looked up resource bundle as a properties file in the respective folder denoted by the bundle name.
E.g. if HelpUtilities looks after javax.help.resources.Constants by calling
ResourceBundle.getBundle("javax.help.resources.Constants", locale);

you'd be placing your file in a folder structure at /javax/help/resources/Constants_de_DE.properties. This must be located in your applications "working directory".


text:
Q: How to make tsfresh.extract_features work? tsfresh is a library used for time series analyzing. I am trying to work through the Quick Start Guide in their docs but the code provided seems to not work.
import matplotlib.pyplot as plt
from tsfresh import extract_features, select_features
from tsfresh.utilities.dataframe_functions import impute
from tsfresh.examples.robot_execution_failures import download_robot_execution_failures, \
    load_robot_execution_failures

download_robot_execution_failures()
timeseries, y = load_robot_execution_failures()

extracted_features = extract_features(timeseries,
                                      column_id="id",
                                      column_sort="time")

Output:
Feature Extraction:   0%|          | 0/20 [00:00<?, ?it/s]

This is where tsfresh gets stuck. It seems to do something in the background but does not pass 0%. What am I doing wrong?

A: There have been a few issues mentioning this problem (see #400, #402, #456, #490). For me, the behaviour of extract_feature varies amongst the example notebooks, with some giving me the same error as the one you mentioned. Following #490, turning off multiprocessing with n_jobs=0 fixed most of my issues, e.g.:
extracted_features = extract_features(timeseries,
                                      column_id="id",
                                      column_sort="time",
                                      n_jobs=0)

Note that:

*

*Although issue #490 mentions Windows, this was the case for me on MacOS 10.15

*Still the progress bar sometime remains stuck at 0% despite ongoing processing


text:
Q: Private docker registry on Kubernetes not visible to other pods I have a CoreOS base Kubernetes deployment.  I followed the instruction on GitHub to set up a private Docker registry:
https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/registry/README.md
The registry came up and the registry proxy also came up:
$ kubectl get po --namespace=kube-system
NAME                              READY     STATUS    RESTARTS   AGE
kube-dns-v9-hd0hz                 4/4       Running   0          1d
kube-registry-proxy-10.1.52.113   1/1       Running   0          1d
kube-registry-proxy-10.1.52.114   1/1       Running   0          1d
kube-registry-proxy-10.1.52.117   1/1       Running   0          1d
kube-registry-proxy-10.1.52.118   1/1       Running   0          1d
kube-registry-v0-ib8vx            1/1       Running   0          1d
kubernetes-dashboard-17zfm        1/1       Running   0          1d

I was also able to push private image using the port-forward method (port forward to either the registry pod or the registry proxy pod.)  But when I try to use the image, I get PullImageError:
kubectl run -i --tty ubuntu --image=localhost:5000/myfirstubuntu/ubuntu --restart=Never -- bash

And if I just create a new container with plain ubuntu and try to curl localhost:5000, I don't get the 404 error as shown in the instruction so looks like the pod on the same node is not talking to the registry-proxy as expected.  What are the ways to further debug this?

A: run docker images  to make sure that the value of your image "REPOSITORY" is "localhost:5000/myfirstubuntu/ubuntu"
[root@centos7 ~]# docker images
REPOSITORY                                            TAG                  IMAGE ID            CREATED             VIRTUAL SIZE
localhost:5000/myfirstubuntu/ubuntu                   latest               05e197984182        18 hours ago        516.7 MB

A: Can try add configuration item in /etc/default/docker file
DOCKER_OPTS="$DOCKER_OPTS --insecure-registry=localhost:5000"
then service docker restart
Hope to provide some reference!


text:
Q: Cannot clone from gcloud to git: "Could not find gcloud's git credential helper." I've got a git repository in Google's Cloud Platform.  I'm trying to clone it into a local git report like this:
git config credential.helper gcloud.sh
gcloud source repos clone myrepository --project=myprojectid

It's giving me this error:
ERROR: (gcloud.source.repos.clone) Could not find gcloud's git credential helper. Please make sure the Cloud SDK bi
n folder is in PATH.

I've verified that gcloud is in $PATH:
> which gcloud
/usr/bin/gcloud

This is a new GCE instance of SUSE.  Works on mac but not on this SUSE server.
Any ideas?

A: The Cloud SDK's bin folder needs to be in $PATH, not just gcloud.
/usr/bin/gcloud is likely either a symlink or a wrapper script that points to a full, google-cloud-sdk installation directory. You need to add google-cloud-sdk/bin to your path, since that's where the credential helper is.
(This is due to a limitation in the git-credential-helper model.


text:
Q: Is it possible to determine the size (memory footprint) of an application scoped variable in ColdFusion? We use FusionReactor which will show the overall memory usage at the server level,  but it would be useful to be able to see how much memory individual items stored in the application scope are taking up.

A: Have you looked at http://www.fusion-reactor.com/fr/ or http://www.seefusion.com/
I think both of these server monitors could help you out

A: CFSimplicity,
The Enterprise version of ColdFusion 8 and higher has the Server monitor.  The Server Monitor can  breakdown memory usage and find out what requests and what variable scopes are consuming how much memory. FusionReactor currently can not.
According to a post on the FusionReactor group: http://groups.google.com/group/fusionreactor/browse_thread/thread/8a017a61d17e9840/d57cef46b843207d?lnk=gst&q=memory+request#d57cef46b843207d
James Holmes said:

A CF Standard install could make use
  of the Java SizeOf() class:
  sizeof.sourceforge.net
   sourceforge.net/projects/sizeof
  Some custom code would be necessary to
  create a monitor based on this,  but
  it does work.  mxAjax / CFAjax docs
  and other useful articles:
  www.bifrost.com.au/blog/

A: Is this something that you need to do in real time and/or in production for monitoring? Or is this just something that you need for debugging?
I would suggest just using one of the JVM memory dump tools or maybe launching your app with the JRockit jvm and doing some live analysis with that.
http://www.schierberl.com/blog/coldfusion-memory-leaks-part-i-profiler-introduction/

A: It is possible to see the Application Scope size from ColdFusion, using FusionReactor Application Performance Monitor http://www.fusion-reactor.com - this information is currently captured and stored in one of the log files.   It is also possible to visualize this information using FusionAnalytics - which is able to display and analyze the metrics which have been captured from FusionReactor.  You can see an example of this here - http://docs.intergral.com/display/FA205/CF+Scope+Sizes


text:
Q: Why lone line in fortran code in one part is highlighted and become like comment? I'm trying to write a fortran code for 1 phase flow in porous media.
In discretized equations and other long line I have a below problem as you see in the picture.
After that highlighted phrase my code become like comment.
Can anyone help me?

A: According to this:

In its current state, the syntax highlighting for fixed-form Fortran in the extension only supports a line length of 72 characters. Anything after column 72 appears as comments (green) in the source code, which also affects the appearance of the following lines (when a closing parenthesis is in this green region for example)

You can change it on fortran_fixed-form.tmLanguage.json file or on the VS code settings.