text:
Q: Linearlayout displaying button incorrectly Just a small issue with my layout that I have when running my app on a smaller device such as a phone, on a tablet it renders fine. One of the buttons seems to be being 'squeezed' by the others and is rendered vertically.
Heres a screenshot of the problem area

my xml is as follows.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="78dp"
            android:layout_height="78dp"
            android:layout_alignParentTop="true" />

        <TextView
            android:id="@+id/txtEventNameTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Name"
            android:textSize="19dp"
            android:textStyle="bold"
            android:layout_below="@+id/imageView1" />

        <TextView
            android:id="@+id/txtEventName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp"
            android:layout_below="@+id/txtEventNameTitle" />

        <TextView
            android:id="@+id/txtEventDateTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Date"
            android:textSize="19dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtEventDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/txtEventTimeTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Time"
            android:textSize="19dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtEventTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/txtEventLocationTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Location"
            android:textSize="19dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtEventLocation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/txtEventDetailsTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Event Details"
            android:textSize="19dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtEventDetails"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp" />

  <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:measureWithLargestChild="true"
        android:orientation="horizontal"
        >

     <Button
            android:id="@+id/btnAddToCal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
                        android:layout_marginBottom="20dp"

            android:text="Add to Calendar"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/btnAddToMyEvents"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add to my Events"
            android:layout_marginTop="20dp"

            android:layout_weight="1"
            android:layout_toRightOf="@+id/btnAddToCal"

            />

        <Button
            android:id="@+id/btnSendToTwitter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Share"
            android:layout_marginTop="20dp"
            android:layout_weight="1"
            android:minWidth="40dp"

            />
         <Button
            android:id="@+id/btnSendToMaps"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Get directions"
                        android:layout_marginTop="20dp"

            android:layout_weight="1"
            android:layout_toRightOf="@+id/btnAddToMyEvents"

         />

   </LinearLayout>

        <fragment
            android:id="@+id/map"
            android:layout_width="fill_parent"
            android:layout_height="300dp"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:layout_marginBottom="10dp"
             />
    </LinearLayout>

</ScrollView>

A: Change your code as below. You are not setting the weightSum as well as you are setting wrap_content to your buttons which is the problem making your buttons displaying in wrong way.
<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:measureWithLargestChild="true"
        android:orientation="horizontal"
        android:weightSum="4">
 <Button
        android:id="@+id/btnAddToCal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
                    android:layout_marginBottom="20dp"

        android:text="Add to Calendar"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btnAddToMyEvents"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Add to my Events"
        android:layout_marginTop="20dp"

        android:layout_weight="1"
        android:layout_toRightOf="@+id/btnAddToCal"

        />

    <Button
        android:id="@+id/btnSendToTwitter"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Share"
        android:layout_marginTop="20dp"
        android:layout_weight="1"
        android:minWidth="40dp"

        />
     <Button
        android:id="@+id/btnSendToMaps"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Get directions"
                    android:layout_marginTop="20dp"

        android:layout_weight="1"
        android:layout_toRightOf="@+id/btnAddToMyEvents"

     />
</LinearLayout>

A: add parameter 'android:weightSum="4"' to your linear layout


text:
Q: expected value properties I'm reading an algorithm proof in which there is a passage I can't understand.
Substantially we have 2 statistically independent random arrays $X$ and $Z$, and a third random array $Y$.
It's known that $Y=XZ$ and $E[Z] = 1$. What the author provides are textually the following passages:
\begin{align}
VAR[Y] &= E[(Y -E[Y])^2]\\
&= E[(X(Z-1) + (X-E[X]))^2]\\
&= (VAR[X]+E[X^2])VAR[Z]+VAR[X]
\end{align}
where $E[X]$ and $VAR[X]$ are the expected value (i.e. mean) and the variance of $X$, respectively.
Trying to understand that proof, I'm getting a different result, as it is:
\begin{align}
VAR[Y] &= E[(Y -E[Y])^2]\\
&= E[(XZ - E[XZ])^2]\\
&= E[(XZ -X +X -E[X])^2]\\
&= E[(X(Z-1) + (X-E[X]))^2]\\
&= E[X^2(Z-1)^2 + (X - E[X])^2 + 2X(Z-1)(X - E[X])]\\
&= E[X^2]E[(Z-1)^2] + VAR[X] + 2E[X(Z-1)(X - E[X])]\quad \text{(then, as $E[Z] = 1$)}\\
&= E[X^2]VAR[Z] + VAR[X] + 2E[X^2Z - ZXE[X] - X^2 + XE[X]]\\
&= E[X^2]VAR[Z] + VAR[X] + 2E[X^2Z] - 2E[ZXE[X]] - 2E[X^2] + 2E[XE[X]]]\\
&= E[X^2]VAR[Z] + VAR[X] + 2E[X^2]E[Z] - 2E[XE[X]]E[Z] - 2E[X^2] + 2E[XE[X]]]\\
&= E[X^2]VAR[Z] + VAR[X] + 2E[X^2] - 2E[XE[X]] - 2E[X^2] + 2E[XE[X]]]\\
&= E[X^2]VAR[Z] + VAR[X] \neq (VAR[X]+E[X^2])VAR[Z]+VAR[X]
\end{align}
Can you help me to understand where am I wrong?
Thank you very much in advance for your attention.
EDIT:
This is the original author proof

A: I don't see in what sense $X$, $Y$ and $Z$ are arrays, especially given $E[Z]=1$; I'll assume that they're just random variables. (Also where you write "pass" it seems you mean "passage".)
Your calculation is correct. You can check this using a simple example, for instance $X$ and $Z$ both uniformly drawn from $\{0,2\}$.
You could considerably shorten your calculation by noting that the expected value of any term of the form $f(X)(Z-1)$ vanishes; that gets rid of the mixed term that the last few lines focus on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximum Actions or Conditions in SharePoint Designer Workflow Is there a recommended or documented maximum of actions and/or conditions that should be used in a single SPD workflow?
I don't think I would be anywhere close, but I just want to make sure that what I'm building won't be too much of a load on the workflow manager since it will be running several workflow instances at once.
I am working with SharePoint Designer 2013.

A: From Software boundaries and limits for SharePoint 2013 inside Workflow limits see Maximum depth of a workflow sub-step in xaml (workflow complexity).

There is a hard limit of 125 for node depth in xaml. The maximum value
  of 121 levels accounts for the default activities (stage, sequence,
  etc.) that SharePoint Designer inserts automatically.

A: When you think of creating an application, you should focus on business logic rather than boundaries. In the long run, it is usually better to find commercial solution without any restrictions and giving you a great possibilities for the future. Try out some free trial solutions such vendors like WEBCON, Nintex or any others and see which one is best for you.


text:
Q: Advanced Magmi value replacer problem I have a CSV which I want to use for import. It has clomuns with compatibility information as follows:

|  |Compatible with Product X|Compatible with Product Y|Compatible with Product Z|
|1 |      Y                  |                         |       Y                 |
|2 |                         |       Y                 |       Y                 |
|3 |      Y                  |       Y                 |                         |
|4 |                         |                         |                         |

I want to use value replacer to map the colums to the my Magento attribute "compatibilty" which is a multiselect box.
The value of the "compatibilty" attribute should be as follows for a single value Product X And for multiple values it should be like this Product X;Product Y;Product Z
I first use the column mapper to map every different cloum to campatibility. Then I use value replacer on the compatibility column. I came up with the following code the make it possible to assign the right values to the right products:

{{ {item.'Product_X}=='Y'?'Product X;':NULL }}{{ {item.'Product_Y}=='Y'?'Product Y;':NULL }}{{ {item.'Product_Z}=='Y'?'Product Z;':NULL }}

Or better readable

{{ {item.'Product_X}=='Y'?'Product X;':NULL }}
{{ {item.'Product_Y}=='Y'?'Product Y;':NULL }}
{{ {item.'Product_Z}=='Y'?'Product Z;':NULL }}

Everything gets set correctly. But the problem is that Magmi sometimes adds an ampty value to the attribute and assigns it to a product. I obviously don't want that.

A: here is a formula that does what you expect (since Magmi value replacer only accepts R-values)
It's a bit complicated, so maybe developing a very simple plugin maybe more readable.
implode(';',array_filter(array({item.Product_X}=='Y'?'Product X':'',{item.Product_Y}=='Y'?'Product Y':'',{item.Product_Z}=='Y'?'Product Z':'')))

it also trims the end ; if any.

A: It will add an empty value because of the trailing ';' that will always be prevalent if any of the columns have 'Y' in them. The empty space after the ';' will represent an empty value.
It is akin to doing this,
$myVar = '';
$myVar .= 'Product X;';
$myVar .= 'Product Y;';

// Product X;Product Y;   (<- empty value here!)

Instead of this:
$myVar = array();
$myVar[] = 'Product X';
$myVar[] = 'Product Y';
$myVarString = implode(';', $myVar);
// Product X;Product Y

You need to do the latter, if Magmi's value mapper will allow it. As this will remove any trailing ';'.


text:
Q: Django ORM JOIN and LEFT JOIN Всем привет помогите не могу составить запрос на Django.Мне нужен вот такой запрос сделать.
SELECT * FROM "crudapp_infohospitals" AS "hospital"
JOIN "crudapp_infohospitals" AS "filiate" ON ( "hospital"."id" = "filiate"."parentId_id")
LEFT JOIN "crudapp_valuehospitals" AS "value" ON ("filiate"."id" = "value"."fkHospitals_id")
WHERE "hospital"."userFK_id" = 1

не чего не выходит с LEFT JOIN. Много перерым тем в интернете и не получается.
вот что пробовал:
InfoHospitals.objects.filter(parentId__userFK__id=1) вот тут INNER JOIN
ValueHospitals.objects.filter(fkHospitals__parentId__userFK__id = id) тут два INNER JOIN .

class InfoHospitals(models.Model):
    avatar = models.ImageField(blank=True)
    names = models.CharField(max_length=255, blank=True, null=True)
    shortName = models.CharField(max_length=255, blank=True, null=True)
    parentId = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
    userFK = models.ForeignKey(User, null=True, on_delete=models.CASCADE)

class ValueHospitals(models.Model):
    create_date = models.DateField(auto_now_add=True, db_index=True)
    subordination = models.CharField(max_length=255, blank=True, null=True)
    nameWLO = models.CharField(max_length=255, blank=True, null=True)
    subjectRF = models.CharField(max_length=255, blank=True, null=True)
    dislocationWLO = models.CharField(max_length=255, blank=True, null=True)
    fkHospitals = models.ForeignKey(InfoHospitals, on_delete=models.CASCADE)

A: Не совсем ответ на Ваш вопрос, но все же.
Метод raw() можно использовать для выполнения необработанных SQL-запросов, которые возвращают экземпляры модели. Пример из документации:
Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')

https://docs.djangoproject.com/en/4.1/topics/db/sql/


text:
Q: Datatable not updated after add,delete or edit using jquery

$(document).ready(function(){
    $('#table').DataTable();
    $('#add').on('click',()=>{
        $("#popup").dialog({
            width:400,
            modal:true,
            resizeable:false,
            buttons:{
                "Submit":function(){
                    var addrow = '
<input type="checkbox" class="select">	'+
                    $('#name').val()+'	'
                    +$("#age").val()+
                    '	'+
                    '<button type="button"  class="edit" >Edit</button>'+
                    '
';
                    $('#table tbody').append(addrow);
                    $('.add-input').val('');
                    $(this).dialog("close");
                }
            }
        });
    })
    $("#delete").on("click", function () {
        $('table tr').has('input:checked').remove();
    })
    $('#deleteall').on('click',function(){
        $('tbody tr').remove();
    })
    $('tbody').on('click',".edit",(event)=>{
        $("#popup").dialog({
            width:400,
            modal:true,
            resizeable:false,
            buttons:{
                "Submit":function(){
        var name = '
<input type="checkbox" class="select">	'+
        $('#name').val()+'	'
        +$("#age").val()+
        '	'+
        '<button type="button"  class="edit" >Edit</button>'+
        '
';
        $(event.currentTarget).parents('tr').replaceWith(name);
        console.log($('tr'));
        $('.add-input').val('');
        $(this).dialog("close");
        }
        }
    })
    })
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>table edit</title>
    <link rel = "stylesheet" type = "text/css" href = "style.css" >

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />

    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>

                Select
                Name
                Age
                Edit

                <input type="checkbox" class="select">
                Sakthi
                20
                <button type="button"  class="edit" >Edit</button>

                <input type="checkbox" class="select">
                Prabhu
                21
                <button type="button"  class="edit" >Edit</button>

                <input type="checkbox" class="select">
                Sakthi
                20
                <button type="button"  class="edit" >Edit</button>

    <button type="button"  class="mod" id="add">Add</button>
    <button type="button"  class="mod" id="delete">Delete</button>
    <button type="button"  class="mod" id="deleteall">Delete All</button>

        <input type="text" placeholder="Name" class="add-input" id="name">
        <input type="number" placeholder="Age" class="add-input" id="age">

After I add,delete or edit a row using my code, I can't search the newly added row using the search option. The newly added row is not shown when I search it. I think the table is not updating when I add or edit a row. Also when I use delete or deleteall, the row is still there when i search for the deleted row. How can I overcome this?
Thank you!

A: Delete all
To delete all row you need to use clear() This method simply removes all rows from the DataTables, resulting in a data length set of 0. New data might then be added using the rows.add() method.
reference: https://datatables.net/reference/api/clear()
Add new row
To add a new row you need to use row.add().
reference:https://datatables.net/reference/api/row.add()
Delete one row
To delete one row you need to use row().remove(), This method (and its plural counterpart, rows().remove()) will remove the selected row from the DataTable completely, deleting the allocated memory for data and node from the browser.
referece: https://datatables.net/reference/api/row().remove()

    $(document).ready(function(){
    var t = $('#table').DataTable();
    $('#add').on('click',()=>{
        $("#popup").dialog({
            width:400,
            modal:true,
            resizeable:false,
            buttons:{
                "Submit":function(){
                    t.row.add( [
                        '<input type="checkbox" class="select">',
                        $('#name').val(),
                        $("#age").val(),
                        ''
                    ] ).draw( false );
                    $(this).dialog("close");
                }
            }
        });
    })
    $("#delete").on("click", function () {
        //$('table tr').has('input:checked').remove();
        t.row( $('table tr').has('input:checked') )
        .remove()
        .draw();
    })
    $('#deleteall').on('click',function(){
        //t.$('tbody tr').remove();
        t.clear().draw();
    })
    $('tbody').on('click',".edit",(event)=>{
        $("#popup").dialog({
            width:400,
            modal:true,
            resizeable:false,
            buttons:{
                "Submit":function(){
        var name = '
<input type="checkbox" class="select">	'+
        $('#name').val()+'	'
        +$("#age").val()+
        '	'+
        '<button type="button"  class="edit" >Edit</button>'+
        '
';
        $(event.currentTarget).parents('tr').replaceWith(name);
        console.log($('tr'));
        $('.add-input').val('');
        $(this).dialog("close");
        }
        }
    })
    })
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>table edit</title>
    <link rel = "stylesheet" type = "text/css" href = "style.css" >

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />

    <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>

                Select
                Name
                Age
                Edit

                <input type="checkbox" class="select">
                Sakthi
                20
                <button type="button"  class="edit" >Edit</button>

                <input type="checkbox" class="select">
                Prabhu
                21
                <button type="button"  class="edit" >Edit</button>

                <input type="checkbox" class="select">
                Sakthi
                20
                <button type="button"  class="edit" >Edit</button>

    <button type="button"  class="mod" id="add">Add</button>
    <button type="button"  class="mod" id="delete">Delete</button>
    <button type="button"  class="mod" id="deleteall">Delete All</button>

        <input type="text" placeholder="Name" class="add-input" id="name">
        <input type="number" placeholder="Age" class="add-input" id="age">


text:
Q: Why would promisify cause a loop to take massively longer? I have an app which has to extract color info from a video and it does this by analyzing each frame. First I extract the frames and then load an array of their locations in memory. As you might imagine, for even a small video it can be in the thousands.
The function I use to extract each frames color info is a promise so I opted to batch an array of promises with Promise.all
With each files absolute path, I read the file with fs and then pass it along to be processed. I've done this with many stand alone images and know the process only takes about a second but suddenly it was taking almost 20min to process 1 image. I finally figured out that using promisify on fs.readFile was what caused the bottle neck. What I don't understand is why?
In the first one fs.readFile is transformed inside of the promise that's returned while in the second one fs.readFile is just used as it normally would be and I wait for resolve to be called. I don't mind using the non-promise one, I'm just curious why this would cause such a slow down?
The second I stopped using promisify the app sped back up to 1 frame / second
The slow code:
   async analyzeVideo(){
    await this._saveVideo();
    await this._extractFrames();
    await this._removeVideo();

    const colorPromises = this.frameExtractor.frames.map(file => {
      return new Promise(resolve => {
        //transform image into data
        const readFile = promisify(fs.readFile);
        readFile(file)
            .then(data => {
              const analyzer = new ColorAnalyzer(data);
              analyzer.init()
                  .then(colors => {
                    resolve(colors)
                  })
            })
            .catch((e)=> console.log(e));
      })
    });
    const colors = await runAllQueries(colorPromises);

    await this._removeFrames();

    this.colors = colors;

    async function runAllQueries(promises) {
      const batches = _.chunk(promises, 50);
      const results = [];
      while (batches.length) {
        const batch = batches.shift();
        const result = await Promise.all(batch)
            .catch(e=>console.log(e));
        results.push(result)
      }
      return _.flatten(results);
    }
  }

The fast code:
async analyzeVideo(){
    await this._saveVideo();
    await this._extractFrames();
    await this._removeVideo();
    const colorPromises = this.frameExtractor.frames.map(file => {
      return new Promise(resolve => {
        //transform image into data
        fs.readFile(file, (err, data) => {
          const analyzer = new ColorAnalyzer(data);
          analyzer.init()
              .then(colors => {
                resolve(colors)
              })
        });
      })
    });
    const colors = await runAllQueries(colorPromises);

    await this._removeFrames();

    this.colors = colors;

    async function runAllQueries(promises) {
      const batches = _.chunk(promises, 50);
      const results = [];
      while (batches.length) {
        const batch = batches.shift();
        const result = await Promise.all(batch)
            .catch(e=>console.log(e));
        results.push(result)
      }
      return _.flatten(results);
    }
  }

A: You don't need to promisify in each loop iteration, just do it once at the top of the module.
Most likely the issue is caused by Promises that are never settled. You are not handling the error correctly, so Promise.all may never finish if an error is thrown.
Instead of logging the error in .catch, you'll have to reject too, or resolve at least if you don't care about the errors. Also analyzer.init() errors are not being catched (if that function can reject)
const readFile = promisify(fs.readFile);
// ...

const colorPromises = this.frameExtractor.frames.map(file => {
   return new Promise((resolve, reject) => {
        //transform image into data
        // const readFile = promisify(fs.readFile);
        readFile(file)
            .then(data => {
              const analyzer = new ColorAnalyzer(data);
              return analyzer.init()
            })
            .then(resolve) // colors
            .catch((e)=> {
              reject(e);
              console.log(e)
            });
      })
})

Aside from that runAllQueries is not doing what you think it's doing. You already executed all the promises.
I recommend you use p-limit instead
const pLimit = require('p-limit');

const limit = pLimit(50);

/* ... */

const colorPromises = this.frameExtractor.frames.map(file => {
   return limit(() => {
        return readFile(file)
            .then(data => {
              const analyzer = new ColorAnalyzer(data);
              return analyzer.init()
            })
            .then(resolve) // colors
    })
})

const colors = await Promise.all(colorPromises);

Furthermore, if you're executing 50 reads at a time, you should increase the value of UV_THREADPOOL_SIZE which defaults to 4.
At your entry point, before any require:
process.env.UV_THREADPOOL_SIZE = 64 // up to 128

Or call the script as: UV_THREADPOOL_SIZE=64 node index.js


text:
Q: How to make REST Call Logout work with Spring Boot, Vaadin 10 and Keycloak 4? I tried this with Keycloak 4.4.0.Final and 4.6.0.Final. I checked the keycloak server log and I saw the following warning messages in the console output.
10:33:22,882 WARN  [org.keycloak.events] (default task-1) type=REFRESH_TOKEN_ERROR, realmId=master, clientId=security-admin-console, userId=null, ipAddress=127.0.0.1, error=invalid_token, grant_type=refresh_token, client_auth_method=client-secret
10:40:41,376 WARN  [org.keycloak.events] (default task-5) type=LOGOUT_ERROR, realmId=demo, clientId=eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqYTBjX18xMHJXZi1KTEpYSGNqNEdSNWViczRmQlpGS3NpSHItbDlud2F3In0.eyJqdGkiOiI1ZTdhYzQ4Zi1mYjkyLTRkZTYtYjcxNC01MTRlMTZiMmJiNDYiLCJleHAiOjE1NDM0MDE2MDksIm5iZiI6MCwiaWF0IjoxNTQzNDAxMzA5LCJpc3MiOiJodHRwOi8vMTI3Lj, userId=null, ipAddress=127.0.0.1, error=invalid_client_credentials

So how did build the HTTP request? First, I retrieved the user principal from the HttpSession and cast to the internal Keycloak instance types:
KeycloakAuthenticationToken keycloakAuthenticationToken = (KeycloakAuthenticationToken) request.getUserPrincipal();
final KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal)keycloakAuthenticationToken.getPrincipal();
final RefreshableKeycloakSecurityContext context = (RefreshableKeycloakSecurityContext) keycloakPrincipal.getKeycloakSecurityContext();
final AccessToken accessToken = context.getToken();
final IDToken idToken = context.getIdToken();

Second, I created the logout URL as in the top stack overflow answer (see  above):
final String logoutURI = idToken.getIssuer() +"/protocol/openid-connect/logout?"+
            "redirect_uri="+response.encodeRedirectURL(url.toString());

And now I then build the rest of the HTTP request like so:
KeycloakRestTemplate keycloakRestTemplate = new KeycloakRestTemplate(keycloakClientRequestFactory);
HttpHeaders headers = new HttpHeaders();
headers.put("Authorization", Collections.singletonList("Bearer "+idToken.getId()));
headers.put("Content-Type", Collections.singletonList("application/x-www-form-urlencoded"));

And also build the body content string:
StringBuilder bodyContent = new StringBuilder();
bodyContent.append("client_id=").append(context.getTokenString())
            .append("&")
            .append("client_secret=").append(keycloakCredentialsSecret)
            .append("&")
            .append("user_name=").append(keycloakPrincipal.getName())
            .append("&")
            .append("user_id=").append(idToken.getId())
            .append("&")
            .append("refresh_token=").append(context.getRefreshToken())
            .append("&")
            .append("token=").append(accessToken.getId());
HttpEntity<String> entity = new HttpEntity<>(bodyContent.toString(), headers);
//   ...
ResponseEntity<String> forEntity = keycloakRestTemplate.exchange(logoutURI, HttpMethod.POST, entity, String.class); // *FAILURE*

As you can observed, I attempted many variations of theme, but I kept getting invalid user authentication.
Oh yeah. I injected the keycloak credentials secret from the application.properties into object instance field with @Value
@Value("${keycloak.credentials.secret}")
private String keycloakCredentialsSecret;

Any ideas from Java Spring Security experienced engineers?
ADDENDUM
I created a realm in KC called 'demo' and a client called 'web-portal'
with the following parameters:
Client Protocol: openid-connect
Access Type: public
Standard Flow Enabled: On
Implicit Flow Enabled: Off
Direct Access Grants Enabled: On
Authorization Enabled: Off

Here is the code that rebuilds the redirect URI, I forgot to include it here.
final String scheme = request.getScheme();             // http
final String serverName = request.getServerName();     // hostname.com
final int serverPort = request.getServerPort();        // 80
final String contextPath = request.getContextPath();   // /mywebapp

// Reconstruct original requesting URL
StringBuilder url = new StringBuilder();
url.append(scheme).append("://").append(serverName);

if (serverPort != 80 && serverPort != 443) {
    url.append(":").append(serverPort);
}

url.append(contextPath).append("/offline-page.html");

That's all


text:
Q: What is a good choice for a free Flash Socket Server I see Red5 which looks nice but it really lacks documentation and since I'm new to using sockets it would be a hassle.
I'm wanting to make a flash chat with audio/video (though just text will work at first) and I enjoy ES but the cheapeast license is $700!  I'm a solo developer so the cost is too high.
The main factor is just having good enough documentation for a new comer.
(I use the flash CS4 IDE if that matters)

A: SmartFoxServer is a good choice. I played around with it a few years ago with AS2, so might be work a look.
They offer a free lite version, but it does not support AS3. I think you need to get the basic plan for that. The pricing plans do look well priced though.
They have some nice documentation and plenty of example.
SmartFoxServer seems to be targeted at multi-player games, but it could be used for your needs.
EDIT*
Just found these Beta AS3 classes for SmartFoxServer. I haven't tried it out for my self though.
EDIT 2*
Another option would be to make your own. It's probably easier than you think if you have a few programming languages under your belt. Of course, this is the kinda thing that can suck your time away.
There are a bunch of tutorials out there for building your own socket server, and some are even specifically for flash. Here are some of the best:

*

*Building a Flash socket server with
Java in five minutes

*Python socket server for Flash

*XML Sockets / Flash / PHP Based Chat App

*Writing Socket Servers in PHP

*Asynchronous Socket Programming in C#
I would definitely suggest using C# .net if you have Windows hosting. It would definitely be the simplest to build and would have the best performance. I would stay away from PHP for anything bigger than a chat app, but if that's all you have then go for it.

A: Try Union. IT's written by one of the best actionscript programmers out there, Colin Moock. The options seem affordable and it's well documented as well.

A: You can get a free flash socket policy server from https://fsps.rpath.org.  I built this appliance for internal use at rPath where I work, but I also maintain it on our free rBuilder Online service.  Just click on the Home tab, and download the type of appliance you want (ISO, vmware image, etc.).  The Appliance is a full system image including the OS (in this case rPath Linux 2) plus the fsps application.
The policy service resides in the fsps package and runs on the standard Adobe port of 843.  By default, it only opens up access to port 443 on the system (https).  The policy file served up lives in /usr/share/fsps if you want to change it.


text:
Q: Datetime / Timespan order by hour I have a list of objects. Each object has a DateTime property.
When I'm adding objects, to this list the DateTime is instantiated through ParseExact.
public class Event
{
    public Event(string time)
    {
         Time = DateTime.ParseExact(time, "HH:mm zzz", CultureInfo.InvariantCulture);
    }

    public DateTime Time { get; set; }
}

This allows me to add items like so:
Events.AddRange(new List<Event> { new Event("07:00 +" + timeZone), new Event("11:30 +" + timeZone), new Event("16:00 +" +timeZone), new Event("19:00 +" + timeZone), new Event("00:00 +" + timeZone), new Event("03:00 +" +timeZone) });

I'm using DateTime, because it handles the timezones in the background.
Problem is; I want to create a list that sorts the above list, with the current time.
so if the list had ["7:30", "5:12", "15:55", "22:22", "23:59"] and the current time is 22:19, it would sort it from that time.
So it would be: ["22:22", "23:59", "5:12", "7:30", "15:55"]
I already have a function that does that:
Events.Sort((x,y) => x.Time.TimeOfDay.CompareTo(y.Time.TimeOfDay));

Problem is that, it's all the same day (Today).
To illustrate with the list above (given the date and time is 25/7 22:19, it would be:
["22:22 25/7", "23:59 25/7", "5:12 25/7", "7:30 25/7", "15:55 25/7"]
I hope this illustrates my point, as the date should turn to the 26th, past midnight, and so on...
Another thing is, that it returns a list as long as the input length, but ideally this could go on forever (hope this makes sense). It would be nice to be able to ask for 10 items, and it will return the next 10 items, from the current time.
Edit: Clarification
I'm getting a list of DateTimes, only the hour and minute of the DateTime object is relevant.
From this moment, I want to get the next 10, 25 or 50 DateTimes objects. This can be generated as the hours and minutes are the only relevant data in the datetime object. The items should then be ordered by now and so forth.
Edit 2: Timezones
In above code, timezone = "0000", UTC.
This will on the users end automatically convert the time to the users current location.

A: You can add 1 day to the dates if they're before the start dates:
Events.Sort((x, y) =>
{
    var xTime = x.Time;
    var yTime = y.Time;
    if (xTime < startTime)
        xTime = xTime.AddDays(1);
    if (yTime < startTime)
        yTime = yTime.AddDays(1);

    return xTime.CompareTo(yTime);
});

Note that I compared the dates, not the TimeOfDay, since the dates no longer have the same day.
This gives the expected result:
Before sort:
25/07/2015 07:30:00
25/07/2015 05:12:00
25/07/2015 15:55:00
25/07/2015 22:22:00
25/07/2015 23:59:00

After sort:
25/07/2015 22:22:00
25/07/2015 23:59:00
25/07/2015 05:12:00
25/07/2015 07:30:00
25/07/2015 15:55:00

A: I ended up doing it like this. Following @JonSkeet, I switched to a TimeSpan object istead of a DateTime.
public List<Event> Events = new List<Event>();

public void InitializeTimers()
{
    Boss tequalt = new Boss("Tequatl the Sunless", BossPriority.HardCore) { Location = "Splintered Coast", Image = "tequatl.jpg" };
    Events.AddRange(new List<Event>
    {
        new Event("07:00", tequalt),
        new Event("11:30", tequalt)
    });
}

public List<Event> GetEvents(int count)
{
    InitializeTimers();
    var timeSpanPattern = Events.OrderBy(x => x.Time.Hours).ThenBy(x => x.Time.Hours);
    var newOrder = new List<Event>();
    var previousTimes = new List<Event>();
    foreach (var timespan in timeSpanPattern)
    {
        if (timespan.Time.CompareTo(DateTime.Now.TimeOfDay) != -1)
            newOrder.Add(timespan);
        else
            previousTimes.Add(timespan);
    }
    newOrder.AddRange(previousTimes);
    var finalList = new List<Event>();
    for (int i = 0; i < count; i++)
    {
        int extraDays = i / (newOrder.Count);
        int current = i - (extraDays * newOrder.Count);
        if (newOrder[current].Time.CompareTo(DateTime.Now.TimeOfDay) != 1)
            extraDays++;
        DateTime time = DateTime.ParseExact(newOrder[current].Time.Hours + ":" + newOrder[current].Time.Minutes + " +0000", "H:m zzz", CultureInfo.InvariantCulture).AddDays(extraDays);
        var newEvent = new Event { Boss = newOrder[current].Boss, DateAndTime = time, Time = newOrder[current].Time};
        newEvent.CalculateCountdown();
        finalList.Add(newEvent);
    }
    finalList.Sort((x,y) => x.DateAndTime.CompareTo(y.DateAndTime));
    return finalList;
}

Given GetEvents(10) (date is 27-7-2015 and time is 11:00), it will return
[0] = Event.DateAndTime = "27-7-2015 11:30";
[1] = Event.DateAndTime = "28-7-2015 7:00";
[2] = Event.DateAndTime = "28-7-2015 11:30";
[3] = Event.DateAndTime = "29-7-2015 7:00";
[4] = Event.DateAndTime = "29-7-2015 11:30";
[5] = Event.DateAndTime = "30-7-2015 7:00";
[6] = Event.DateAndTime = "30-7-2015 11:30";
[7] = Event.DateAndTime = "31-7-2015 7:00";
[8] = Event.DateAndTime = "31-7-2015 11:30";
[9] = Event.DateAndTime = "1-8-2015 7:00";

It isn't pretty at all, but it get's the job done, and allows me to specify how many items I want.
If anybody knows how to optimize above, I will gladly accept it as the answer.


text:
Q: Google Sheets sum(max) in row Is it possible to sum the biggest values of each row?
This will be more clear:
The goal is to move actions from MAX(C1; C2) and SUM(MAX) to one query;

A: impossible, or is it...
if you got only two columns as in your example you can do:
=SUMPRODUCT(IF(C7:C>D7:D; C7:C; D7:D))

for multiple columns you can find the formula here:
https://stackoverflow.com/a/65435321/5632629
(just change avg for max)


text:
Q: How to convert unix timestamp to date in Spark I have a data frame with a column of unix timestamp(eg.1435655706000), and I want to convert it to data with format 'yyyy-MM-DD', I've tried nscala-time but it doesn't work.
val time_col = sqlc.sql("select ts from mr").map(_(0).toString.toDateTime)
time_col.collect().foreach(println)

and I got error:
java.lang.IllegalArgumentException: Invalid format: "1435655706000" is malformed at "6000"

A: You needn't convert to String before applying toDataTime with nscala_time
import com.github.nscala_time.time.Imports._
scala> 1435655706000L.toDateTime
res4: org.joda.time.DateTime = 2015-06-30T09:15:06.000Z

`

A: I have solved this issue using the joda-time library by mapping on the DataFrame and converting the DateTime into a String :
import org.joda.time._
val time_col = sqlContext.sql("select ts from mr")
                         .map(line => new DateTime(line(0)).toString("yyyy-MM-dd"))

A: You can use the following syntax in Java
input.select("timestamp)
            .withColumn("date", date_format(col("timestamp").$div(1000).cast(DataTypes.TimestampType), "yyyyMMdd").cast(DataTypes.IntegerType))

A: Here it is using Scala DataFrame functions: from_unixtime and to_date
// NOTE: divide by 1000 required if milliseconds
// e.g. 1446846655609 -> 2015-11-06 21:50:55 -> 2015-11-06
mr.select(to_date(from_unixtime($"ts" / 1000)))

A: What you can do is:
input.withColumn("time", concat(from_unixtime(input.col("COL_WITH_UNIX_TIME")/1000,
"yyyy-MM-dd'T'HH:mm:ss"), typedLit("."), substring(input.col("COL_WITH_UNIX_TIME"), 11, 3),
typedLit("Z")))

where time is a new column name and COL_WITH_UNIX_TIME is the name of the column which you want to convert. This will give data in millis, making your data more accurate, like: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

A: Since spark1.5 , there is a builtin UDF for doing that.
val df = sqlContext.sql("select from_unixtime(ts,'YYYY-MM-dd') as `ts` from mr")

Please check Spark 1.5.2 API Doc for more info.

A: import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.DateTimeFormat

You need to import the following libraries.
val stri = new DateTime(timeInMillisec).toString("yyyy/MM/dd")

Or adjusting to your case :
 val time_col = sqlContext.sql("select ts from mr")
                     .map(line => new DateTime(line(0).toInt).toString("yyyy/MM/dd"))

There could be another way :
  import com.github.nscala_time.time.Imports._

  val date = (new DateTime() + ((threshold.toDouble)/1000).toInt.seconds )
             .toString("yyyy/MM/dd")

Hope this helps :)


text:
Q: Converting an R dataframe of lists into a dataframe of strings I have a dataframe generated with R in which the individual fields are occupied by lists. Here is an example:
col1 <- list (c("a", "b", "c"), c("d", "e", "f", "g"))

col2 <- list (c("h", "i"), "j")

df = cbind (col1, col2) %>% as.data.frame()

What would be a good way to change the lists in each field into strings?

A: If you want the vectors in each data frame cell concatentated into a single string with comma separators (since you don't specify this in your question), you can do:
df[] <- lapply(df, function(x) sapply(x, function(y) paste(y, collapse = ', ')))

df
#>         col1 col2
#> 1    a, b, c h, i
#> 2 d, e, f, g    j

Or, using tidyverse syntax
library(dplyr)

df %>%
  mutate(across(.fns = ~ map(.x, ~ paste(.x, collapse = ', '))))
#>         col1 col2
#> 1    a, b, c h, i
#> 2 d, e, f, g    j

Created on 2023-01-21 with reprex v2.0.2


text:
Q: Is there any faster way to hide/show html element? I want a faster way to show/hide about 20000+ dom element.
I found that it is very slow using element.style.display = "none"
I think it's because I cause too many reflows of the browser.
But just element.style.visibility = "hidden" is not enough because the height of the element still exists
Is there any better way?
I can only use google closure
There is a runable example. But in my project, there are about 20000+ checkboxes

function filter_change (txt) {
  var eles = document.getElementsByClassName("checkbox_container");
  for (var i = 0; i < eles.length; i++) {
    var cnt = eles[i];
    var ipt = cnt.getElementsByTagName("input")[0];
    if (ipt.id.indexOf(txt.value) < 0) {
      cnt.style.display = "none";
    } else {
      cnt.style.display = "flex";
    }
  }
}

<input type="text" onkeyup="filter_change(this)" />

    <input type="checkbox" id="checkbox_1" value="checkbox_1" class="checkbox_input">
    checkbox_1

    <input type="checkbox" id="checkbox_2" value="checkbox_2" class="checkbox_input">
    checkbox_2

    <input type="checkbox" id="checkbox_3" value="checkbox_3" class="checkbox_input">
    checkbox_3

    <input type="checkbox" id="checkbox_4" value="checkbox_4" class="checkbox_input">
    checkbox_4

    <input type="checkbox" id="checkbox_5" value="checkbox_5" class="checkbox_input">
    checkbox_5

    <input type="checkbox" id="checkbox_10" value="checkbox_10" class="checkbox_input">
    checkbox_10

    <input type="checkbox" id="checkbox_100" value="checkbox_100" class="checkbox_input">
    checkbox_100

    <input type="checkbox" id="checkbox_1000" value="checkbox_1000" class="checkbox_input">
    checkbox_1000

    <input type="checkbox" id="checkbox_10000" value="checkbox_10000" class="checkbox_input">
    checkbox_10000

    <input type="checkbox" id="checkbox_15000" value="checkbox_15000" class="checkbox_input">
    checkbox_15000

    <input type="checkbox" id="checkbox_20000" value="checkbox_20000" class="checkbox_input">
    checkbox_20000

A: You can use CSS:
.checkbox_container input[id*='15'] {
   display: none;
}

See this fiddle
Or use CSS selector in your javascript code, and add class instead:
document.querySelectorAll('.checkbox_container input[id*="' + txt.value '"]')
   .forEach(el => el.classList.add('hidden'))

defining class 'hidden' as:
.hidden { display: none; }

IMPORTANT
With your javascript code, make sure you validate txt.value so that it only contains characters valid for a CSS class name.


text:
Q: getting when running tkinter file NameError: name 'Tk' is not defined Traceback (most recent call last):
  File "tkinter.py", line 2, in <module>
    from tkinter import *
  File "C:\Users\mouad\Desktop\Project 2\tkinter.py", line 11, in <module>
    mainwindow = Tk()
NameError: name 'Tk' is not defined

and when using python directly by running in cmd python I got no issue importing

A: It is not written like that, i advise you to do this :
from tkinter import *
root = Tk()

If i dont work chek if tkinter is well installed.


text:
Q: Django rest api Change oauth response error format I have successfully implemented oauth2 for my django rest api project. I want to change the error response format of the login api.
Current error response is
{
  "error_description": "Invalid credentials given.",
  "error": "invalid_grant"
}

I want to change the error_description key to detail (detail is the key of all other django error responses). I need to make a standardize all the error responses.
Expected result is
{
  "detail": "Invalid credentials given."
}

This is executing from class OAuth2Error(Exception) in /lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py file.

A: I would suggest intercepting this type of response and adapt it as you wish.
There are several ways, but the easiest choice would be to define your own view which is called for the authorization url, which internally calls oauth2 view and modifies response for this case, e.g. something like
from:
from oauth2_provider.views import TokenView
...
    url('auth/token/', TokenView.as_view()),

to:
from oauth2_provider.views import TokenView

def custom_token_view(request, *args, **kwargs):
    response = TokenView.as_view()(request, *args, **kwargs)
    if "invalid_grant " in response.content:
       response = do_whatever_needed(response) # i.e. response.content
    return response

...
    url('auth/token/', custom_token_view),

More flexible/general solution alternative
If you use Django rest framework (DRF) I would suggest:

*

*setting up custom DRF JSON renderer - define your own,

*your custom renderer should inherit default renderer (rest_framework.renderers.JSONRenderer)

*in renderer intercept all responses - by calling default render function and detect this particular one (error=invalid_grant) and customize it

If you don't use DRF:

*

*create custom middleware

*if django < 1.10 then check implementing process_response, if django >=1.10 then call method

*again, intercept all responses and detect only this one, which you can modify as you need


text:
Q: Under what conditions can a function $ y: \mathbb{R} \to \mathbb{R} $ be expressed as $ \dfrac{z'}{z} $? Can an arbitrary function $ y: \mathbb{R} \to \mathbb{R} $ always be expressed as $ \dfrac{z'}{z} $ for some differentiable function $ z: \mathbb{R} \to \mathbb{R} $, or are additional conditions on $ y $ needed for this to be true? This question was inspired by reading a writeup about differential equations, where the change of variables $ y = \dfrac{z'}{z} $ is made.

A: Let $ y: \mathbb{R} \to \mathbb{R} $ be any continuous function. Define $ z: \mathbb{R} \to \mathbb{R} $ by
$$
\forall x \in \mathbb{R}: \quad
z(x) \stackrel{\text{def}}{=} e^{F(x)},
$$
where $ F $ is an antiderivative of $ y $ (which exists). Notice that $ z $ is a positive function. By the Exponential Chain Rule,
$$
\forall x \in \mathbb{R}: \quad
z'(x) = e^{F(x)} \cdot y(x).
$$
Therefore,
$$
\forall x \in \mathbb{R}: \quad
y(x) = \dfrac{e^{F(x)} \cdot y(x)}{e^{F(x)}} = \dfrac{z'(x)}{z(x)}.
$$

Additional Set-Theoretic Information
Let $ y: \mathbb{R} \to \mathbb{R} $, and suppose that there exists a differentiable $ z: \mathbb{R} \to \mathbb{R}^{+} $ such that $ y = \dfrac{z'}{z} $. As $ \dfrac{z'}{z} = (\ln \circ z)' $, it follows that $ y $ is a derivative (or equivalently, $ y $ has an anti-derivative). Then according to the rather fantastic answer in this post, the set of discontinuities of $ y $ is a meager $ F_{\sigma} $-subset of $ \mathbb{R} $.
Conversely, if the set of discontinuities of $ y $ is a meager $ F_{\sigma} $-subset of $ \mathbb{R} $, then $ y $ has an anti-derivative $ F $, which can be used to construct the required function $ z $ in the manner above.

Conclusion: Let $ y: \mathbb{R} \to \mathbb{R} $. Then there exists a differentiable $ z: \mathbb{R} \to \mathbb{R}^{+} $ such that $ y = \dfrac{z'}{z} $ if and only if the set of discontinuities of $ y $ is a meager $ F_{\sigma} $-subset of $ \mathbb{R} $.


text:
Q: What does "What use is X" mean? I've come across this construct on Stack Overflow, in the title of the question "What use is lambda in PHP?"
To me this was an error, so I edited the question changing the title to "What is lambda used for in PHP?" and corrected some other stuff on the question.
Later the original poster changed the title back saying it was not an error and that it changed the voice of the phrase.
I'm not a native English speaker but consider myself pretty fluent in the language, and I have never seen this construct. Not that I remember, at least.
What does it mean?

A: In this case, 'use' is a noun meaning the value or advantage of something (not a verb, as you thought in your correction). So essentially: "what's the usefulness of lambda in PHP?"

A: One of the definitions in Oxford for use as a noun is

the value or advantage of something:
it was no use trying to persuade her
what's the use of crying?

A related definition in the same source is

a purpose for or way in which something can be used:
the herb has various culinary uses

Its use in that sentence is perfectly fine.

A: One thing that nobody's mentioned before is that, while
the verb use is pronounced /yuz/, with a /z/, in all its verbal forms,
the noun use is pronounced /yus/, with an /s/, in all its nominal forms.
So the clause What use is lambda is pronounced /wət 'yusəz 'læmdə/
and not /wət 'yuzəz 'læmdə/, which would be What uses lambda.
If your mind's ear hears the consonants, there isn't a problem.
Rather like the rule for a ~ an or /ðə ~ ði/

A: The meaning doesn't change, but there is a subtle difference in the nuance, or "voice of the phrase".

What use is lambda in PHP?

Sounds to me like the speaker is skeptical of the benefits of using lambda in PHP. They probably know how to create solutions using different methods and don't need to use it, but they are curious about why others would use it instead of something else, or perhaps in a blunt manner, the speaker wants to know why anyone would use lambda instead of using whatever the speaker uses. "What use is..." sounds somewhat negative/pessimistic.

What is lambda used for in PHP?

Sounds more neutral and suggests the speaker is looking for a general run-down of everything that lambda can be used for in PHP. Not necessarily pros or cons, just what parts of PHP it is generally used for. It doesn't suggest that they use alternatives, or that they know of alternatives to using lambda.

A: To provide some context: lambda is concept in programming theory, (seldom discussed in php, not that it cannot be used in php) and 'a lambda' would be a short form for 'a lambda enclosure', so better rewrites would be 'How is lambda used in PHP?' or 'What is a lambda used for in PHP?' Many programmers would try to answer your original rewrite by looking for a lambda keyword, when php does not have one. Don't you just love domain specific jargon (especially in the intersection)?


text:
Q: Swift how to avoid override init?(coder) in subclass A common annoyance with using Swift is that subclasses must implement init?(coder) even if you don't use Storyboard.
required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

It's not elegant. How can I avoid overwriting it in a subclass?

A: If you have a base class, override it in the base class and add the @available(*, unavailable) flag so that its subclasses can avoid overriding the method, and this method also removed from code completion.
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}


text:
Q: OpenCL struct alignment errors I am having troubles with aligning structs between the host and device in OpenCL. I defined many custom structs on both the host and device, and all of them seem to be working perfectly except for one.
I am sending over two structs in an array. All values in the first struct (sObject[0]) are being read correctly in the device, but the second (sObject[1]) is being read in a seemingly corrupt manner where the values are all mixed up and some are missing.
From what I've read, this is possibly a problem with data alignment where the host and device may have different type allocations or padding, but I have verified that the data types have the same size on both the host and device and I have attempted using alignment such as #pragma pack(8), __attribute__ ((aligned (128))) and __attribute__ ((packed)) although I am unsure if they are working correctly with the compiler (VS2017).
Here is the code for the struct on both the host and device:
Host:
typedef struct _cl_tag_sObject {
    cl_double3 m_vCenter;
    cl_double3 m_vBounds1;
    cl_double3 m_vBounds2;
    cl_double m_dRadius;
    cl_bool m_type;
} sObject;

Device:
typedef struct _cl_tag_sObject {
    double3 m_vCenter;
    double3 m_vBounds1;
    double3 m_vBounds2;
    double m_dRadius;
    bool m_type;
} sObject;

Here are the assigned values on the host and the values read from the device:
Host:
m_vCenter = (0,-100.5,0)
m_vBounds1 = (2,2,2)
m_vBounds2 = (3,3,3)
m_dRadius = 100
m_type = 0

Device:
m_vCenter = (0,0,2)
m_vBounds1 = (2,0,3)
m_vBounds2 = (3,0,100)
m_dRadius = 1
m_type = 0

It seems that the value -100.5 is being omitted and the middle values in (2,2,2) and (3,3,3) are taking the place of padding, although I am new to OpenCL and am unsure as to how this process actually works.
What is causing this problem and how can it be solved?
Thanks.

A: WRT struct packing: __attribute__ ((packed)) causes zero padding between struct elements on GCC and LLVM. I don't know if your device's implementation uses them. I have almost no experience with VS, but i think #pragma pack(1) is what you need on host side to get zero padding.
Aside from packing, you need to be aware that the cl_<type>3 types are typedef'ed to cl_<type>4 types in CL/cl_platform.h header. So on the host side, they're essentially the same.
So even with packing, your struct has cl_double4 with 4 elements, and should look like this in host memory (cast to array of doubles):
0 100.5 0 0 | 2 2 2 0 | 3 3 3 0 | 100

I suspect your device's compiler ignores the host convention and uses true 3-element vectors for double3. You can verify simply by changing the device-side struct to use double4:
    double4 m_vCenter;
    double4 m_vBounds1;
    double4 m_vBounds2;

Unfortunately structs are a bit of grey area in OpenCL. Might be best to avoid 3-element vectors inside structs..


text:
Q: There is a PaaS solution that acts like a bastion host for GCP? I am trying to access my VM instances with NO external IP and by security purposes I don't want to open ports or allow SSH policies.
There are solutions in AWS like 'Session Manager', there is something like this in Google Cloud Platform?

A: Google provides Cloud Identity-Aware Proxy (IAP) that allows you to connect to your VM instance that doesn't have an external IP:

With TCP forwarding, IAP can protect SSH and RDP access to your
VMs hosted on Google Cloud. Your VM instances don't even need public
IP addresses.

Have a look at the article Cloud IAP enables context-aware access to VMs via SSH and RDP without bastion hosts first. More details you can find in the documentation Enabling IAP for Compute Engine and Using IAP for TCP forwarding.
I've tried to follow documentation on my test project, you can find my steps below:

*

*create VM instance without external IP:
gcloud compute instances create instance-1 --zone=us-central1-a --machine-type=e2-medium --subnet=default --no-address --maintenance-policy=MIGRATE --image=ubuntu-1804-bionic-v20200610 --image-project=ubuntu-os-cloud

*go to Security -> Identity-Aware Proxy and enable Identity-Aware Proxy API.

*configure GCP Firewall to enable inbound traffic from Cloud IAP:
gcloud compute firewall-rules create allow-ssh-ingress-from-iap --direction=INGRESS --action=allow --rules=tcp:22 --source-ranges=35.235.240.0/20

*connect to VM instance via IAP tunnel:
$ gcloud compute ssh instance-1 --tunnel-through-iap --zone=us-central1-a
Warning: Permanently added 'compute.3924477895872840881' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 5.3.0-1026-gcp x86_64)
...
instance-1:~$

In addition, have a look at the 3rd party video tutorial.


text:
Q: IE.Document.getElementsByName("name").Value = "Value" not working When I try and do this, it throws a number of errors at me depending on other bits of my code, such as the method is not associated with that object or an unspecified error.
I am trying to go down a list of Excel cells with strings and use a web form to search for those strings.
My code currently looks like this:
Sub YSF_automation()
    Application.ScreenUpdating = False

    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "URL"

    While IE.Busy
        DoEvents
    Wend

    IE.Document.getElementsByName("ElementName")(0).Value = "test"

End Sub

A: Try the below
Option Explicit

Dim IE as Object

Sub YSF_automation()
    Application.ScreenUpdating = False

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "URL"

While IE.Busy
    DoEvents
Wend

set document = IE.document
with document
    .getElementsByName("ElementName")(0).value="test"
end with
End Sub


text:
Q: Pandas Groupby sort by Index I have negative values in my index column of my groupby.  I need to sort these as numbers, not as text.  Here is my group by and my attempt at sorting, which has been unsuccessful:
df_counts = df.groupby('DAYSLATE')[['DAYSLATE']].count()
df_counts = df_counts.sort_index().astype(int)

Here is my current output:
          DAYSLATE DAYSLATE_PCT  CUMULATIVE CUM_PCT
DAYSLATE
-1              59        7.73%          59   7.73%
-129             1        0.13%          60   7.86%
-2               7        0.92%          67   8.78%
-230             1        0.13%          68   8.91%
-3               1        0.13%          69   9.04%
0              486        63.7%         555  72.74%
1               98       12.84%         653  85.58%
10               3        0.39%         656  85.98%
11               3        0.39%         659  86.37%
14               2        0.26%         661  86.63%
2               33        4.33%         694  90.96%
260              1        0.13%         695  91.09%
3               18        2.36%         713  93.45%
4               25        3.28%         738  96.72%
5               10        1.31%         748  98.03%
6                3        0.39%         751  98.43%
7                2        0.26%         753  98.69%
70               1        0.13%         754  98.82%
8                4        0.52%         758  99.34%
9                5        0.66%         763  100.0%

A: If you want to leave the index as it is but just want to sort as if it were numeric...
df_counts.iloc[df_counts.index.astype(int).argsort()]

          DAYSLATE.1 DAYSLATE_PCT  CUMULATIVE CUM_PCT
DAYSLATE
-230               1        0.13%          68   8.91%
-129               1        0.13%          60   7.86%
-3                 1        0.13%          69   9.04%
-2                 7        0.92%          67   8.78%
-1                59        7.73%          59   7.73%
0                486        63.7%         555  72.74%
1                 98       12.84%         653  85.58%
2                 33        4.33%         694  90.96%
3                 18        2.36%         713  93.45%
4                 25        3.28%         738  96.72%
5                 10        1.31%         748  98.03%
6                  3        0.39%         751  98.43%
7                  2        0.26%         753  98.69%
8                  4        0.52%         758  99.34%
9                  5        0.66%         763  100.0%
10                 3        0.39%         656  85.98%
11                 3        0.39%         659  86.37%
14                 2        0.26%         661  86.63%
70                 1        0.13%         754  98.82%
260                1        0.13%         695  91.09%

Otherwise, you can set the index to numeric
df_counts.set_index(df_counts.index.astype(int)).sort_index()

          DAYSLATE.1 DAYSLATE_PCT  CUMULATIVE CUM_PCT
DAYSLATE
-230               1        0.13%          68   8.91%
-129               1        0.13%          60   7.86%
-3                 1        0.13%          69   9.04%
-2                 7        0.92%          67   8.78%
-1                59        7.73%          59   7.73%
0                486        63.7%         555  72.74%
1                 98       12.84%         653  85.58%
2                 33        4.33%         694  90.96%
3                 18        2.36%         713  93.45%
4                 25        3.28%         738  96.72%
5                 10        1.31%         748  98.03%
6                  3        0.39%         751  98.43%
7                  2        0.26%         753  98.69%
8                  4        0.52%         758  99.34%
9                  5        0.66%         763  100.0%
10                 3        0.39%         656  85.98%
11                 3        0.39%         659  86.37%
14                 2        0.26%         661  86.63%
70                 1        0.13%         754  98.82%
260                1        0.13%         695  91.09%


text:
Q: Segmentation fault after function call in x86 assembly I'm currently writing a compiler and I have created some tests and only one of them fails with Segmentation fault (core dumped) as error message.
This is the code that gets compiled
function main(): int {
    var f: int = 10;
    return func(f) - func(f / 2);
}

function func(a: int): int {
    return a;
}

And this is the generated assembly code (it's not really optimized as you can see)
section .text
global _start
_start:
    call function_main
    mov rdi, rax
    mov rax, 60
    syscall

global function_main
function_main:
    push rbp
    mov rbp, rsp
    sub rsp, 4
    mov rax, 10
    mov DWORD[rbp-0], eax
    mov eax, DWORD[rbp-0]
    mov rdi, rax
    call function_func
    push rax
    mov eax, DWORD[rbp-0]
    mov rbx, 2
    idiv rbx
    mov rdi, rax
    call function_func
    mov rbx, rax
    pop rax
    sub rax, rbx
    mov rsp, rbp
    pop rbp
    ret

global function_func
function_func:
    push rbp
    mov rbp, rsp
    sub rsp, 4
    mov DWORD[rbp-0], edi
    mov eax, DWORD[rbp-0]
    mov rsp, rbp
    pop rbp
    ret

The assembly file is compiled with nasm -f elf64 ./test9.lv.asm -o ./test9.lv.asm.o and ld -g ./test9.lv.asm.o a.out
I've used gdb to debug the binary file and it seems like the program receives the SIGSEGV signal right after func(f) returns the first time.
But now I don't know why this is happening in this case.


text:
Q: for each loop help in Rails. Trying to count data in each table. Quick one. How can I pull in the number of courses that are completed to show in a for each block in the a view. Currently as the code loops through all the categories it only brings in the category_id result based on my hard code of 1. How can I get this loop to pull in the category Id for each of the categories in my block code so that i can count only courses showing as not complete in my view. I've shown the controller and view code below. The parts that are related. Thanks.
View loop
   <% @categories.each do |category| %>

                                        <% if category.name.length < 20 %>

<%= category.name %>

                                        <% else %>

<%= category.name %>

                                        <% end %>

<%= @categories_active.count %>

                                        <% if @categories_active.count > 1 || @categories_active.count < 1 %>

Courses available

                                        <% else %>

Course available

                                        <% end %>

                                     <%= link_to "See All", courses_categories_path(category_id: category.id), class: "cat-item-heading no-link-style", method: :post %>

 <% end %>

Controller variable being pulled from DB
@categories = Category.all.order("created_at ASC").limit(12)
@categories_active = Course.where(category_id: 1)
@categories_active = @categories_active.where(complete: false)

Any direction appreciated. Currently it just counts all courses in the category_id 1 and displays the same count across all the categories shown. I'm trying to extract the category_id out in the loop or controller so I can display a count for each of the courses that are false in each category in the loop. Thanks.

A: I think you can get the count number for each of the courses that are false in each category by adding like this in your view
   <% @categories.each do |category| %>
      .....
      Uncompleted course count number for <%= category.name %> category: <%= category.courses.where(complete: false).count %>
      .....

   <% end %>


text:
Q: Appending characters to strings in XSL This XML has details of the string to be appended, string length and character to append.
<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
    <input>
        <string>Auckland</string>
        <len>12</len>
        <char>#</char>
    </input>

    <input>
        <string>Ohio</string>
        <len>3</len>
        <char>*</char>
    </input>
 </data>

I also have an XSLT which should (ideally) use this logic:
while (length of string < specified length){
 concatenate(char, string)
}
else
{ truncate string to the specified length}
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="append" match="/">
    <xsl:param name="char"></xsl:param>
    <xsl:param name="string"></xsl:param>
    <xsl:param name="len"></xsl:param>
    <xsl:value-of select="$string" />

    <xsl:for-each select="data/input">
        <xsl:choose>
            <xsl:when test="string-length(string) < len" >
                <xsl:call-template name="append">
                    <xsl:with-param name="char" select="char" />
                    <xsl:with-param name="string" select="concat(char,string)" />
                    <xsl:with-param name="len" select="len" />
                </xsl:call-template>
            </xsl:when>
        </xsl:choose>
    </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

For some reason, the looping isn't working as expected. The loop executes once and displays the result.
For example, for the first XML input, the output should be ####Auckland, but the result is #Auckland. Can you help me identify the flaw in this code? Thanks in advance for any help.

A: Here is an easy, efficient and non-recursive XSLT 1.0 solution:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pFiller" select=
 "'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'"/>

   <xsl:template match="/">

            <xsl:apply-templates select="data/input"/>

   </xsl:template>

   <xsl:template match="input">

     <xsl:value-of select=
     "concat(string, substring(translate($pFiller,'$', char), 1, len))"/>

   </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:
<data>
    <input>
        <string>Auckland</string>
        <len>12</len>
        <char>#</char>
    </input>
    <input>
        <string>Ohio</string>
        <len>3</len>
        <char>*</char>
    </input>
</data>

the wanted, correct result is produced:

Auckland############

Ohio***

A: I assume you are specifying the use of XSLT 1.0; this would be a trivial one-liner in 2.0.
However, we can still do something simple if you are willing to make as assumption about the maximum length of the string.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template name="append" match="/">

                <xsl:for-each select="data/input">
                    <xsl:value-of select="substring(concat(char,char,char,char,char,char,char,char,char,char,.), 10 + string-length() - len, len)"/>
                </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

If you aren't happy with the assumption of a maximum length, you can always use the hack:
<xsl:variable name="char" select="char"/>
<xsl:variable name="chars">
    <xsl:for-each select="//*[position() <= $len]">
        <xsl:value-of select="$char"/>
    </xsl:for-each>
</xsl:variable>

Which works unless len is larger than the number of nodes in the input document. Then you can just do
<xsl:for-each select="data/input">
    <xsl:value-of select="substring($chars,.), string-length(), len)"/>
</xsl:for-each>

Bottom-line, although the recursive technique is frequently seen in XSLT 1.0, and is useful to learn, it is not really necessary in this particular case.

A: When I tried your XSLT, I didn't get any text output, mainly because in your code, your named append template expects parameters of string and len but you are calling it with parameters of field and length respectively. Additionally, your named template also matches the top-level document element, and as it stands it will output the html multiple times.
It is perfectly fine to have a matching template that is also a named template though. Try this XSLT instead:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">

            <xsl:apply-templates select="data/input"/>

   </xsl:template>

   <xsl:template match="input" name="append">
      <xsl:param name="char" select="char"/>
      <xsl:param name="string" select="string"/>
      <xsl:param name="length" select="number(len)"/>
      <xsl:choose>
         <xsl:when test="string-length($string) < $length">
            <xsl:call-template name="append">
               <xsl:with-param name="char" select="$char"/>
               <xsl:with-param name="string" select="concat($char,$string)"/>
               <xsl:with-param name="length" select="$length"/>
            </xsl:call-template>
         </xsl:when>
         <xsl:otherwise>

               <xsl:value-of select="$string"/>

         </xsl:otherwise>
      </xsl:choose>
   </xsl:template>
</xsl:stylesheet>

When applied to your XML, the following is output

####Auckland

Ohio

Note the use of default values for the parameters. The first time the template is accessed, via a template match, the values will default to the values of the relevant elements. When you subsequently call it as a named template, it will used the values you pass it as parameters.
EDIT: Should you wish to truncate the values if they exceed the required length, simply replace the existing <xsl:value-of select="$string"/> with this line instead:
<xsl:value-of select="substring($string, 1, $length)"/>


text:
Q: Fixed menu gets hidden by relative positioned images? I have the following CSS:
#header-fixed {
  background: url(images/header-fixed-bg.png) repeat-x 0 0;
  border-bottom: 1px solid #111;
  position: fixed;
  top: -70px;
  width: 100%;
  z-index: 1000;
  -webkit-box-shadow: rgba(0,0,0,0.3) 0 0 4px;
  -moz-box-shadow: rgba(0,0,0,0.3) 0 0 4px;
  box-shadow: rgba(0,0,0,0.3) 0 0 4px;
}

.large-bg-1 {
  background: url(images/large-bg-1.jpg) repeat 0 0;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  background-attachment: fixed;
  background-position: 50% 0;
  position: relative;
  height: 294px;
  width: 100%;
}

I'm using the Parallax background technique (when the background seem to scroll slower than the rest of the page). But no matter how much z-index I add to the fixed menu it still gets hidden by them.
How can I solve this?
Here's the live site: http://www.hfwebdesign.com/?ModPagespeed=off

A: Set the other element's z-index to -1


text:
Q: Unable to install specific packages in GoogleColab with R I'm trying to prepare a report to my colleagues and students. I think the best way to make it reproducible is through Google Colab. My analysis was performed using R and some packages available on CRAN.
I am using a Jupyter Notebook with R kernel. I used the followinf link to create a Notebook with netive R kernel: https://colab.research.google.com/notebook#create=true&language=r. As you can see as follows, its running R.
a <- 1
print(a)

However, when I try to install the exactextractr package I get the following error:
install.packages("exactextractr")

Output:
Installing package into '/usr/local/lib/R/site-library'
(as 'lib' is unspecified)

also installing the dependencies 'proxy', 'e1071', 'wk', 'sp', 'terra', 'classInt', 's2', 'units', 'Rcpp', 'raster', 'sf'

Warning message in install.packages("exactextractr"):
"installation of package 'units' had non-zero exit status"
Warning message in install.packages("exactextractr"):
"installation of package 'sf' had non-zero exit status"
Warning message in install.packages("exactextractr"):
"installation of package 'exactextractr' had non-zero exit status"

The package was not installed:
library(exactextractr)

Output:
Error in library(exactextractr): there is no package called 'exactextractr'
Traceback:

1. library(exactextractr)

What is the problem here?

A: Because the Linux variant underlying the GoogleColab is Ubuntu, you could also take advantage of r2u which brings about 20,000 binary CRAN packages with full dependencies to Ubuntu. So if (here) libudunits is needed, it gets installed!
A have a quick demo gif in this tweet (as SO limits image sizes) -- 17s total for everything from a 'blank' start in a container with just R, and r2u set up. This works in any Ubuntu system on stanard x86_64 (ie Intel or AMD): laptop, desktop, server, cloud, continuous integration, ...  Give it a try -- as the demo shows it installs correctly via a single install.packages("exactextractor") from R!

A: Some of the packages that you are trying to install (exactextractr, terra, sf, units) have system dependencies. You can see that on the CRAN pages for these packages (here for terra) under "SystemRequirements".
In this case, you need to have GDAL, GEOS,  PROJ, and udunits-2. Depending on the underlying linux system you can do something like the below to install them.
sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install libudunits2-dev libgdal-dev libgeos-dev libproj-dev

This is essentially what r2evans suggests in the comments. And there is no doubt in my mind that what he says is correct.
See the github pages for more guidance on installing these packages. Here for "terra".
Also, try to install the dependencies one by one, so that it becomes clearer where the problem is.
E.g.
install.packages('proxy')
install.packages('e1071')
install.packages('wk')
install.packages('sp')
install.packages('terra')

Etcetera.

A: Do this in one cell - R Colab doesn't support sudo directly.
system('sudo apt install libudunits2-dev')

Then this should work (I tried it successfully)
install.packages("exactextractr")


text:
Q: Translating Brute-Force Voronoi Diagram into Python from Javascript Example I'm trying to translate code that generates a Voronoi Diagram from Javascript into Python. This is a struggle because I don't know Javascript. I think I can sort-of make it out, but I'm still running into issues with things I don't understand. Please help me figure out what is wrong with my code.
The code I've written simply give a blank window. Please help me generate a Voronoi Diagram.
In order, I have my code, then the original code.
Here's a link to the website I found it at:
Procedural Generation Wiki
My Code:
"""
Translated from javascript example at
http://pcg.wikidot.com/pcg-algorithm:voronoi-diagram

I have included the original comments.

My own comments are preceded by two hash-tags/pound-signs.
IE
# Original Javascript comments here
## My comments here
"""

import random
import pygame
from pygame import gfxdraw

# specify an empty points array
## I will use a list.
points = []
lines = []

# get a random number in range min, max -1
## No need for our own random number function.
## Just, import random, instead.

def definePoints(numPoints, mapSize):
    # we want to take a group of points that will fit on our map at random
    for typ in range(numPoints):
        # here's the random points
        x = random.randrange(0, mapSize)
        y = random.randrange(0, mapSize)
        # "type:" decides what point it is
        # x, y: location
        # citizens: the cells in our grid that belong to this point
        ## Can't use "type:" (without quotes) in python comments
        ## Since I don't know Javascript, I dunno what he's doing here.
        ## I'm just going to append lists inside points.
        ## order is: type, x, y, citizens
        points.append([typ, x, y, []])

    # brute force-y but it works
    # for each cell in the grid
    for x in range(mapSize):
        for y in range(mapSize):
            # find the nearest point
            lowestDelta = (0, mapSize * mapSize)
            for p in range(len(points)):
                # for each point get the difference in distance
                # between our point and the current cell
                ## I split the above comment into two so
                ## it would be less than 80 characters.
                delta = abs(points[p][1] - x) + abs(points[p][2] - y)
                # store the point nearest if it's closer than the last one
                if delta < lowestDelta[1]:
                    lowestDelta = (p, delta)

            # push the cell to the nearest point
            ## Okay, here's where I start getting confused.
            ## I dunno how to do whatever he's doing in Python.
            for point in points:
                if lowestDelta[0] == point[0]:
                        activePoint = point
            dx = x - activePoint[1]
            dy = y - activePoint[2]
            # log delta in cell for drawing
            ## Again, not sure what he's doing here.
            for point in points:
                if activePoint == point:
                    point[3].append(dx)
                    point[3].append(dy)

    return points

## all comments and code from here on are mine.
def main():
    # Get points
    points = definePoints(20, 400)
    print("lines: ", lines)

    # Setup pygame screens.
    pygame.init()
    size = (400, 400)
    screen = pygame.display.set_mode(size)
    white = (255, 255, 255)

    done = False

    # Control fps of window.
    clock = pygame.time.Clock()
    fps = 40

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        for point in points:
            for p in point[3]:
                # draw white wherever there's a point.
                # pygame windows are black by default
                gfxdraw.pixel(screen, point[1], point[2], white)

        # controls FPS
        clock.tick(fps)

if __name__ == "__main__":
    main()

Original Example Code:
//specify an empty points array
var points = [];

//get a random number in range min, max - 1
function randRange(min, max) {
    return Math.floor(Math.random() * ((max) - min) + min);
}

function definePoints(numPoints, mapSize) {
    //we want to take a group of points that will fit on our map at random
    for(var i = 0; i < numPoints; i++) {
        //here's the random points
        var x = randRange(0, mapSize);
        var y = randRange(0, mapSize);
        //type: decides which point it is
        //x, y: location
        //citizens: the cells in our grid that belong to this point
        points.push({type: i, x: x, y: y, citizens: []});
    }
    //brute force-y but it works
    //for each cell in the grid
    for(var x = 0; x < mapSize; x++) {
        for(var y = 0; y < mapSize; y++) {
            //find the nearest point
            var lowestDelta = {pointId: 0, delta: mapSize * mapSize};
            for(var p = 0; p < points.length; p++) {
                //for each point get the difference in distance between our point and the current cell
                var delta = Math.abs(points[p].x - x) + Math.abs(points[p].y - y);
                //store the point as nearest if it's closer than the last one
                if(delta < lowestDelta.delta) {
                    lowestDelta = {pointId: p, delta: delta};
                }
            }
            //push the cell to the nearest point
            var activePoint = points[lowestDelta.pointId];
            var dx = x - activePoint.x;
            var dy = y - activePoint.y;
            //log delta in cell for drawing
            activePoint.citizens.push({
                dx: dx,
                dy: dy
            });
        }
    }
}

definePoints(20, 40);

for(var point of points) {
        for(var citizen of point.citizens) {
            //set color of cell based on point
            //draw cell at (point.x + citizen.dx) * cellSize, (point.y + citizen.dy) * cellSize
        }
    }

A: Okay, I'm still not sure exactly what the original javascript code is doing. However, I managed to make my own Voronoi Diagram generator based off what I learned by going through it. Here it is. Thank you all for trying to help.
"""
Working Voronoi Diagram Generator

"""

import random as r
import math as m
import pygame as pg
from pygame import gfxdraw

def makeMap(numPoints, mapSize):

    # Generate random colors so I can see what's happened.
    colors = []
    for color in range(numPoints):
        red = r.randint(0, 255)
        grn = r.randint(0, 255)
        blu = r.randint(0, 255)
        colors.append((red, grn, blu))

    # Generate the base points.
    ct = 0
    basePoints = []
    for point in range(numPoints):
        x = r.randint(0, mapSize)
        y = r.randint(0, mapSize)
        basePoints.append((x, y, colors[ct]))
        ct += 1

    # Generate all the other points on the map.
    points = []
    for x in range(mapSize):
        for y in range(mapSize):
            distance = mapSize * 2
            for bp in basePoints:
                newDistance = m.sqrt(((x - bp[0]) ** 2) + ((y - bp[1]) ** 2))
                if newDistance < distance:
                    distance = newDistance
                    color = bp[2]
            points.append([x, y, color])

    return points

def colorer(surf, points):
    for p in points:
        gfxdraw.pixel(surf, p[0], p[1], p[2])

def main():
    # Get points.
    points = makeMap(20, 400)
    print("points: ", points)

    # Setup pygame screens.
    pg.init()
    size = (400, 400)
    surf = pg.display.set_mode(size)

    done = False

    # Control fps of window.
    clock = pg.time.Clock()
    fps = 40

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        colorer(surf, points)

        pg.display.flip()

        # Control FPS.
        clock.tick(fps)

if __name__ == "__main__":
    main()

A: Here's the fixed version. The author uses dictionaries/associative arrays for the points and lowestDelta, but it works with lists and tuples as well. I only changed the code to "push the cell to the nearest point" and add the offset of the citizen points in the drawing loop. BTW, since you only need to draw the points once, you can do it before the while loop to make the code more efficient.
import random
import pygame
from pygame import gfxdraw

def definePoints(numPoints, mapSize):
    points = []
    # we want to take a group of points that will fit on our map at random
    for typ in range(numPoints):
        # here's the random points
        x = random.randrange(0, mapSize)
        y = random.randrange(0, mapSize)
        # "type:" decides what point it is
        # x, y: location
        # citizens: the cells in our grid that belong to this point
        points.append([typ, x, y, []])

    # brute force-y but it works
    # for each cell in the grid
    for x in range(mapSize):
        for y in range(mapSize):
            # find the nearest point
            lowestDelta = (0, mapSize * mapSize)
            for p in range(len(points)):
                # for each point get the difference in distance
                # between our point and the current cell
                delta = abs(points[p][1] - x) + abs(points[p][2] - y)
                # store the point nearest if it's closer than the last one
                if delta < lowestDelta[1]:
                    lowestDelta = (p, delta)

            # push the cell to the nearest point
            activePoint = points[lowestDelta[0]]
            dx = x - activePoint[1]
            dy = y - activePoint[2]
            activePoint[3].append((dx, dy))

    return points

def main():
    pygame.init()
    size = (400, 400)
    screen = pygame.display.set_mode(size)
    white = pygame.Color('white')

    done = False
    clock = pygame.time.Clock()
    fps = 40

    points = definePoints(50, 400)

    # Draw the points before the while loop starts. No need to draw them again.
    for point in points:
        # Use different random colors for the points.
        color = (random.randrange(256), random.randrange(256),
                 random.randrange(256))
        for p in point[3]:
            # Draw the citizen points.
            # Add the offset of the citizen to the positions of the points.
            gfxdraw.pixel(screen, point[1]+p[0], point[2]+p[1], color)
        # draw white wherever there's a point.
        gfxdraw.pixel(screen, point[1], point[2], white)

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        clock.tick(fps)
        pygame.display.flip()

if __name__ == '__main__':
    main()