text:
Q: Rhandsontable change datepicker to month-year level I am using Rhandsontable in my app where I want to use month-year level datepicker for my Date column. I have written a code but it is not working. Please refer to below code and let me know if you can find any issue with it.
library(shiny)
library(rhandsontable)

shinyApp(
  ui = fluidPage(
    tags$head(tags$script(src="pikaday.js")),
    tags$head(tags$style(HTML('
                            /* main sidebar */
                            .htDatepickerHolder .pika-table {
                            display: none !important;
                            }'
    ))),
                   tags$head(tags$script(HTML('var picker= new Pikaday(
                                              {
                                              field: document.getElementById("datePicker"),
                                              firstDay: 1,
                                              minDate: new Date(2000, 0, 1),
                                              maxDate: new Date(2020, 12, 31),
                                              yearRange: [2000, 2020],
                                              bound: true,
                                              onDraw: function() { console.log(this.calendars[0].month, this.calendars[0].year); }
                                              });'
      )
                   )
                   ),
    fluidRow(
      column(12
             ,
             rHandsontableOutput('table')
      )
    )
  ),
  server = function(input, output) {
    DF = data.frame(val = 1:10, bool = TRUE, big = LETTERS[1:10],
                    small = letters[1:10],
                    dt = seq(from = Sys.Date(), by = "days", length.out = 10),
                    stringsAsFactors = FALSE)

    # try updating big to a value not in the dropdown
    output$table <- renderRHandsontable(
      rhandsontable(DF, rowHeaders = NULL, width = 550, height = 300) %>%
        hot_col(col = "big", type = "dropdown", source = LETTERS) %>%
        hot_col(col = "small", type = "autocomplete", source = letters,
                strict = FALSE)
    )
  }
)

Pikaday.js used in above code can be referred here:-
https://github.com/dbushell/Pikaday/blob/master/pikaday.js


text:
Q: UI does not update when using a backgroundworker and binding in xaml I am currently trying to update a text box in my UI, through a backgroundworker class. This backgroundworker is in my ViewModel section of my solution, and it only occurs when my application receives data (triggered as an event on my Model).
I have used binding in my MainWindow xaml file to bind the text to properties in my ViewModel, and when breakpoints are set it appears to store the correct values, even though they are still not displayed.
I am not too sure about the split between the DoWork event & the RunWorkerCompleted event. I have the DoWork event setting the data packet to whatever the latest packet received is, and on completion (RunWorkerCompleted), I am assigning the value to the property created in the ViewModel. Have I implemented the backgroundworker class correctly?
Any help on this would greatly be appreciated.
View
<TextBox Height="23" HorizontalAlignment="Left" Margin="577,70,0,0" Name="receiveVariableValueBox" VerticalAlignment="Top" Width="120" Text="{Binding Path=RxVariableValue}"/>

ViewModel
public class DataPointsViewModel : INotifyPropertyChanged
{
    public Model model;

    BackgroundWorker receiveBackground;
    RRTDataPacket rxDataPacket = new RRTDataPacket();

    private int rxVariableValue;
    public int RxVariableValue
    {
        get { return rxVariableValue; }
        set
        {
            if(rxVariableValue != value)
            {
                rxVariableValue = value;
                OnPropertyChanged(rxMajorVersion.ToString());
            }
        }
    }

    public void receivingUpdater(object sender, EventArgs e)
    {
        receiveBackground = new BackgroundWorker();
        receiveBackground.DoWork += new DoWorkEventHandler(receiveBackground_DoWork);
        receiveBackground.RunWorkerCompleted += new RunWorkerCompletedEventHandler(receiveBackground_RunWorkerCompleted);
        receiveBackground.RunWorkerAsync();
    }

    public void receiveBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            if (rxDataPacket != Engine.latestRxDataPacket)
            {
                rxDataPacket = Engine.latestRxDataPacket;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    public void receiveBackground_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(rxDataPacket != null)
        {
            RxMajorVersion = (int)rxDataPacket.majorVersion;
            RxVariableValue = (int)rxDataPacket.variableValue;
        }
    }

A: You have the OnPropertyChanged wrong
public int RxVariableValue
{
    get { return rxVariableValue; }
    set
    {
        if(rxVariableValue != value)
        {
            rxVariableValue = value;
            OnPropertyChanged("RxVariableValue");
        }
    }
}

A: Try calling OnPropertyChanged("RxVariableValue"); in the setter of RxVariableValue

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to create byte buddy subclasses for my controller class. I don't have source code. I have create dynamic classes in another project @RestController
public class HomeController {

    @GetMapping("/home")
    public String homePage() {
        return "welcome to homepage";
    }
}


text:
Q: Effective sentence formation
X had invited person Y on Saturday to have a discussion on a topic on
Sunday (the discussion will happen on Sunday).

Is the above sentence correct? How can this be written effectively?

A:
On Saturday, X invited Y to come the next day and discuss a certain
topic.


text:
Q: Win 10 sound configuration ignores all sound devices All of a sudden, Win 10 Pro reports no sound devices available: The speaker icon in the lower right corner tells me that the speaker configuration is UNKNOWN, and in the win 10 sound setup, there´s no devices detected. However, in device manager all devices are where they should be: These are the onboard realtek sound devices and USB headphones, that have no exclamation marks and are all enabled.
The only thing I´ve done before this happened was to RDP into Windows from a Raspberry with WTWare, and reboot Windows FROM the Raspberry. Usually I don´t reboot this way but directly from the Win 10 machine itself, so I have the idea that maybe, but only maybe, the RDP connection somehow "stole" the audio service. Why? Because when on WTWare, the audio devices are not showing as available for output - all audio is then routed to a virtual audio device on the raspberry - which still works btw if I connect from the Raspberry.
What I have tried is to disable and then enable the onboard sound card in the BIOS, with reboots inbetween but this did not help. I did run the audio troubleshooter in Win 10 too of course, and every time it comes with no solution. It did however the first time tell me something about installing drivers and that I had to reboot, but this solved nothing.
Obviously this is no driver problem, since it´s both the usb headset and the onboard audio card that is not being picked up by the sound settings in Windows.
What could be a solution for this?

A: So, I dunno what caused my audio devices to no longer be considered audio devices in the audio management tool of Windows, but I solved the problem by doing a repair install from a fresh Win 10 ISO that I downloaded at the Microsoft homepage. Please note that the "keep all apps and personal files" was grayed out when trying with an older ISO, but this option was functional in the new one, being crucial for me to not have to install everything again.
So far everything seems to run as it should, and the sound devices again are accessible for Windows to play through :)


text:
Q: Assigning values received from api calls for each element in the loop iteration using Observables I have a foreach loop through which I am iterating and want to call functions which would in turn make async api calls and return value which can be rendered in the html.
The 1st function call getCurrentValue() would return currentTemperatureRef which I finally want to assign receivedCurrentValue and render in html
The 2nd function call getDesiredValue1() would return desiredValueToBeReturned which I finally want to assign receivedDesiredValue1 and render in html
ts
myObj = { droppedItem: [] };
elements = [
   { elementId: 1, elementName: "name1" },
   { elementId: 2, elementName: "name2" },
   { elementId: 3, elementName: "name3" },
   { elementId: 4, elementName: "name4" }
 ];

this.elements.forEach(element => {

    let receivedCurrentValue = this.getCurrentValue(element.name);
    let receivedDesiredValue1 = this.getDesiredValue1(element.id);

 this.myObj.droppedItem.push(receivedCurrentValue)
 this.myObj.droppedItem.push(receivedDesiredValue1)

}

getCurrentValue(eleName){

 //1st api(async api call)
 var ref = this.helperService.getPointIdbyTags(this.existingObj, ['current',
          'temp'], eleName)[0];

 //2nd api(async api call which expects ref value from above api call)
 this.siteService.getHisPointData(ref, 'current')
                    .pipe(
                        map(this.helperService.stripHaystackTypeMapping),
                    )
                    .subscribe(({ rows }) => {
                        if (rows.length > 0) {
                            this.currentTemperatureRef = rows[0].val;
                        }
                    });
}

getDesiredValue1(eleId){
 //1st async api call
 this.siteService.getScheduleParamsByRoomRef('temp and air and desired and
 heating', eleId)
   .subscribe(function (a) {
    let row = a;

      let pointId = this.helperService.stripHaystackTypeMapping(row['id']).split(' ')[0];

      //2nd async api call expecting pointId from above api call
       this.siteService.getHisPointData(pointId, 'current')
         .subscribe(function (a) {
                    let rows = a.rows,
                    if (rows.length > 0) {
                    let desiredValueToBeReturned = rows[0].val;
            )
           }
  )
 }
}

html

{{existingItem.receivedValue}}
{{existingItem.receivedDesiredValue1}}
{{existingItem.receivedDesiredValue2}}

Update
when I try to
getCurrentValue(eleName){
    let roomObj = this.getRoomObj(eleName);
    let equipRef = roomObj.map(equip => equip.entities.filter(entity => entity.entities.length > 0)[0])[0];

    return this.helperService.getPointIdbyTags(this.buildings, ['current',
             'temp'], equipRef.referenceIDs.room)[0].pipe(switchMap((res:any)=>{
                   //we don't want "res" else the response of
                   return  this.siteService.getHisPointData(res, 'current')
                       .pipe(
                           map(this.helperService.stripHaystackTypeMapping),
                       )
              }));
}

I get an error on line => return this.helperService.getPointIdbyTags(this.buildings, ['current',
             'temp'], equipRef.referenceIDs.room)[0].pipe(switchMap(

ERROR TypeError: this.helperService.getPointIdbyTags(...)[0].pipe is
  not a function

A: I don't undestand so much the question, but you need understand some about forkJoin and switchMap. SwitchMap it's usefull when you need make two calls one depending the response of the another. The construction becomes like
callOne.pipe(
  switchMap(resposeOfCallOne=>{
      return callTwo(responseOfCallOne)
  })

If subscribe you received the response of callTwo
forkJoin get an array of calls and return the result in an array
forkJoin([callOne,callTwo])

if subscribe you received an array: res[0] has the response of callOne and res[1] the response of callTwo
Well, First convert your functions getCurrentValue and getDesiredValue1 to return observables
getCurrentValue(eleName){

 return this.helperService.getPointIdbyTags(this.existingObj, ['current',
          'temp'], eleName)[0].pipe(switchMap((res:any)=>{
                //we don't want "res" else the response of
                return  this.siteService.getHisPointData(ref, 'current')
                    .pipe(
                        map(this.helperService.stripHaystackTypeMapping),
                    )
           };
}

getDesiredValue1(eleId){
 return this.siteService.getScheduleParamsByRoomRef('temp and air and desired and
 heating', eleId).pipe(
      switchMap((a:any)=>{
        let row = a;
        let pointId = this.helperService.stripHaystackTypeMapping(row['id']).split(' ')[0];
        return this.siteService.getHisPointData(pointId, 'current')
      }))

Well, when we has an element we want create the two calls, we are going to use forkjoin
We want to make, forEach element create two calls, so we can make
this.elements.forEach(element => {
   forkJoin([this.getCurrentValue(element.name),this.getDesiredValue1(element.id)])
    .subscribe(([current,desired])=>{
        element.current=current;
        element.desired=desired;
    })
})

I user in subscribe ([current,desired]) but we can use res and use element.current=res[0],element.desired=res[1]
If we want, we can even make only one subscription -now we has so many subscriptions as element we have-
arrayOfCalls=[]
this.elements.forEach(element => {
   arrayOfCalls.push(
     forkJoin([this.getCurrentValue(element.name),this.getDesiredValue1(element.id)])
   )
}
//then subscribe
arrayOfCalls.subscribe((fullRes:any[])=>{
    fullRes.map((res,index)=>{
       this.elements[index].currentValue=res[0]
       this.elements[index].desiredValue=res[1]
    })
})


text:
Q: Updating MySQL database with "reindexed" array I'm working on a project where I need to update a database with the values of an array. The starting value must be at 1, instead of 0, so that the right database entries are selected with the update query.
When I print the array (seen below) the results come back starting with a value of 1 but the database isn't updated correctly. The database is still being updated with the 0 value for the array.
foreach($rowPrice as $priceID => $price) {
 $rowPrice = array_combine(range(1, count($rowPrice)), array_values($rowPrice));
  mysql_query("UPDATE ---- SET price='$price' WHERE id='$priceID' AND store_id='$store' LIMIT 1") or die (mysql_error());
}

This is part of the array when it is printed. This part is working but not translating through the update query.

This is how the entries in the database are updated.

As you can see the query is only inserting the array values starting at 2.
What am I doing wrong? Is there a better way to do this?

A: Reindex $rowPrice before you start iterating over it.
$rowPrice = array_combine(range(1, count($rowPrice)), array_values($rowPrice));
foreach($rowPrice as $priceID => $price) {
    mysql_query(...);
}

However this method seems fragile as it makes assumptions about the association between the values in your array and the IDs in the database. It'd be better have the original IDs in the array so you can refer to them during the update.


text:
Q: Is there a thing like regular expressions for numbers? Is there a thing like regular expressions for numbers? I mean a handy notation to specify constraints for numbers. Like say that a number to match must be an odd natural number between -10 and 1000 but not between 3 and 14 and must have a digit 8 in it.

A: Regular expressions are used to express or define regular languages, i.e. the type 3 languages on the Chomsky hierarchy. These languages are those that can be accepted by finite automata, both deterministic and non-deterministic.
The example you have in your question appears to describe languages that cannot be defined by regular expressions, thus cannot be a regular language. Actually it would require an unrestricted grammar, i.e. a Turing-complete language to define your example language.
Luckily, we have plenty of those in the form of programming languages. So the regular expression for numbers that you outline in your question is any programming language!
As for a handy notation, your question seems to call for a series of filters to be applied. Many languages make this easy to express through the use of lambda expressions and higher order functions.


text:
Q: Woocommerce Emails - Sending multiple emails based on product count In Woocommerce, I have a Course product that uses WC Fields to collect student[s] names and email addresses, and custom email template that sends an email when this course product is purchased. As of now, based on the answer in this thread, I am able to collect the email addresses added to those custom fields and send one email to each student as a BCC recipient.
I am now trying to have the emails include the student's name and email address in the body of the email, but I do not want all of the names to appear in the same email. For example, if Student A (studenta@example.com) and Student B (studentb@example.com) are both enrolled in the same purchase, the email received by Student A should just contain in the body something like "Dear Student A, Thank you for enrolling. Use your email address studenta@example.com to login." and the email received by Student B should say the same but with Student B's info, and they should not see the other one's.
So I would have to send multiple emails, based on the number of students being enrolled in that purchase (which is set in the order meta, added from the purchased product's meta).
I tried adding a while() outside of the for() to continue checking through the items until it had gone through all of the items, and sending again for each time it found, but I think the foreach($items as $item) ends up starting through the first item again, since that sends two emails to only the first recipient.
***UPDATED****
I changed the custom email code (which I've stored in my plugins) to:
    $order = wc_get_order( $order_id );
            $items = $order->get_items();
            $course_ordered = false;
            $cqt = 1;
            $emailnum = 0;
        foreach ( $items as $item ) {

            $product_id = $item['product_id'];

            if ( $item['product_id']== 1164 ) {
                $course_ordered = true;
                $emailnum++;
                continue;
            }

        }

    if ( ! $course_ordered )
        return;
    while(  $cqt <= $emailnum ){
        // replace variables in the subject/headings
        $this->find[] = '{order_date}';
        $this->replace[] = date_i18n( woocommerce_date_format(), strtotime( $this->object->order_date ) );
        $this->find[] = '{order_number}';
        $this->replace[] = $this->object->get_order_number();
        if ( ! $this->is_enabled() || ! $this->get_recipient() )
            return;
        // woohoo, send the email!
        $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
        $cqt++;
    }

And the code in my functions.php file, which was from this answer, is:
add_filter( 'woocommerce_email_headers', 'student_email_notification', 20, 3 );
function student_email_notification( $header, $email_id, $order ) {
// Only for 'wc_course_order' notification
if( 'wc_course_order' != $email_id ) return $header;

$student_emails = array();
//$enroll_num = 0;

// Loop though  Order IDs
foreach( $order->get_items() as $item_id => $item_data ){
    /*$course_qty = $item_data->get_quantity();
    $q = 1;
    while ( $q <= $course_qty){
        $enroll_num++;
        // Get the student full Name
        $full_name     = wc_get_order_item_meta( $item_id, 'First Name - '.$enroll_num, true );
        $full_name    .= ' ' . wc_get_order_item_meta( $item_id, 'Last Name - '.$enroll_num, true );
        // Get the student email
        $student_email = wc_get_order_item_meta( $item_id, 'Student Email - '.$enroll_num, true );
        if( ! empty($student_email) && $full_name != ' ' )
            // Format the name and the email and set it in an array
            $student_emails[] = utf8_decode($full_name . ' <' . $student_email . '>'); // Add name + email to the array
        $q++;
    }*/
        // Get the student full Name
        $full_name     = wc_get_order_item_meta( $item_id, 'First Name - 1', true );
        $full_name    .= ' ' . wc_get_order_item_meta( $item_id, 'Last Name - 1', true );
        // Get the student email
        $student_email = wc_get_order_item_meta( $item_id, 'Student Email - 1', true );
        if( ! empty($student_email) && $full_name != ' ' )
            // Format the name and the email and set it in an array
            $student_emails[] = utf8_decode($full_name . ' <' . $student_email . '>'); // Add name + email to the array

}

// If any student email exist we add it
if( count($student_emails) > 0 ){
    // Remove duplicates (if there is any)
    $student_emails = array_unique($student_emails);
    // Add the emails to existing recipients
    $headers .= 'Cc: ' . implode(',', $student_emails) . "\r\n";
}
return $headers;
}

(If the section that is commented out is uncommented, it only sends to the first recipient, and not the second, if it is entered as two separate products, if I remove the while() and use the part below it instead, it sends one email to all recipients)
It sends to all recipients (i.e. gets all of the emails from all of the custom fields and uses those as CC or BCC, however I set it) twice, ie sends the same email twice to everyone. How can I get it to send twice but each time to only one of the recipients? Thank you for any suggestions!

A: I found a solution for the first half of my question - adding the user's names and emails from the product meta to the body of the email - though still have not been able to get it to send a unique email to each email address (email addresses are coming from this meta):
I updated my custom email template (this is only the email template, not the custom function that creates/sends the email) to the following:
<?php
$student_emails = array();
// Loop though  Order IDs
foreach( $order->get_items() as $item_id => $item_data ){
    // Get the student full Name
        $full_name     = wc_get_order_item_meta( $item_id, 'First Name - 1', true );
        $full_name    .= ' ' . wc_get_order_item_meta( $item_id, 'Last Name - 1', true );
        // Get the student email
        $student_email = wc_get_order_item_meta( $item_id, 'Student Email - 1', true );

        print_r('Name: ' . $full_name . ', Login Email: ');
        print_r($student_email . '<br/>');

}

?>

This prints the various users and their emails in the email body.


text:
Q: Apple Maps link not opening native app through Chrome for iOS I've built a custom Google map that includes a function that either sets a link to open in Apple Maps or Google Maps:
function mapsSelector(lat, long) {
  /* If on iOS, open in Apple Maps */
  if ((navigator.platform.indexOf('iPhone') != -1) || (navigator.platform.indexOf('iPad') != -1)) {
    window.open('http://maps.apple.com/?daddr=' + lat + ',' + long + '&dirflg=w');
  /* else, use Google */
  } else {
    window.open('https://www.google.com/maps/dir/?api=1&destination=' + lat + ',' + long + '&travelmode=bicycling');
  }
}

It works on my website when it's run as a web app or in Safari (it opens Apple Maps), but in Chrome for iOS, it briefly opens a new tab, which then immediately closes. If the same URL is opened as a standard href, it works as expected, so I imagine it's something to do with the way the function triggers the link.
To reproduce, you can go to http://nyceboarding.com/map.html, tap on any marker, and then the "Get Directions" link.

A: They key is iOS users use a different protocol at the beginning. Try changing the "http://" in the iOS block to "maps://" and see if that works.

A: Change the
www.google.com/maps/...

to
maps.google.com/maps/...


text:
Q: Android: Numeric key register backspace pressed I have an EditText which only accepts numeric numbers defined like this:
<EditText android:id="@+id/routeInit_price"
    android:layout_height="wrap_content"
    android:layout_width="120dp"
    android:layout_gravity="center_horizontal"
    android:lines="1"
    android:inputType="numberDecimal"/>

I am validating if there is a valid input like below to enable/disable a button. However, I doesn't receive an event on the backspace/delete button pressed event. How can I fix that? Because when the EditText is empty the button should be diabled.
EditText priceField = (EditText)findViewById(R.id.routeInit_price);
priceField.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if(keyEvent.getAction() == KeyEvent.ACTION_UP)
            {
                if(((EditText)view).getText().toString().length() > 0)
                    ready.setEnabled(true);

                else
                    ready.setEnabled(false);
            }

            return false;
        }
});

A: Try this
priceField.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if(priceField.getText().toString().length() > 0)
                ready.setEnabled(true);

            else
                ready.setEnabled(false);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

A: You need to implement your own EditText and override the method onKeyPreIme():
@Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
                        // Do whatever you want to here.
            return true;
        }
        return false;
    }

A:           <EditText
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:digits="0123456789"
                  android:scrollHorizontally="true"
                  android:singleLine="true"
                  android:textSize="14sp" />

A: You need to modify your code something like this:
EditText priceField = (EditText)findViewById(R.id.routeInit_price);

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if(priceField.getText().toString().length() > 0)
                return super.onKeyDown(keyCode, event);
            else
                return true;
        }
        return false;
    }
});


text:
Q: Comparison of the spectrum decomposition In the spectral theorem, we learned that the spectrum of a linear operator $A$ is a disjoint union of: point spectrum (eigenvalues), continuous spectrum (the kernel of $zI-A$ is zero, the closure of $\rm Ran(zI-A)$ is the whole space but the resolvent is unbounded), and the residue spectrum (the closure of ${\rm Ran}(zI-A)$ is not the whole space). We will call this the first way of decomposition.
By the spectral theorem of self-adjoint operators (on Hilbert spaces), we also know that the spectrum of a self-adjoint operator $A$ can be decomposed into pure point spectrum (which is eigenvalues, by the definition from the book of Reed-Simon), the absolutely continuous spectrum and the singular continuous spectrum. It is remarked in the book of Reed-Simon that, in general, the union of these three sets is not the spectrum of $A$.
My question is: for a self-adjoint operator $A$, we already know that its residue spectrum is empty, its continuous spectrum is the union of the singular continuous spectrum and the absolutely continuous spectrum. Therefore, why the union of pure point spectrum, the singular continuous spectrum and the absolutely continuous spectrum is not the spectrum of $A$? Maybe the point spectrum is not just the point spectrum in the first way of decomposition?


text:
Q: What can C++ do that Python cannot? I was reading this post: http://www.quora.com/What-are-the-advantages-of-Python-over-C++
And I am wondering the converse of this question: what can C++ do that Python cannot?
For example, in the realm of performance graphics and GUIs: I understand that C++ would be a better language for high-end game development that requires fancy graphics and great performance, but as far as making GUIs I don't understand the tangible difference between using C++ and QT, or choosing PyQt.
If someone could please make a point-by-point quick rundown like this (e.g., GUIs, high performance graphics, building command line tools, concurrency, etc), it would be very helpful for me to decide whether to choose C++ or Python for my next programming project.

A: Python is a dynamically-typed language. This has two important consequences:

*

*The compiler is unable to reject certain kinds of logical error at compile time which would be caught by a C++ compiler

*Because the types of some (even most) variables cannot be determined at compile time, operations on those variables must be implemented by dynamically dispatching a method call (a fairly slow operation) whereas C++ compilers are often able to generate inline code (which has no overhead). C++ is therefore an inherently faster
language.

The former of these is actually surprisingly useful. See for example the Boost Units library, which allows scientific and engineering code to be written in a way that allows the compiler to statically check that the calculations have logically consistent unit usage at compile time, with no runtime overhead. This would be impossible in Python.
Python also has very poor support for multithreading. Its language design requires certain operations (for instance modifications to lists) to complete atomically, which has lead to the most common implementation using a global lock to prevent two threads executing Python code at the same time (although if one thread calls native code the other will be allowed to procede), because the overhead of locking and unlocking individual objects made single threaded performance terrible.
C++, on the other hand, leaves the job of ensuring code is thread-safe up to the developer, which allows for efficient multithreading.
C++ also gives developers much more control over memory management, allowing for example generic containers that allocate user-specified object types inside their structures (leading to lower overhead and better locality of reference than is possible with Python), allocating objects in specified memory regions (e.g. so that multiple objects can be deleted in a single operation, or to allocate them in a memory-mapped file) or using developer-supplied custom allocators.
C++ is also loosely typed, which means you can use an area of memory for one type of data, and then change to treating it as containing another type. While operations of this type are dangerous (and the language specification states that programs that do this have "undefined behavior"), if you know what you're doing you can use this to implement dynamic loading of code modules, runtime native code generation, direct manipulation of file structures without individually extracting fields as you would have to in Python, and a wide variety of other uses. This is why operating systems can be implemented in C++ and not in Python.

A: Programs which require real-time number crunching (such as digital audio workstations or video players) have what I call a "computational threshold."  What that means is that the choice of programming language can matter when there is not enough hardware horsepower to satisfy the necessary computational load, if the language itself is consuming a substantial part of the CPU's clock cycles.  In other words, if your language is not efficient enough, the application may not work at all.
Consequently, the choice of language depends on whether such a threshold exists.  Naturally, you will have a better chance at writing a functional video player if you do it in a language that is highly efficient, like C++.  The tradeoff is that you will generally write more code (and it will take longer to write), but that is generally true of applications like video players anyway.
For business applications with form-based GUI's, python is often chosen over C++ because, generally speaking, python allows you to code at a higher level of abstraction and with fewer intellectual hurdles than C++ does.  Faster prototyping is thus made possible.
Of course, these are broad generalizations, and your mileage may vary due to factors like the speed of the processor, the number of available cores, the size of the installed RAM, whether you're cross-compiling the python to C, etc, making any definitive decision of which language to use for which application impossible to predict.  As will all performance-related things, measure, don't guess.

A: It is notably an implementation issue, not a language one (however the typing is different in the languages).
Pedantically, both Python & C++ are Turing-complete languages with a lot of bindings to external libraries, so every program you could write in Python could be rewritten in C++ and vice versa.
On Linux, /usr/bin/python (a.k.a. cpython) is a bytecode interpreter
but /usr/bin/g++ is a native compiler
So very often a C++ program would be faster than the equivalent python program.
notice that there are experimental python compilers (e.g. pypy) and experimental C++ interpreters.
So C++ is good for programs which need to be fast, but may accept more development time, and Python is good for programs which need to be written quickly.
You probably won't write a Unix shell or an OS kernel (or even an optimizing C++ compiler) in Python (but in C++ or C), and you probably won't write a sysadmin script or utility in C++ (but in Python).
Also, a C++ program can usually be distributed as a self-contained executable (either statically linked, or using many C++ shared libraries).
At last, C++ is statically typed, and Python is dynamically typed. This means that you would need to do whole program type analysis to compile Python to efficient code. However, some Javascript JIT implementations (e.g. v8) seems to show that dynamically typed languages might be efficiently compiled with a lot of efforts (on implementation development). But nobody paid for such an effort on a mythical Python whole-program compiler implementation.
BTW, some Common Lisp implementations (e.g. SBCL) brings you a dynamic typing and an expressivity close to Python with a performance close to C++.


text:
Q: An Interesting Two Players' Game Involving Cumulative Sum of Uniform Distribution $A$ and $B$ are two players, each have exactly one turn. $A$ goes first. $A$ keeps on choosing a random number uniformly distributed over $(0,1)$ and add the values. If at one point it exceeds $1$, $A$ loses. If $A$ thinks his cumulative sum is very close to $1$, hence there is a risk of losing, he stops. Then $B$ starts the same process and add the values separately. If at one point $B$ exceeds $A$'s sum and still below $1$, he wins. What is the optimal strategy for $A$ to stop adding and what is the probability of winning in that case ($B$ knows the value $A$ stopped at)?
From simulation It appears that the optimal threshold of $A$'s cumulative sum is approximately $0.5772$, which is very close to the Euler-Mascheroni constant $\gamma$.

A: Expanding on the comment by @Ross:
Working backwards, suppose $A$ stopped at $a$, $B$ is currently at $b<a$, and denote $B$'s chances of winning by $p_a(b)$. The strategy of $B$ is trivial: as long as he's below $a$, he has to roll again, and then he can either get to a level $b'<a$, fall between $a$ and $1$ (and win), or exceed $1$ (and lose). Therefore $p_a(b)$ satisfies
$$
p_a(b)=\int_b^ap_a(b')db'+(1-a),
$$
or,
$$
\partial_bp_a(b)=-p_a(b),\quad \lim_{b\rightarrow a}p_a(b)=1-a.
$$
The solution of this is given by $p_b(a)=(1-a)e^{a-b}$, in particular if $B$ takes the value $a$ from $A$, $B$'s chance of winning is $(1-a)e^a$.
Now suppose $A$ is currently at $a$ and has to decide whether to proceed, denote his chance of winning with optimal strategy is $q(a)$. If he stops, his chance of winning if stopping is $1-(1-a)e^a$. If he keeps going, his chance of winning is $\int_a^1q(a')da'$.
Therefore
$$
q(a)=\max\{1-(1-a)e^a,\int_a^1q(a')da'\}
$$
The first term is strictly increasing, the second is strictly decreasing, so there is a unique turning point $a_0$, which is the threshold for $A$ :
$$
1-(1-a_0)e^{a_0}=\int_{a_0}^11-(1-a')e^{a'}da'=(2-a_0)e^{a_0}-a_0-e+1,
$$
or,
$$
(3-2a_0)e^{a_0}-a_0-e=0.
$$
I can't quite solve this, but plugging in $\gamma$ gives $\sim-0.0084$. The actual numerical solution from WolframAlpha is $\sim0.570557$.
Edit: Just as a curiosity, one also gets the total winning chance of $A$, $q(0)=e^{a_0}q(a_0)\sim0.425$


text:
Q: Authenticate a user into D2L using the APP ID and APP KEY If you have authenticated with an APPID and APPKEY and a specific user (meaning when prompted the users username and password have been entered and authenticated) and the system has sent back a USERID and USERKEY.  Can you then make an API call to authenticate that user into D2L so the user arrives at the D2L MY HOME page?
In addition to that...
if the USERID and USERKEY for a specific user are stored in a DB, can you use that data alone to authenticate the user into D2L using an API call so the user arrives at the MY HOME page with no additional login prompt?
I understand that if the USERID and USERKEY have expired this would not work.

A: There are several different issues in this question.
Active web session for a user. Currently, D2L's Valence platform's user authentication does not work this way. The LMS will only provide back a UserID/Key pair as part of the auth process when it can confirm that it has an active session with a user:

*

*API-calling client makes a request directly to the LMS to retrieve a UserID/Key pair for a user.

*a. If the LMS has an active session with a user, (generate if necessary and) return the UserID/Key pair for that application/user pair.
b. If the LMS does not have an active session with a user, go through the login process it has configured to authenticate a user: this could be to redirect the calling web request to the LMS' own user login page, or that redirection could go through a third-party service that the LMS uses to authenticate users (for example, a configured SSO IDP).
What this means: if you use the API to initiate the auth process to retrieve a UserID/Key pair, the calling web browser will (as part of that process) already have an active web-session with the LMS. Either the user will be asked to log in using whatever auth process the LMS uses for that, or the user will already have done so and the calling browser will know that (because it has cookie state indicating an active session).
Programmatic logins. Currently, D2L's Valence platform does not support direct participation in the user authentication process: there are no calls to authenticate the user with the LMS by providing a userid/password or any other secret shared between the user and the LMS. The Valence security model specifically seeks to avoid having the API-calling client know about the authentication secret shared between the user and the LMS.
A client using the Valence Learning Framework APIs needs to either:

*

*Initiate the authentication process by requesting a UserID/Key pair from the LMS (in which case the LMS will seek to auth the user; see the previous answer)

*Rebuild a user context by using a valid UserID/Key pair from a cached state that it has already gathered from the LMS (which, in turn, will have required a real user to authenticate with the LMS)
UserID/Key pair expiry. Note that these auth tokens provided to the calling client by the LMS are intended to be long-lived. They should out-last the current web session that a browser will have for the user. Thus, a client application should treat those as secure data especially in combination with the client application's own ID/Key pair (since the user ID/Key pair is bound app's own ID/Key pair). While we expect client applications to cache these authentication tokens, we also expect them to be cached as sensitive information.
A user's ID/Key pair generated for an application will expire when one of these events happens:

*

*The arrival of the expiry time associated with the ID/Key pair when the LMS generated it (the LMS admins can ensure that the default expiry time value for these tokens is "indefinite")

*The user's password changes (either by the user or an LMS admin resetting it)

*An LMS admin manually revokes client app access for the user


text:
Q: Concourse CI tool to continuously monitor an S3 bucket and trigger job if a file appears I need to be able to trigger a Concourse task when a file appears in an Amazon S3 bucket.
There is this Concourse tool:
https://github.com/pivotalservices/concourse-curl-resource
However I am looking to test for the existence of a file, and if it exists, trigger another job, then delete the file to reset.
Any suggestions?

A: The s3 resource can handle this with a versioned file. Every time you update/change the same file, the resource will detect a new update, and then trigger a job.


text:
Q: redux thunk calling two different api requests trying to call two api's in an action. When one is complete call the other then on the last one pass it off to a reducer.
Looks like my getAttending is getting called at the same time as post and not after post is completed. I'm new to redux-thunk and thought I could just call them one after another as the completed.
   export function postDeclined(id){
        let post = axios.post(blaBla.com);
        let getAttending = axios.get(attending.com);
        return (dispatch) => {
            post.then(()=>{
                getAttending.then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

A: Try doing the api calls like this:
 export function postDeclined(id){
        return (dispatch) => {
             axios.post(blaBla.com).then(()=>{
                 axios.get(attending.com).then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

When you "declared" the calls, you were actually calling the API... so it was doing async...

A: I'd add async/await to your babel config. Makes reading/debugging these things a lot easier.
export const postDeclined => (id) => async (dispatch) => {
  const post await axios.post(blaBla.com);
  const getAttending = await axios.get(attending.com);
  return dispatch({
    type: type.NOT_GOING,
    payload: getAttending.data
  });
};

A: There is a very common problem with the code sample. The function does two things at once: do calls to apis and dispatch an action. Also, please note, that you can chain Promises, you don't need that intermediate callback:
 export const postDeclined = id =>
   axios.post(blaBla.com).then(axios.get(attending.com));

 export const notifyNotGoing = dispatch => promisedResult =>
   promisedResult.then(({data}) =>
     dispatch({
       type: type.NOT_GOING,
       payload: data.data
     })
   );

And then you can call your function like that:
notifyNotGoing(dispatch)(postDeclined(2))

or using composition and currying (I personally prefer Ramda)
const prog = compose(notifyNotGoing(dispatch), postDeclined)
prog(2)


text:
Q: htaccess RewriteRule versioning number I am trying to rewrite the css or js version number but I can't write a descent regex...
I have found some similar rewrite rule for htaccess
RewriteRule ^(.*)\.[\d]+\.(css|js)$ $1.$2 [L] # Strip out the version number

but I don't know how to change it for my sitation:
/assets/min/base_js.16.min.js

or
/assets/min/base_js.16.min.css

has to rewrite to:
/assets/min/base_js.min.css

A: You can use that in your .htaccess:
RewriteRule ^(.+)\.[\d]+\.((?:[^/.]+\.)?(?:css|js))$ $1.$2 [NC,L] # Strip out the version number


text:
Q: Smooth Manifolds and Lie Group Action I have started to read about Lie group action on smooth manifolds.
A question popped up in my mind and I am not sure it's silly or not.
Diff (M) = space of all smooth diffeomorphisms is a large group and usually it's not a Lie group which acts transitively on M.
Is it possible to extract out a Lie group from Diff (M) which still acts transitively?
I am sure it's not true. Can you please provide me an insight as to why?
What would be the consequences? For example, would it have any effect  on sectional curvature if the above group contains its isometric group?

A: As AreaMan's answer is sufficient for the isometry group part of the OP's curiosity, I'll just mention the differential topological part.
I think you may know of the notion of homogeneous space, a (differentiable) manifold $M$ with transitive Lie group action $G$ as diffeomorphisms. And it is well-known that such manifolds can be represented as a quotient $G/H$ by a Lie subgroup $H$. So you have asked the existence of a manifold which is not of such form. This MO posting gives one(in fact, infinitely many).

A: (This is too long to be a comment, too naive to be an answer.)
If $M$ is a Riemannian Manifold, then the group of isometries is a Lie group. This is an old (and apparently difficult) theorem of Myers-Steenrod.
https://en.wikipedia.org/wiki/Myers–Steenrod_theorem
Generally this will not act transitively, if your metric is bumpy or something.
(I think) it's not always possible to put a metric on a manifold for which it becomes a homogeneous space.
Here is a "proof:"
I googled around a bit and found this (a paper by Mostow!): http://www.jstor.org/stable/1969997?seq=1#page_scan_tab_contents
In particular, if a homogeneous space has solvable fundamental group, then this theorem puts a bound on the rank in terms of its dimension. (He defines what he means by rank.)
But now, because (apparently), fundamental groups of 4-manifolds can be pretty much anything you want (they need to be finitely generated), you can probably cook up a counter example.
But you would have to actually read that paper somewhat more carefully than I just did in order to be sure. (I can't read past the first page right now, his definition of homogeneous is on page 3. Maybe it is something completely different!) Let me know!
https://mathoverflow.net/questions/15411/finite-generated-group-realized-as-fundamental-group-of-manifolds


text:
Q: Does running a live wallpaper slow down your PC when gaming or is it no longoer being processed as not on screen? I have just downloaded wallpaper engine from steam and I have set the live wallpaper to highest quality and to run at 60 fps with 8x mmxa and according to task manager its using 22% of my 16gb ram?
Is this normal and  will it stop using the ram as soon as its not onscreen anymore when I start gaming?
my Rig is Alienware ALX 16gb standard Alienware ram 1600hz I-7 3930k overclocked to 3.8 ghz (water cooled) 2x GTX 780 sli with g-synch standard Alienware 1200w power source running an ASUS rog swift 27" 1440p 144ghz monitor. And I ALWAYS run at maximum resolution! and refresh rate.

A: Maybe because, I've used live wallpapers in the past and every time a client opened up the wallpaper paused so it can reduce my ram and CPU usage. But having anything running in the background will slow your PC down a bit. I would like to say, that it uses a fare bit of memory though but I think your PC performance wont have a major effect with live wallpapers running.


text:
Q: Handle response from post request to Json I'm using the following code to get a response from a server after a post request:
type ResponseFromPost struct {
    N_expediente string
    Enviar string
}

func main(){

    ......

    res, err := client.Do(req)
    if err != nil {
        return
    }

    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)

    var re ResponseFromPost
    err = json.Unmarshal(body, &re)
    fmt.Println(re.Enviar);
}

With this I get:
    error: &{%!e(string=array) %!e(*reflect.rtype=&{32 2509985895 0 8 8 25 0x608170
[0x7703c0 <nil>] 0x730b80 0x69acb0 0x6116c0 0x7732c0})}

The value sent by the server is:
[{"n_expediente":"9","enviar":"2"}]

How can I use the json variables?

A: The json is an array of those objects having the strings n_expediente and enviar on each instance. In the Go you'll need an array of your type;
re := []ResponseFromPost{}
err := json.Unmarshal([]byte(`[{"n_expediente":"9","enviar":"2"}]`), &re)
fmt.Println(re[0].Enviar);

Here's an example to show what your model needs to be https://play.golang.org/p/d64Sict4AG
You'll probably want to make some other changes to your code based on that. Like a loop bound by the length of the slice ( for i := range re { print i } ) after the unmarshal and a different name for the type.


text:
Q: Displaying a Facebook Page Feed on a Wordpress Page As the title suggests, I'm trying to display a Facebook Page's feed on a specific page on my website..
Not really sure what the easiest way to do this would be, tried using LifeStream but it was giving me errors when I tried to access it's settings, so scratch that.
Any help to link me to a solution (or give me a solution!) is greatly appreciated. :)

A: The like box should get you what you need, with only a bit of Javascript or an iframe needed.

A: This plugin -> http://wordpress.org/plugins/facebook-feed-grabber/
This widget-> http://wordpress.org/plugins/fbf-facebook-page-feed-widget/
other; http://wordpress.org/plugins/jsl3-facebook-wall-feed/, http://wordpress.org/plugins/custom-facebook-feed/

A: You can create a page badge and copy its code in a Text widget.


text:
Q: I'm confused about what the point of community wiki is So I've read the FAQ, https://blog.stackoverflow.com/2011/08/the-future-of-community-wiki/ and What are "Community Wiki" posts?. Honestly, I'm more confused about what it should be now (even after). Is this merely a voting and points issue? It seems like an attempt to disconnect a question or answer from the user because it is not asked or answered well - if that's the case, what does wiki have to do with it?
I'm not asking saying it should be changed because clearly a lot is written about it but could it summarized in like 1 sentence? Not asking to be argumentative but would just like a crystallized idea.

A: The Community Wiki status is a way to encourage collaboration on an answer, by lowering the required reputation threshold for edits to 100.
That's about it, in a sentence. After suggested edits were introduced, Community Wiki became more a relic of the past than a useful feature. Frankly, it's probably the most abused feature on Stack Exchange, but we don't care because all the possible ways we can abuse it are extremely harmless.

A: I principally use community wiki when I'm doing clean-up.
Example: The user wrote a question and THEN solved his question and put elements of solution in the question body instead of in an answer. Well then I edit the question, fix the issues and remove the solution from the question and put it in an answer. It's not MY answer so I put it in a CW post with the attribution to the author. That way the question is clean, and the answer can now be found easily in an answer.
In fact you can consider making a CW post when you are posting a (good) solution that doesn't come from you AND (very important) you want other people to help you improve it, or think other could come and improve it. For example someone put the solution in comments, but is no longer active and cannot post it in an answer, well then you post it in an answer as CW and mention who it comes from. Please, though, provide an answer that is well formatted and that fits the FAQ about how to answer!
If you take an incomplete answer from comments, and improve it yourself and make it a complete answer, you should take the credit for it and post it with your name.

You should NOT use CW to write answers that you know would get downvoted (and you want to avoid the -rep for it), or as a way to post really incomplete answers.


text:
Q: Is there a way to reduce amount of boilerplate code in Equals and GetHashCode? I frequently have to override Equals and GetHashCode methods for the purpose of unit testing. After this my classes begin to look like this:
public class TestItem
{
    public bool BoolValue { get; set; }

    public DateTime DateTimeValue { get; set; }

    public double DoubleValue { get; set; }

    public long LongValue { get; set; }

    public string StringValue { get; set; }

    public SomeEnumType EnumValue { get; set; }

    public decimal? NullableDecimal { get; set; }

    public override bool Equals(object obj)
    {
        var other = obj as TestItem;

        if (other == null)
        {
            return false;
        }

        if (object.ReferenceEquals(this, other))
        {
            return true;
        }

        return this.BoolValue == other.BoolValue
            && this.DateTimeValue == other.DateTimeValue
            && this.DoubleValue == other.DoubleValue // that's not a good way, but it's ok for demo
            && this.EnumValue == other.EnumValue
            && this.LongValue == other.LongValue
            && this.StringValue == other.StringValue
            && this.EnumValue == other.EnumValue
            && this.NullableDecimal == other.NullableDecimal;
    }

    public override int GetHashCode()
    {
        return this.BoolValue.GetHashCode()
            ^ this.DateTimeValue.GetHashCode()
            ^ this.DoubleValue.GetHashCode()
            ^ this.EnumValue.GetHashCode()
            ^ this.LongValue.GetHashCode()
            ^ this.NullableDecimal.GetHashCode()
            ^ (this.StringValue != null ? this.StringValue.GetHashCode() : 0);
    }
}

While it's not hard to do it, time after time it gets boring and error prone to maintain list of same fields in Equals and GetHashCode. Is there any way to list filelds used for equality checking and hash code function only once? Equals and GetHashCode should be implemented in terms of this setup list.
In my imagination configuration and usage of such setup list may look like
public class TestItem
{
    // same properties as before

    private static readonly EqualityFieldsSetup Setup = new EqualityFieldsSetup<TestItem>()
        .Add(o => o.BoolValue)
        .Add(o => o.DateTimeValue)
        // ... and so on
        // or even .Add(o => o.SomeFunction())

    public override bool Equals(object obj)
    {
        return Setup.Equals(this, obj);
    }

    public override int GetHashCode()
    {
        return Setup.GetHashCode(this);
    }
}

There's a way to auto implement hashCode and equals in java, project lombok for example. I wonder is there anything serving the purpose of reducing boilerplate code readily available for C#.

A: I think it would be possible to implement pretty much the same thing as Lombok in C#, but I'm not feeling that ambitious at the moment.
I believe this is what you are after though (pretty much exactly as you have described it).  This implementation does box all value types into objects, so it's not the most efficient implementation, but it should be good enough for your purpose of unit tests.
public class EqualityFieldsSetup<T>
    where T : class
{
    private List<Func<T, object>> _propertySelectors;

    public EqualityFieldsSetup()
    {
        _propertySelectors = new List<Func<T, object>>();
    }

    public EqualityFieldsSetup<T> Add(Func<T, object> propertySelector)
    {
        _propertySelectors.Add(propertySelector);
        return this;
    }

    public bool Equals(T objA, object other)
    {
        //If both are null, then they are equal
        //    (a condition I think you missed)
        if (objA == null && other == null)
            return true;

        T objB = other as T;

        if (objB == null)
            return false;

        if (object.ReferenceEquals(objA, objB))
            return true;

        foreach (Func<T, object> propertySelector in _propertySelectors)
        {
            object objAProperty = propertySelector.Invoke(objA);
            object objBProperty = propertySelector.Invoke(objB);

            //If both are null, then they are equal
            //   move on to the next property
            if (objAProperty == null && objBProperty == null)
                continue;

            //Boxing requires the use of Equals() instead of '=='
            if (objAProperty == null && objBProperty != null ||
                !objAProperty.Equals(objBProperty))
                return false;
        }

        return true;
    }

    public int GetHashCode(T obj)
    {
        int hashCode = 0;

        foreach (Func<T, object> propertySelector in _propertySelectors)
        {
            object objProperty = propertySelector.Invoke(obj);

            if (objProperty != null)
                hashCode ^= objProperty.GetHashCode();
        }

        return hashCode;
    }
}

A: I've done some research and found several components that were not quite what I wanted:

*

*EqualityComparer (nuget) - does not seem to provide meaningful GetHashCode() by default and too heavyweight to my taste.

*AnonymousComparer (nuget) - does not support GetHashCode() composition.

*MemberwiseEqualityComparer - requires adding custom attribute to exclude member from comparison this way it's not possible to flexibly configure comparisons for existing types. Personally doing Emit for this task is a little bit overkill.

*System.DataStructures.FuncComparer (nuget) - does not support composition.

And also a couple of related discussions:

*

*How to quickly check if two data transfer objects have equal properties in C#?

*Is there a better way to implment Equals for object with lots of fields?
So far idea of having explicitly configured list of members seemed unique. And I implemented my own library https://github.com/msugakov/YetAnotherEqualityComparer. It's better than the code suggested by TylerOhlsen in that it does not box extracted members and it uses EqualityComparer<T> to compare members.
Now the code looks like:
public class TestItem
{
    private static readonly MemberEqualityComparer<TestItem> Comparer = new MemberEqualityComparer<TestItem>()
        .Add(o => o.BoolValue)
        .Add(o => o.DateTimeValue)
        .Add(o => o.DoubleValue) // IEqualityComparer<double> can (and should) be specified here
        .Add(o => o.EnumValue)
        .Add(o => o.LongValue)
        .Add(o => o.StringValue)
        .Add(o => o.NullableDecimal);

    // property list is the same

    public override bool Equals(object obj)
    {
        return Comparer.Equals(this, obj);
    }

    public override int GetHashCode()
    {
        return Comparer.GetHashCode(this);
    }
}

Also the MemberEqualityComparer implements IEqualityComparer<T> and follows its semantics: it can successfully compare default(T) which may be null for reference types and Nullables.
UPDATE: There are tools that can solve the same problem of creating member based IEqualityComparer<T> but also these can provide composite IComparer<T>!

*

*Comparers (by Stephen Cleary) (nuget).

*ComparerExtensions (nuget).


text:
Q: R dplyr: Find a specific value in a column, then replace the adjacent cell in the subsequent columns to the right with that value I am trying to create a matrix of site and time-of-event. In my case, once the event has occurred ("1") it is permanent and cannot go back to a "0". Once a cell in a column is a "1" I am trying to populate the adjacent cell in the subsequent columns to the right with a "1" (see bellow example).
site <- c('A','B','C','D','E','F','G') #site
time <- c(0,1,4,0,3,2,0) # time in which even occured
event <- c(0,1,1,0,1,1,0) # did a event occur
data <- data.frame(site, time, event)

site.time.matrix <- cast(data, site~time)

# This is the output      # This is the desired output
#site   0  1  2  3  4     #site   0  1  2  3  4
#    A  0 NA NA NA NA     #    A  0  0  0  0  0
#    B NA  1 NA NA NA     #    B  0  1  1  1  1
#    C NA NA NA NA  1     #    C  0  0  0  0  1
#    D  0 NA NA NA NA     #    D  0  0  0  0  0
#    E NA NA NA  1 NA     #    E  0  0  0  1  1
#    F NA NA  1 NA NA     #    F  0  0  1  1  1
#    G  0 NA NA NA NA     #    G  0  0  0  0  0

I have found some promising code using dplyr e.g. (Replacing more than one elements with replace function or Apply function to each column in a data frame observing each columns existing data type) which replaces values, although I am unsure of how to specify the adjacent cell in subsequent columns argument.
My apologies if this question is unclear, this is my first post on StackOverflow.
Thank you.

A: It was welcome surprise for a first user post to be detailed, reproducible and interesting, +1!
With na.locf from zoo package you could do:
library(reshape) # for cast function
library(zoo)    #for na.locf function short for if NA, last observation carrried forward, ?na.locf

site <- c('A','B','C','D','E','F','G') #site
time <- c(0,1,4,0,3,2,0) # time in which even occured
event <- c(0,1,1,0,1,1,0) # did a event occur
data <- data.frame(site, time, event)

site.time.matrix <- reshape::cast(data, site~time)

site.time.matrix.fill <- site.time.matrix

# Transpose the matrix excluding first column, carry forward last observation and
# transpose again to return to original matrix structure

site.time.matrix.fill[,-1] <- t(na.locf(t(site.time.matrix.fill[,-1])))

site.time.matrix.fill[is.na( site.time.matrix.fill)] <- 0

site.time.matrix.fill

#  site 0 1 2 3 4
#1    A 0 0 0 0 0
#2    B 0 1 1 1 1
#3    C 0 0 0 0 1
#4    D 0 0 0 0 0
#5    E 0 0 0 1 1
#6    F 0 0 1 1 1
#7    G 0 0 0 0 0

A: A base R approach using apply.
Basically, for every row we are trying to find any element that has 1 in it and assigning 0 to every element in left of it and 1 for every element to the right.
t(apply(site.time.matrix, 1, function(x) {
       temp = if(any(x == 1, na.rm = T)) which(x==1)-1 else length(x)
       x[temp:length(x)] <- 1
       x[0:temp] <- 0
       x
}))

#  0 1 2 3 4
#A 0 0 0 0 0
#B 0 1 1 1 1
#C 0 0 0 0 1
#D 0 0 0 0 0
#E 0 0 0 1 1
#F 0 0 1 1 1
#G 0 0 0 0 0

A: Here is a second base R method (excluding the reshaping). This uses apply and cummax (cumulative maximum). If only one event occurs for each site, then replacing cummax with cumsum would return the same result.
# reshape the data
temp <- cast(data, site~time)

# construct matrix of 0s and 1s
myMat <- as.matrix(temp[-1])
myMat[is.na(myMat)] <- 0

# expand 1s to the right when they appear
myMat <- t(apply(myMat, 1, cummax))

# add row and column names
dimnames(myMat) <- list(levels(temp$site), seq_len(ncol(myMat))-1)

This returns
myMat
  0 1 2 3 4
A 0 0 0 0 0
B 0 1 1 1 1
C 0 0 0 0 1
D 0 0 0 0 0
E 0 0 0 1 1
F 0 0 1 1 1
G 0 0 0 0 0

Note:
The reshaping (with cast) can also be performed with the base R reshape function, but you have to also re-order the variables afterward. For example,
# reshape data
temp <- reshape(data, direction="wide", idvar="site")
# reorder variables
temp <- temp[c("site", sort(names(temp)[-1]))]

would produce the expected data frame.
  site event.0 event.1 event.2 event.3 event.4
1    A       0      NA      NA      NA      NA
2    B      NA       1      NA      NA      NA
3    C      NA      NA      NA      NA       1
4    D       0      NA      NA      NA      NA
5    E      NA      NA      NA       1      NA
6    F      NA      NA       1      NA      NA
7    G       0      NA      NA      NA      NA


text:
Q: RecyclerView blinks when notifyDataSetChanged() is called I am facing the issue that my adapter blinks when adapter.notifyDataSetChanged() or adapter.notifyItemRangeChanged(0,recyclerView.getChildCount()) is called. I have tried so many solutions like setHasStableIds(true) and overiding the getItemId() to return id but it doesn't help me.
if (page == 1) {
    homeAdapter = new HomeAdapter(getActivity(), homeBeanList, Home.
    this, Home.
    this, Home.
    this, profile_pic, Home.
    this, Home.
    this, page);
    loaderDiloag.dismissDiloag();
    recyclerView.setAdapter(homeAdapter);
    recyclerView.setNestedScrollingEnabled(false);
} else {
    if (homeAdapter != null) {
        try {
            loaderDiloag.dismissDiloag();
            recyclerView.setNestedScrollingEnabled(false);
            homeAdapter.notifyItemRangeChanged(0, recyclerView.getChildCount());
        } catch (Exception e) {
            Log.e("error", e.toString() + "");
        }
    } else {
        try {
            homeAdapter = new HomeAdapter(getActivity(), homeBeanList, Home.
            this, Home.
            this, Home.
            this, profile_pic, Home.
            this, Home.
            this, page);
            loaderDiloag.dismissDiloag();
            recyclerView.setAdapter(homeAdapter);
            recyclerView.setNestedScrollingEnabled(false);
            homeAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.e("error", e.toString() + "");
        }
    }

A: Try this
private void removeBlinkAnimationWhenNewItemAdded(){
        ((SimpleItemAnimator)recyclerView).setSupportsChangeAnimations(false)
}


text:
Q: What can be done to promote beta sites? One of the problems that affect the users of beta sites is that they don't get enough views for their questions. So they post off topic questions on reputed SE sites.
Usually, when I post a question in SO, I get at least 10-15 views within the first 5 minutes (The figures are not exact). But, when I posted the question on Project Management beta, there were only 2 views within the first 30 minutes
This is an impediment to the development of a significant user base for the beta sites.
Can we do something to attract more users to the beta sites, at least while they are on the beta stage?
For example - show the questions from the beta sites that the user has signed up for, in her SO account

A: A good answer to the title question

What can be done to promote beta sites?

is community promotion ads. These show up in the sidebar (the upper right-hand corner) on most graduated sites (except Stack Overflow). You must nominate an ad for a beta site on each graduated site you want it on, e.g. here. However, community ads are expected to be for sites related to the site they are being advertised on. You wouldn't add an ad for Aviation on Seasoned Advice, would you?
Another (less up-front) way is to place those ads on your profile, as some users do. I don't know what Stack Exchange thinks of such promotion, so I'll try to cast it in a neutral light, but some do it. I mention what sites I'm active on in my profile purely so people know a bit about me and my contributions to Stack Exchange, not as a plug. I also highly doubt that advertising via profiles does much good - or at least not as much as community ads.
Aside from that, you could go around mentioning the beta site in questions, answers, comments and chat. The downsides to this are

*

*It's not encouraged frowned upon immoral.

*People will think ill of you for it.

*You'll get whacked with the spam-hammer.

Don't do this.

A: I have gone through a bunch of SE meta sites to see if they have any site promotion ideas that we hadn't though of yet at Language Learning. My answer is posted on Language Learning Meta, but I copy it here, with some minor modifications.

*

*A leaflet, see e.g. the leaflet for English Language & Usage.

*A leaflet like this may be used to promote the site at exhibitions (e.g. Expolangues in France, as mentioned on ELL, or Expolingua in Berlin), in public libraries, adult education centres (e.g. Volkshochschulen in Germany), etc. (This idea may not apply to all types of topics on Stack Exchange.)

*A subreddit, as proposed on Linguistics SE.

*A "Language learning flashmob week", like the stats flashmob week proposed on Cross Validated.

*"Polishing" the questions with the highest number of views (example from Language Learning SE), as proposed on French Language SE.

*A question asking competition or question challenge week, as proposed on Chinese Language SE (although there was no response when the idea was repeated two years later). The idea came from a StackOverflow blog post from 2012: Hot Topics: A Contest Formula that Works.

*Writing a great blogpost, as suggested on Chess SE. (This requires publication on a blog with a significant amount of traffic.)

*Creating our own blog, like Worldbuilding SE's blog on Medium. SE announced in December 2014 that it would no longer start community blogs for individual sites.

*Retweeting upvoted questions on Twitter, as suggested on Chess SE. That is ... if the beta site has a Twitter account. (See Why is it so difficult to find the twitter account for a Stack Exchange site?.) Literature SE, for example, has a community-maintained Twitter account.


text:
Q: LateInitializationError: Field 'transaction' has not been initialized Can u please check the both widgets and let me know where is the problem actually? it's been showing me that the transaction hasn't been initialized. in the first widget i've indicated the problem location by ( problem here ) in ListView. Chcek both widget please.
this is transaction_list.dart
import 'package:flutter/material.dart';
import '../widgets/transaction_item.dart';
import '../models/transaction.dart';
import 'package:intl/intl.dart';

class TransactionList extends StatelessWidget {
  // TransactionList({Key? key}) : super(key: key);

  final List<Transaction> transactions;
  final Function deleteTx;

  TransactionList(this.transactions, this.deleteTx);

  @override
  Widget build(BuildContext context) {
    return transactions.isEmpty
        ? LayoutBuilder(
            builder: (context, Constraints) {
              return Column(
                children: [
                  Text(
                    'No transaction added yet!',
                    style: Theme.of(context).textTheme.subtitle2,
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Container(
                    height: Constraints.maxHeight * 0.6,
                    child: Image.asset(
                      'assets/images/waiting.png',
                      fit: BoxFit.cover,
                    ),
                  ),
                ],
              );
            },
          )
        : ListView(
            children: transactions
                .map(
                  (tx) => (problem here) TransactionItem(
                      key: ValueKey(tx.id),
                      transaction: tx,
                      deleteTx: deleteTx),
                )
                .toList(),
          );
  }
}

// ignore_for_file: deprecated_member_use
this is transaction_item.dart
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';

class TransactionItem extends StatefulWidget {
  const TransactionItem({
    Key? key,
    @required this.transaction,
    required this.deleteTx,
  }) : super(key: key);

  final Transaction? transaction;
  final Function deleteTx;

  @override
  State<TransactionItem> createState() => _TransactionItemState();
}

class _TransactionItemState extends State<TransactionItem> {
  late final Transaction? transaction;
  late final Function deleteTx;

  late Color _bgColor;

  @override
  void initState() {
    const availableColors = [
      Colors.red,
      Colors.blue,
      Colors.pink,
      Colors.purple,
    ];

    _bgColor = availableColors[Random().nextInt(4)];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
      elevation: 5,
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: _bgColor,
          radius: 33,
          child: Padding(
            padding: const EdgeInsets.all(6),
            child: FittedBox(
              child: Text('\$ ${transaction?.price}'),
            ),
          ),
        ),
        title: Text(
          transaction!.title,
          style: Theme.of(context).textTheme.titleSmall,
        ),
        subtitle: Text(
          DateFormat.yMMMd().format(transaction!.date),
        ),
        trailing: MediaQuery.of(context).size.width > 460
            ? FlatButton.icon(
                onPressed: () => deleteTx(transaction!.id),
                icon: const Icon(Icons.delete),
                label: const Text('Delete'),
                textColor: Theme.of(context).errorColor,
              )
            : IconButton(
                //to delete the transactions
                icon: const Icon(Icons.delete),
                color: Theme.of(context).errorColor,
                onPressed: () => deleteTx(transaction!.id),
              ),
      ),
    );
  }
}

A: If you like assign widget variable on state class, it will be
class _TransactionItemState extends State<TransactionItem> {
  Transaction? transaction;
  .....
  @override
  void initState() {
    transaction = widget.transaction; //this

or just
class _TransactionItemState extends State<TransactionItem> {
  late Transaction? transaction = widget.transaction;

A: from reading your code, I can say that you forget to assign the value to the transaction, instead of this:
  late final Transaction? transaction;

change it with this:
  final Transaction? transaction = widget.transaction;


text:
Q: Where does my First Responder Chain start? I am in he final step to design my application.
It Basically consists of two tableviews plus other views. Each TableView has its own TableViewController class instance.
What I would like to do is to activate the corresponding menu items when the user clicks one of the table view row. For example, I want to delete the file the user is currently selecting, so the file menu save is activated. But if he is not in the table view, I want to gray it out in the menu.
Therefore, I want to use First Responder. I added menu item, defined an action delete: in the First Responder and linked the menu item to that action. TableViewController is a subclass of NSViewController. In The TableViewController.m, I write in the init method (to insert the view controller in the responder's chain):
    [self setView:_tableView];
    [self setNextResponder:self.view];
    [self.view.subviews enumerateObjectsUsingBlock:^(NSView *subview, NSUInteger idx, BOOL *stop) { [subview setNextResponder:self]; }];

But My method delete: doesn't get called! When the user click the tableview, it becomes the First Responder right? Then THe ViewController should receive the action.
Otherwise, What is the First Responder and how to set it?
I guess I'm missing something!

A: reason it doesn't work
the firstResponder is the first view, or the window, or the app itself that responds to the selectors
basically
id firstResponder = keyView;
while(![firstResponder respondsToSelector:yourSelector] && firstResponder != nil) {
    firstResponder = firstResponder.superview;
}

if(!firstResponder && [keyView.window respondsToSelector:sel]) {
    firstResponder = window;
}

if(!firstResponder && [application respondsToSelector:sel]) {
    firstResponder = application;
}

ViewControllers are not in the responder chain and never get the selector
see https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html
solution
add the VC into the responder chain
id resp = myTableView.nextResponder;
myViewController.nextResponder = resp;
tableView.nextResponder = myViewController;

A: I found the solution to this problem. I just forgot to add a semicolon to my actions when I defined them in the First Responder.
SO I entered "delete" instead of "delete: " And just for this reason, my method -(void)delete:(id)sender was not called!
Thanks for your help anyway!


text:
Q: How to change color of selected text of textarea? I have textarea and i want to change color of selected text.
Example:
var text = "abcdefg";

I want to change color of selected text efg.
here is my code:
var input = document.getElementById('area');
var value = input.value.substr(input.selectionStart, input.selectionEnd - input.selectionStart);
$('#abc').find(value).attr('color',color);

A: Use ::selection CSS selector that select part of text is seleced. You can add your CSS property to selected text of elements.

var textarea = document.querySelector("textarea");
textarea.selectionStart = 12;
textarea.selectionEnd = 23;
::-moz-selection {
    color: red;
}
::selection {
    color: red;
}
<textarea>My textarea highlighted text</textarea>

A: You can't change the selection color for a textarea, you can only change it for non-input objects.
Maybe you should try contenteditable instead of textarea


text:
Q: How to configure consumer-level transactional redelivery with Camel and IBM MQ I am trying to accomplish a transactional JMS client in Java Spring Boot using Apache Camel, which connects to IBM MQ. Furthermore, the client needs to apply an exponential back-off redelivery behavior when processing of messages fails. Reason: Messages from MQ need to be processed and forwarded to external systems that may be down for maintenance for many hours. Using transactions to guarantee at-least once processing guarantees seems the appropriate solution to me.
I have researched this topic for many hours and have not been able to find a solution. I will start with what I currently have:
  @Bean
  UserCredentialsConnectionFactoryAdapter uccConnectionFactoryAdapter ()
      throws IOException {
    MQConnectionFactory factory = new MQConnectionFactory();
    factory.setCCDTURL(tabFilePath);

    UserCredentialsConnectionFactoryAdapter adapter =
        new UserCredentialsConnectionFactoryAdapter();
    adapter.setTargetConnectionFactory(factory);
    adapter.setUsername(userName);
    bentechConnectionFactoryAdapter.setPassword(password);

    return adapter;
  }

  @Bean
  PlatformTransactionManager jmsTransactionManager(@Autowired UserCredentialsConnectionFactoryAdapter uccConnectionFactoryAdapter) {
    JmsTransactionManager txMgr = new JmsTransactionManager(uccConnectionFactoryAdapter);
    return txMgr;
  }

  @Bean()
  CamelContextConfiguration contextConfiguration(@Autowired UserCredentialsConnectionFactoryAdapter uccConnectionFactoryAdapter,
      @Qualifier("jmsTransactionManager") @Autowired PlatformTransactionManager txMgr) {
    return new CamelContextConfiguration() {
      @Override
      public void beforeApplicationStart(CamelContext context) {
        JmsComponent jmsComponent = JmsComponent.jmsComponentTransacted(uccConnectionFactoryAdapter, txMgr);
        // required for consumer-level redelivery after rollback
        jmsComponent.setCacheLevelName("CACHE_CONSUMER");
        jmsComponent.setTransacted(true);
        jmsComponent.getConfiguration().setConcurrentConsumers(1);

        context.addComponent("jms", jmsComponent);
      }

      @Override
      public void afterApplicationStart(CamelContext camelContext) {
        // Do nothing
      }
    };
  }

// in a route builder
...
from("jms:topic:INPUT_TOPIC?clientId=" + CLIENT_ID + "&subscriptionDurable=true&durableSubscriptionName="+ SUBSCRIPTION_NAME)
    .transacted()
    .("direct:processMessage");
...

I was able to verify the transactional behavior through integration tests. If an unhandled exception occurs during message processing, the transaction gets rolled back and retried. The problem is, it gets immediately retried, several times per second, causing possibly significant load on the IBM MQ manager and external system.
For ActiveMQ, redelivery policies are easy to do, with plenty of examples on the net. The ActiveMQConnectionFactory has a setRedeliveryPolicy method, meaning, the ActiveMQ client library has redelivery logic built in. This from all I can tell in line with the documentation of Camel's Transactional Client EIP, which states:

The redelivery in transacted mode is not handled by Camel but by the backing system (the transaction manager). In such cases you should resort to the backing system how to configure the redelivery.

What I absolutely can't figure out is how to achieve the same thing for IBM MQ. IBM's MQConnectionFactory does not have any support for redelivery policies. In fact, searching for redeliverypolicy in the MQ Knowledge Center brings up exactly... drumroll... 0 hits. I even looked a bit through the implementation of the MQConnectionFactory and didn't discover anything either.
Another backing system I looked into was the JmsTransactionManager. Searches for "jmstransactionmanager redelivery policy" or "jmstransactionmanager exponential backoff" did not turn up anything useful either. There was some talk about TransactionTemplate and AbstractMessageListenerContainer but 1) I didn't see any connection to redelivery policies, and 2) I could not figure out how those interact with Camel and JMS.
Sooo, does anybody have any idea how to implement exponential backoff redelivery policies with Apache Camel and IBM MQ?
Closing note: Camel supports redelivery policies on errorHandler and onException are not the same as redelivery policies in the transaction/connection backing system. Those handlers retry at the point of failure using the 'Exchange' object in whichever state it is, without rolling back and reprocessing the message from the start of the route. The transaction remains active during entire rety period, and a rollback only occurs when the errorHandler or onException gives up. This is not what I want for retries that may go on for many hours.

A: Looks like @JoshMc pointed me in the right direction. I managed to implement a RoutePolicy that delays redeliveries with increasing delays. I have run a test session for a few hours and several thousand redeliveries of the same message to see if there are any problems like memory leak, MQ connection exhaustion or so. I did not observe any problems. There were two stable TCP connections to the MQ manager, and memory usage of the Java process moved within a close range.
import java.util.Timer;
import java.util.TimerTask;
import javax.jms.Session;
import lombok.extern.log4j.Log4j2;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Route;
import org.apache.camel.component.jms.JmsMessage;
import org.apache.camel.support.RoutePolicySupport;

@Log4j2
public class ExponentialBackoffPolicy extends RoutePolicySupport implements CamelContextAware {
  final static String JMSX_DELIVERY_COUNT = "JMSXDeliveryCount";
  private CamelContext camelContext;

  @Override
  public void setCamelContext(CamelContext camelContext) {
    this.camelContext = camelContext;
  }

  @Override
  public CamelContext getCamelContext() {
    return this.camelContext;
  }

  @Override
  public void onExchangeDone(Route route, Exchange exchange) {
    try {
      // ideally we would check if the exchange is transacted but onExchangeDone is called after the
      // transaction is already rolled back, and the transaction context has already been removed.
      if (exchange.getException() == null)
      {
        log.debug("No exception occurred, skipping route suspension.");
        return;
      }

      int deliveryCount = getRetryCount(exchange);
      int redeliveryDelay = getRedeliveryDelay(deliveryCount);
      log.info("Suspending route {} for {}ms after exception. Current delivery count {}.",
          route.getId(), redeliveryDelay, deliveryCount);

      super.suspendRoute(route);
      scheduleWakeup(route, redeliveryDelay);
    } catch (Exception ex) {
      // only log exception and let Camel continue as of this policy didn't exist.
      log.error("Exception while suspending route", ex);
    }
  }

  void scheduleWakeup(Route route, int redeliveryDelay) {
    Timer timer = new Timer();
    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {
            log.info("Resuming route {} after redelivery delay of {}ms.", route.getId(), redeliveryDelay);
            try {
              resumeRoute(route);
            } catch (Exception ex) {
              // only log exception and let Camel continue as of this policy didn't exist.
              log.error("Exception while resuming route", ex);
            }
            timer.cancel();
          }
        },
        redeliveryDelay);
  }

  int getRetryCount(Exchange exchange) {
    Message msg = exchange.getIn();
    return (int) msg.getHeader(JMSX_DELIVERY_COUNT, 1);
  }

  int getRedeliveryDelay(int deliveryCount) {
    // very crude backoff strategy for now, will need to refine later
    if (deliveryCount < 10) return 1000;
    if (deliveryCount < 20) return 5000;
    if (deliveryCount < 30) return 20000;
    return 60000;
  }
}

And this is how it being used in route definitions:
    from(mqConnectionString)
        .routePolicy(new ExponentialBackoffPolicy())
        .transacted()
        ...

    // and if you want to distinguish between retriable and non-retriable situations, apply the following two exception handlers
    onException(NonRetriableProcessingException.class)
        .handled(true)
        .log(LoggingLevel.WARN, "Non-retriable exception occurred, discard message.");

    onException(Exception.class)
        .handled(false)
        .log(LoggingLevel.WARN, "Retriable exception occurred, retry message.");

One thing to note is that the JMSXDeliveryCount header comes from the MQ manager, and the redelivery delay is calculated from that. When you restart an application using the ExponentialBackoff policy while a message permanently fails, upon restart it will immediately attempt to reprocess that message but in case of another failure apply a delay corresponding to the total number of redeliveries, and not start over with the initial short delay.


text:
Q: Replicate oh-my-zsh directory tab completion selection with arrow keys With oh-my-zsh they've extended cd tab completion so that, once the directory selection is active, you can move around all the available directories with the arrow keys, rather than just tabbing through them.
Through searching around I'm unable to figure out how it's done. If it's a plugin that does it then that's fine as I can install oh-my-zsh plugins with zplug.

A: To enable the tab-completion menu in zsh, put the following in ~/.zshrc:
autoload -Uz compinit
compinit
zstyle ':completion:*' menu select


text:
Q: Consume external api into kentico What is the best way to consume an external api's data?
Do I need to create a new web api project and set up routing?
In the past I use a web service data source and attached a repeater.  This won't work because I have an API instead of a web service.
Thanks much

A: you can try this, this is how i've converted my JSON / XML apis (or anything really) into a Transformable object, just clone this tool and adjust to your needs
https://devnet.kentico.com/marketplace/utilities/universal-api-viewer-(with-hierarchy-support)
A custom Data Source is what you would still want to do, as all a data source does really is return a Data Table, my tool there takes it another step by assigning it hierarchy structure and psuedo page types so the Repeater can treat them like items on the content tree.

After reading you can now connect externally do the database, you can use Kentico's ConnnectionHelper to connect to the external database via the Connection String, then query it.
If you have access to the external database, then you can use Kentico's ConnectionHelper class to pass in the external database connection string and run queries against it if you wish.
GeneralConnection ConnectionObj = ConnectionHelper.GetConnection("GetConnectionStringFromWeb.ConfigHere");
        ConnectionObj.Open();
        DataSet Results = ConnectionObj.ExecuteQuery(new QueryParameters("select * from SomeTable", null, QueryTypeEnum.SQLQuery));


text:
Q: Get index of Shuffle Range on 2D Array php I want to random 80*13 digits for genetic algorithm where 80 is popsize and 13 is dna size. And I trying to get index of range value on 2d array. To make a random int from 1 - 13 without duplicate where i mean 2d for 80 rows and 13 column. like this
$arr = [0][0]; //this is output will be same with the table value in row1 col1
$arr = [0][1]; //this is output will be same with the table value in row1 col2
...
$arr = [0][12]; //this is output will be same with the table value in row2 col1
$arr = [1][1]; //this is output will be same with the table value in row2 col2
..

i have a code like this.
<?php
function randomGen($min, $max) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0);
}
?>

        Kromosom ke-
        Stasiun Kerja

        <?php
        for ($i=1; $i <= 13; $i++) {
        ?>

                <?php echo $i;?>

        <?php
        }
        ?>

<?php
    for($i = 0; $i < 80; $i++) {
        $no = 1;
        echo " v".$no."	";
        $arr[$i] = randomGen(1,13);
        for ($j=0; $j <= 12; $j++) {
            $arr[$j] = randomGen(1,13);
            echo "";
            echo $arr[$i][$j];
            echo "	";
        }
            echo "
";
            $no++;

    }
    // print_r($arr[0][0].' '); // for see the value is same or not
    ?>

when i try to printout $arr[0][0], thats value is not same with the table in row1 col1.
Any ideas?

UPDATE!

great solution for this problem is answer from Rainmx93 , thats work for me. Thankyou very very much

A: In first for loop you already generating multidimensional array, but now in second loop you override all array elements on each iteration, you need to remove that second function call.
Your code should look like this:
for($i = 0; $i < 80; $i++) {
    $no = 1;
    echo " v".$no."	";
    $arr[$i] = randomGen(1,13);
    for ($j=0; $j <= 12; $j++) {
        echo "";
        echo $arr[$i][$j];
        echo "	";
    }
    echo "
";
    $no++;

}


text:
Q: NSI and DetailPrint not logging I am using the NSISLog plugin in my script with the DLL from the site installed in , however the log file is not written to.
Please advise what I am doing wrong?
!define COMPANYNAME "My Company"
!define APPNAME "My App"

InstallDir "$PROGRAMFILES64\${COMPANYNAME}\${APPNAME}"
!define INSTALL_LOG_NAME "install.log"
!define INSTALL_LOG_PATH "$INSTDIR\${INSTALL_LOG_NAME}"
!define PRODUCT_NAME "${COMPANYNAME} ${APPNAME} ${VERSION}"
Name "${PRODUCT_NAME}"
OutFile "installer.exe"

!macro Log str
    MessageBox MB_OK "${str}." /SD IDOK
    ; Log to NSIS console
    DetailPrint "${str}"
    IfFileExists $INSTDIR 0 +2 ; check exists
    nsislog::log ${INSTALL_LOG_PATH} "${str}"
    ; Log to stdout
    System::Call 'kernel32::GetStdHandle(i -11)i.r9'
    System::Call 'kernel32::AttachConsole(i -1)'
    FileWrite $9 "${str}$\r$\n"
!macroend

Function .onInit
    MessageBox MB_OK "Start." /SD IDOK
FunctionEnd

Section
    SetOutPath $INSTDIR # define output path
    MessageBox MB_OK "Main." /SD IDOK
    nsislog::log "$INSTDIR\hello-main.txt" "hello"
    !insertmacro Log "$\rhello-main"
    File test.txt
    WriteUninstaller $INSTDIR\uninstaller.exe   # define uninstaller name
SectionEnd

Section "Uninstall"
    Delete $INSTDIR\test.txt # Delete installed file
    Delete $INSTDIR\uninstaller.exe # Delete the uninstaller
    RMDir $INSTDIR # Delete the directory
SectionEnd

I am running v3.08 and the flags are below:
PS C:\Program Files (x86)\NSIS> .\makensis.exe /HDRINFO
Size of first header is 28 bytes.
Size of main header is 300 bytes.
Size of each section is 2072 bytes.
Size of each page is 64 bytes.
Size of each instruction is 28 bytes.

Defined symbols: __GLOBAL__,NSIS_CHAR_SIZE=2,NSIS_COMPRESS_BZIP2_LEVEL=9,NSIS_CONFIG_COMPONENTPAGE,NSIS_CONFIG_COMPRESSION_SUPPORT,NSIS_CONFIG_CRC_SUPPORT,NSIS_CONFIG_ENHANCEDUI_SUPPORT,NSIS_CONFIG_LICENSEPAGE,NSIS_CONFIG_PLUGIN_SUPPORT,NSIS_CONFIG_SILENT_SUPPORT,NSIS_CONFIG_UNINSTALL_SUPPORT,NSIS_CONFIG_VISIBLE_SUPPORT,NSIS_CPU=x86,NSIS_DEFAULT_LANG=1033,NSIS_FIX_COMMENT_HANDLING,NSIS_IX86=400,NSIS_LOCKWINDOW_SUPPORT,NSIS_MAX_INST_TYPES=32,NSIS_MAX_STRLEN=1024,NSIS_PACKEDVERSION=0x03008000,NSIS_PTR_SIZE=4,NSIS_SUPPORT_ACTIVEXREG,NSIS_SUPPORT_BGBG,NSIS_SUPPORT_CODECALLBACKS,NSIS_SUPPORT_COPYFILES,NSIS_SUPPORT_CREATESHORTCUT,NSIS_SUPPORT_DELETE,NSIS_SUPPORT_ENVIRONMENT,NSIS_SUPPORT_EXECUTE,NSIS_SUPPORT_FILE,NSIS_SUPPORT_FILEFUNCTIONS,NSIS_SUPPORT_FINDFIRST,NSIS_SUPPORT_FNUTIL,NSIS_SUPPORT_GETDLLVERSION,NSIS_SUPPORT_GETFILETIME,NSIS_SUPPORT_HWNDS,NSIS_SUPPORT_INIFILES,NSIS_SUPPORT_INTOPTS,NSIS_SUPPORT_LANG_IN_STRINGS,NSIS_SUPPORT_MESSAGEBOX,NSIS_SUPPORT_MOVEONREBOOT,NSIS_SUPPORT_NAMED_USERVARS,NSIS_SUPPORT_REBOOT,NSIS_SUPPORT_REGISTRYFUNCTIONS,NSIS_SUPPORT_RENAME,NSIS_SUPPORT_RMDIR,NSIS_SUPPORT_SHELLEXECUTE,NSIS_SUPPORT_STACK,NSIS_SUPPORT_STANDARD_PREDEFINES,NSIS_SUPPORT_STROPTS,NSIS_SUPPORT_VERSION_INFO,NSIS_UNICODE,NSIS_UNICODE_MAKENSIS,NSIS_VARS_SECTION=.ndata,NSIS_VERSION=v3.08,NSIS_WIN32_MAKENSIS,NSISDIR=C:\Program Files (x86)\NSIS

A: That plug-in is not Unicode compatible. You could add Unicode False to the top of your .nsi script but ideally you should build a Unicode installer.
You can just replace the plug-in with a simple function:
!define FileAppendLine '!insertmacro FileAppendLine '
!macro FileAppendLine f l
Push "${l}"
Push "${f}"
Call FileAppendLine
!macroend
Function FileAppendLine
Exch $0
Exch
Exch $1
FileOpen $0 $0 a
StrCmp $0 "" err
FileSeek $0 0 END
!if "${NSIS_CHAR_SIZE}" > 1 ; Replace this with "!if 0" if you always want to force ASCII (not all strings might convert correctly)
FileWriteUTF16LE /BOM $0 $1
FileWriteUTF16LE $0 "$\r$\n"
!else
FileWrite $0 $1
FileWrite $0 "$\r$\n"
!endif
FileClose $0
err:
Pop $1
Pop $0
FunctionEnd

Section
SetOutPath $InstDir
${FileAppendLine} "$InstDir\install.log" "Hello"
${FileAppendLine} "$InstDir\install.log" "World"
SectionEnd


text:
Q: Grouping and staggering estimates with geom_point I have two "main" estimates groupcent_rating and grandcent_rating and I am hoping to plot them along with the model estimates that were stratified by the individual's R-EM status.
help.a <- data.frame(variable = as.factor(c("grandcent_rating", "groupcent_rating", "rem_grand", "rem_group", "white_grand", "white_group")),
                     lower = c(-17.1, -3.7, -25.6, -8, -19.6, -3.5),
                     b = c(-2.3, -0.8, 0.2, -2.4, -3.2, -0.2),
                     upper = c(12.2, 1.9, 25.8, 3.1, 12.9, 2.9),
                     type = c("total", "total", "rem", "rem", "white", "white"))

Using the above example code, I can create the following plot with:
ggplot(help.a, aes(x = variable, y = b))+
  geom_pointrange(aes(ymin=lower,ymax=upper)) +
  coord_flip()

However, I am hoping to only have two variables on the y-axis (after the coord_flip) groupcent_rating and grandcent_rating and then have the White and R-EM estimates staggered (maybe jittered?) around those estimates but in a different color for White and REM.
My attempt is to use color in the aesthetics, but that just changes the color. I cannot figure out how I might jitter or offset these White and REM estimates by groupcent_rating and grancent_rating estimates.
ggplot(help.a, aes(x = variable, y = b, color = type))+
  geom_pointrange(aes(ymin=lower,ymax=upper)) +
  coord_flip()

A: Maybe something like this?
library(stringr)
help.a$y = str_extract(help.a$variable, "grand|group")

ggplot(help.a, aes(x = y, y = b)) +
    geom_pointrange(aes(ymin = lower, ymax = upper, color = type),
                    position = position_dodge(width = 0.2)) +
    coord_flip()


text:
Q: apt-get update on private IPv6 AWS EC2 I have an EC2 on a private subnet with an IPv6 egress-only gateway. The VPC, subnet and EC2 all have IPv6 support and the EC2 has an IPv6 IP address assigned.
I can ping and run curl to pull down content from the internet.
However, when I run apt-get update I timeout:
root@ip-10-0-20-20:~# apt-get update
Hit:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
Err:2 http://us-west-2.ec2.archive.ubuntu.com/ubuntu bionic InRelease  Could not connect to us-west-2.ec2.archive.ubuntu.com:80 (54.191.70.203), connection timed out

I'm assuming this is because it has a private IPv4 address (10.0.0.0/16) and is trying to use this to update? How do I get apt to run under IPv6? Why doesn't it try to connect archive.ubuntu.com via an IPv6 address?
If I try to force IPv6 I get No address associated with hostname, does this mean Ubuntu EC2 packages don't support IPv6??!!
root@ip-10-0-20-20:/var/snap/amazon-ssm-agent/1566# sudo apt-get -o Acquire::ForceIPv6=true update
Err:1 http://us-west-2.ec2.archive.ubuntu.com/ubuntu bionic InRelease
  Something wicked happened resolving 'us-west-2.ec2.archive.ubuntu.com:http' (-5 - No address associated with hostname)

A: It looks like the ec2 package repository mirror doesn't support IPv6.
After running the following to update /etc/apt/sources.list to use archive.ubuntu.com instead it ran fine with IPv6.
sudo sed -i 's/us-west-2\.ec2\.//g' /etc/apt/sources.list
You'll need to change the command to your specific region (us-east-1, etc.)


text:
Q: i got an error stating that === Cannot assign "'12'": "Cart.product" must be a "Product" instance. please do help me out in solving the issue [I have attached an image of my code where you can find the add-to-cart function
and the error is on line=5][1]
def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    product = Product.objects.get(id=product_id)
    Cart(user=user,product=product_id).save()
    return render(request, 'app/addtocart.html')

A: You create the cart with:
Cart.objects.create(user=user, product_id=product_id)
so you assign it to product_id, not product, since product=… expects a Product object.
In that case you can also omit fetchting the product:
def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    Cart(user=user, product_id=product_id).save()
    return render(request, 'app/addtocart.html')

Note: Section 9 of the HTTP protocol
specifies that requests like GET and HEAD should not have side-effects, so you
should not change entities with such requests. Normally POST, PUT, PATCH, and
DELETE requests are used for this. In that case you make a small <form> that
will trigger a POST request, or you use some AJAX calls.

Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.