text:
Q: Proof of the Symmetry Lemma I'm hoping someone can check that my proof of the Symmetry Lemma below is okay. (I'm actually proving a version of the result restricted to geodesic variations, because that's what I'm primarily interested in.) Note: I have seen the proof done with local coordinates, e.g., in John M. Lee's book; I want to avoid using coordinates.
Let $\gamma : [0,T] \to M$ be a geodesic in a Riemannian manifold $(M,g)$, and let $\sigma : (-\varepsilon,\varepsilon) \times [0,T] \to M$, $(s,t) \mapsto \sigma(s,t)$ be a smooth geodesic variation of $\gamma$ (i.e., $\sigma(0,\cdot) = \gamma$, and $\sigma(s,\cdot)$ is a geodesic for every $s$). We can define vector fields along $\sigma$ as follows:
$$
  J(s,t) = T_{(s,t)}\sigma\cdot\left.\frac{\partial}{\partial s}\right|_{(s,t)}
         =: \frac{\partial\sigma}{\partial s}(s,t)
 \quad\text{and}\quad
  Z(s,t) = T_{(s,t)}\sigma\cdot\left.\frac{\partial}{\partial t}\right|_{(s,t)}
         =: \frac{\partial\sigma}{\partial t}(s,t).
$$
(Here $s$ is the coordinate on $(-\varepsilon,\varepsilon)$, and $t$ is that on $[0,T]$.) So we have $\dot{\gamma} = Z(0,\cdot)$, and $J(0,\cdot)$ is a Jacobi field along $\gamma$.
Claim: $\frac{D}{ds}Z = \frac{D}{dt}J$.
Proof: Let $\widetilde{J},\widetilde{Z} \in \mathfrak{X}(M)$ be (smooth) extensions of $J$ and $Z$, resp., to an open neighbourhood of $\sigma$, i.e., $\widetilde{J}(\sigma(s,t)) = J(s,t)$ and $\widetilde{Z}(\sigma(s,t)) = Z(s,t)$. Since $\partial/\partial s$ and $\widetilde{J}$ are $\sigma$-related, likewise $\partial/\partial t$ and $\widetilde{Z}$, we then get that
$$
  [\widetilde{J},\widetilde{Z}]\circ\sigma
    = T\sigma\cdot\left[\frac{\partial}{\partial s},\frac{\partial}{\partial t}\right]
    = 0.
$$
Thus, since the Levi-Civita connection $\nabla$ is symmetric:
\begin{align*}
  0 & = T(J(s,t),Z(s,t))\\
    & = T(\widetilde{J},\widetilde{Z})(\sigma(s,t))\\
    & = \nabla_{\widetilde{J}}\widetilde{Z}(\sigma(s,t)) - \nabla_{\widetilde{Z}}\widetilde{J}(\sigma(s,t)) - [\widetilde{J},\widetilde{Z}](\sigma(s,t))\\
    & = \nabla_{J(s,t)}(\widetilde{Z}\circ\sigma) - \nabla_{Z(s,t)}(\widetilde{J}\circ\sigma)\\
      & = \frac{D}{ds}Z(s,t) - \frac{D}{dt}J(s,t).
\end{align*}
(End of proof.)
My main concern with this argument is the existence of the extensions $\widetilde{J}$ and $\widetilde{Z}$ (and hence that $[\widetilde{J},\widetilde{Z}]\circ\sigma = 0$). Clearly they won't exist on the entire image of $\sigma$, but if we restrict to a sufficiently small open subset $A \subset (-\varepsilon,\varepsilon) \times [0,T]$, then can we be assured that they exist on $\sigma(A)$? (Everything else in the proof seems okay to me, but I could be mistaken.)
Edit: my claim was originally written incorrectly ($J$ and $Z$ were on the wrong sides); I've corrected this.


text:
Q: About Pythons str class constructor default arguments Python str class constructor in Python3.5:
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

Does it mean that the default encoding is utf-8?

A: Yes, that means that the default value for encoding is 'utf-8'.
Also you could check this on: https://docs.python.org/3/library/stdtypes.html#str.encode

A: It is an additional initializer for str objects that is used when an object of type bytes (or byte-like) is supplied (indicated by the prefix b'text'.
It's default value is utf-8 because the default encoding for Python 3.5 is utf-8 (and it rocks).
It simply means that if a bytes object is passed in, the encoding utf-8 is going to be used by default and the errors=strict means that encoding errors will raise a UnicodeError. It essentially issues a call to bytes.decode().
You can of course change these if you wish and use another encoding (like latin-1) or another level of errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Material Table rowspan columns based on dataSource object array property size Even now in version 7.2 of Angular Material, I can't seem to find examples on how to use rowspan on mat-table and keep the component functionality.
This is how far (short?) I've got:
https://stackblitz.com/edit/angular-wudscb
The example in the Stackblitz above is "almost" what I am looking for, but I am not being able to see how to finish it.
...
===============================================
||     ||            ||            ||  row1  ||
||  1  ||  Hydrogen  ||   1.0079   ||========||
||     ||            ||            ||  row2  ||
===============================================
||     ||            ||            ||  row1  ||
||     ||            ||            ||========||
||  2  ||   Helium   ||   4.0026   ||  row2  ||
||     ||            ||            ||========||
||     ||            ||            ||  row3  ||
===============================================
||     ||            ||            ||  row1  ||
||  3  ||  Lithium   ||   6.941    ||========||
||     ||            ||            ||  row2  ||
===============================================
...

An example using other metadata format can be found in:
https://stackblitz.com/edit/angular-lnahlh
Following my Stackblitz (the first link), my questions are:
Am I too far of achieving this rowspan shim/hack?
How do I loop the rows based on the lenght of the row['descriptions'] size?
What If I had another array property inside the object? Could I iterate and generate the columns/rows/rowspan with its size, so it would become more generic?
I'm trying to find a generic solution for the community.

A: As I was not happy with the answers presented (especially with the cacheSpan implementation).
I came up with something more convenient IMHO, that goes something like:
export class TableBasicExample {
  displayedColumns = ['priority', 'status', 'dateCreated', 'testNumber', 'testCurrency', 'testTime'];
  dataSource = DATA;

  spans = {};

  constructor() {
    this.spans = Object.assign({}, {
      priority: this.spanDeep(['priority'], DATA),
      status: this.spanDeep(['priority', 'status'], DATA),
      dateCreated: this.spanDeep(['priority', 'status', 'dateCreated'], DATA)
    });
  }

  spanDeep(paths: string[] | null, data: any[]) {
    if (!paths.length) {
      return [...data]
        .fill(0)
        .fill(data.length, 0, 1);
    }

    const copyPaths = [...paths];
    const path = copyPaths.shift();

    const uniq = uniqWith(data, (a, b) => get(a, path) === get(b, path))
      .map(item => get(item, path));

    return uniq
      .map(uniqItem => this.spanDeep(copyPaths, data.filter(item => uniqItem === get(item, path))))
      .flat(paths.length);
  }

  getRowSpan(path, idx) {
    return this.spans[path][idx];
  }
};

Working example may be found here: https://stackblitz.com/edit/angular-lnahlh-hw2d3b

A: Well, it seems that material table has no api documentation for it, I could not find any trick to do this too, But we can twick the our data to support this, as per your second example we can reform the data to new json and we can get our expected result.
Step 1 :
    const originalData = [
      { id: 1, name: 'Hydrogen', weight: 1.0079, descriptions: ['row1', 'row2'] },
      { id: 2, name: 'Helium', weight: 4.0026, descriptions: ['row1', 'row2', 'row3'] },
      { id: 3, name: 'Lithium', weight: 6.941, descriptions: ['row1', 'row2'] },
      { id: 4, name: 'Beryllium', weight: 9.0122, descriptions: ['row1', 'row2', 'row3'] },
      { id: 5, name: 'Boron', weight: 10.811, descriptions: ['row1'] },
      { id: 6, name: 'Carbon', weight: 12.0107, descriptions: ['row1', 'row2', 'row3'] },
      { id: 7, name: 'Nitrogen', weight: 14.0067, descriptions: ['row1'] },
      { id: 8, name: 'Oxygen', weight: 15.9994, descriptions: ['row1'] },
      { id: 9, name: 'Fluorine', weight: 18.9984, descriptions: ['row1', 'row2', 'row3'] },
      { id: 10, name: 'Neon', weight: 20.1797, descriptions: ['row1', 'row2', 'row3'] },
    ]; //original data

    const DATA = originalData.reduce((current, next) => {
      next.descriptions.forEach(b => {
        current.push({ id: next.id, name: next.name, weight: next.weight, descriptions: b })
      });
      return current;
    }, []);//iterating over each one and adding as the description
    console.log(DATA)

    const ELEMENT_DATA: PeriodicElement[] = DATA; //adding data to the element data

Step 2
this will be as it is as your second stackblitz link.
 getRowSpan(col, index) {
    return this.spans[index] && this.spans[index][col];
  }

Step 3
as it is as per your second link
  constructor() {
    this.cacheSpan('Priority', d => d.id);
    this.cacheSpan('Name', d => d.name);
    this.cacheSpan('Weight', d => d.weight);
  }

  /**
   * Evaluated and store an evaluation of the rowspan for each row.
   * The key determines the column it affects, and the accessor determines the
   * value that should be checked for spanning.
   */
  cacheSpan(key, accessor) {
    for (let i = 0; i < DATA.length;) {
      let currentValue = accessor(DATA[i]);
      let count = 1;

      // Iterate through the remaining rows to see how many match
      // the current value as retrieved through the accessor.
      for (let j = i + 1; j < DATA.length; j++) {
        if (currentValue != accessor(DATA[j])) {
          break;
        }

        count++;
      }

      if (!this.spans[i]) {
        this.spans[i] = {};
      }

      // Store the number of similar values that were found (the span)
      // and skip i to the next unique row.
      this.spans[i][key] = count;
      i += count;
    }
  }

Step 4
Using index to pass down to rowspan and hiding the rows where it doesn't needed

    <ng-container matColumnDef="id">
         Priority

         {{ data.id }}
    </ng-container>

    <ng-container matColumnDef="name">
         Name

         {{ data.name }}
    </ng-container>

    <ng-container matColumnDef="weight">
         Weight

         {{ data.weight }}
    </ng-container>

    <ng-container matColumnDef="descriptions">
         Descriptions
         {{ data.descriptions }}
    </ng-container>

Here is the demo

A: We must say how many rows there, but some rows has same id and we will sort and merge td if them used same id.
But for your data, it is say some rows there, and descriptions is array and split able. For this way JS can't know how many
 should be there.
2 ways for you:
1- Format your data, keep one description each row, same as the example data in second href, [{id, name, weight, countdescriptions, description},...], and use [attr.rowspan]='data.countdescriptions' instead [attr.rowspan]='getRowSpan(data.id)'.
2- Update content format, like
<li *ngFor... in the description , and remove the [attr.rowspan] attribute.

A: a way simpler approach would be to use ng-containers
html template would be something like this, ex: app.component.html

<ng-container matColumnDef="id">
     Priority
       <ng-container *matCellDef="let data">

            {{ data.id }}

       </ng-container>
</ng-container>

<ng-container matColumnDef="name">
     Name
    <ng-container *matCellDef="let data">

       {{ data.name }}

    </ng-container>
</ng-container>

<ng-container matColumnDef="weight">
     Weight
    <ng-container *matCellDef="let data">

       {{ data.weight }}

    </ng-container>
</ng-container>

<ng-container matColumnDef="descriptions">
     Descriptions
     {{ data.description }}
</ng-container>

JS / TS  file content will be
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dataSource = ELEMENT_DATA;
  rowSpanData = ROWSPANDATA;
  displayedColumns = ['id', 'name', 'weight', 'descriptions'];
  constructor() {  }
}

export interface PeriodicElement {
  id: number;
  name: string;
  weight: number;
  descriptions: string[];
}

const originalData = [
  { id: 1, name: 'Hydrogen', weight: 1.0079, descriptions: ['row1', 'row2'] },
  { id: 2, name: 'Helium', weight: 4.0026, descriptions: ['row1', 'row2', 'row3'] },
  { id: 3, name: 'Lithium', weight: 6.941, descriptions: ['row1', 'row2'] },
  { id: 4, name: 'Beryllium', weight: 9.0122, descriptions: ['row1', 'row2', 'row3'] },
  { id: 5, name: 'Boron', weight: 10.811, descriptions: ['row1'] },
  { id: 6, name: 'Carbon', weight: 12.0107, descriptions: ['row1', 'row2', 'row3'] },
  { id: 7, name: 'Nitrogen', weight: 14.0067, descriptions: ['row1'] },
  { id: 8, name: 'Oxygen', weight: 15.9994, descriptions: ['row1'] },
  { id: 9, name: 'Fluorine', weight: 18.9984, descriptions: ['row1', 'row2', 'row3'] },
  { id: 10, name: 'Neon', weight: 20.1797, descriptions: ['row1', 'row2', 'row3'] },
]

let DATA1 = []
const ROWSPANDATA = {}
originalData.forEach(row => {
  ROWSPANDATA[row.id] = row.descriptions.length;
  row.descriptions.forEach((desc, index) => {
    if (index === 0) {
      DATA.push({id: row.id, name: row.name, weight: row.weight, description:
      desc});
    } else {
     DATA.push({description: desc})
    }
  })
})

const ELEMENT_DATA: PeriodicElement[] = DATA;

just reformat the data to fit in a basic HTML table.
working example here
note: ID field can be duplicated, here i have used ID for simplicity of an answer you can create your own unique key and add it as part of row data and let it not displayed as a table column, that is still fine with angular material table.


text:
Q: How can I create an HTML text input that validates URLs as well as anchor links? I've got an input field of type text where I'd like to allow the user to enter full URLs as well as anchor links that start with "#". I've got a regex that works as expected on regex101.com but doesn't work within the HTML code.
Here's my HTML code with the regex I'm trying to use:
<input type="text" pattern="https?://.+|^[#]">
<input type="submit">

This regex works as expected on regex101 but it the HTML it matches URLs but not the anchor links. I'd appreciate any guidance with this!
Thanks in advance.

A: Try to use type="url" instead of type="text"


text:
Q: How to handle username/pass changes in a distributed REST application? I have a distributed REST application, written in C++, with an integrated SQLite DB. The application is self contained - no apache or iis server, and no external mysql. The application is the logic behind a hardware sensor: the application monitors sensor(s), identifying and storing data of interest, and generating "events" when data of interest repeats. The creation of data of interest is synchronized across the Internet to multiple instances of the application using REST to communicate the synchronization.
Using basic authentication over https, each instance maintains a local key/value store of remote instances' user/pass authentication data. This is necessary because each communication with a remote instance of the application requires authentication.
My question is how to handle the situation when the human operator changes either the username or password in the application, while the application is in active synchronization with remote instances.
I'm thinking this is really no different than any other material application data changing - when a local username / password changes, a REST communication is posted to each synchronization instance containing the changed data for that remote's local key/value store. Any communications that fail get queued for when that remote is back, as that is material information the remote needs to maintain synchronization.
Because the communications occur over https, the fact that authentication data is being passed around is okay.
I thought I might need special logic to handle the race condition where one instance tries to communicate with another, but the other has just changed its authentication fields. The sender will queue with my current logic, and when the remote sends it's updated authentication data, the locally queued failed communications will start succeeding. So that does not appear to be an issue.
I guess this is a request for anyone that's been here before, what did you do? Maybe my search terms are weak here, because I'm not finding discussion of this issue.


text:
Q: Correct way to use FormEvents to customise fields in SonataAdmin I have a Sonata Admin class with some form fields in it, but I'd like to use the FormEvents::PRE_SET_DATA event to dynamically add another form field based on the bound data.
However, I'm running into several problems:
1) The only way I can find to add the form field to the correct 'formGroup' in the admin is by adding the new field twice (once via the formMapper and once via the form itself)... this seems very wrong and I cannot control where in the formGroup it appears.
2) The added element doesn't seem to know that it has a connected Admin (probably because it is added using Form::add()). This means, amongst other things, that it renders differently to the other fields in the form since it triggers the {% if sonata_admin is not defined or not sonata_admin_enabled or not sonata_admin.field_description %} condition in form_admin_fields.html.twig
So, this leads me to believe that I'm doing this all wrong and there must be a better way.
So...
What is the correct way to use a FormEvent to add a field to a form group, ideally in a preferred position within that group, when using SonataAdmin?
Here's some code, FWIW...
protected function configureFormFields(FormMapper $formMapper)
{
    $admin = $this;
    $formMapper->getFormBuilder()->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin, $formMapper) {
        $subject = $event->getData();

        // do something fancy with $subject
        $formOptions = array(/* some cool stuff*/);

        // If I don't add the field with the $formMapper then the new field doesn't appear on the rendered form
        $formMapper
            ->with('MyFormGroup')
                ->add('foo', null, $formOptions)
            ->end()
        ;

        // If I don't add the field with Form::add() then I get a Twig Exception:
        // Key "foo" for array with keys "..." does not exist in my_form_template.html.twig at line xx
        $event
            ->getForm()
            ->add('foo', null, $formOptions)
        ;
    });

    $formMapper
        ->with('MyFormGroup')
            ->add('fieldOne')
            ->add('fieldTwo')
        ->end()
    ;
}

The aim is to add the new foo field between fieldOne and fieldTwo in MyFormGroup.

Edit: here's what I came up with with the help of Cassiano's answer
protected function configureFormFields(FormMapper $formMapper)
{
    $builder = $formMapper->getFormBuilder();
    $ff = $builder->getFormFactory();
    $admin = $this;
    $formMapper->getFormBuilder()->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($ff, $admin) {
        $subject = $event->getData();

        // do something fancy with $subject
        $formOptions = array(
            'auto_initialize'       => false,
            'class'                 => 'My\ProjectBundle\Entity\MyEntity',
            /* some cool stuff*/
        );

        $event->getForm()->add($ff->createNamed('foo', 'entity', null, $formOptions));
    });

    $formMapper
        ->with('MyFormGroup')
            ->add('fieldOne')
            ->add('foo')  // adding it here gets the field in the right place, it's then redefined by the event code
            ->add('fieldTwo')
        ->end()
    ;
}

A: No time here for a long answer, I will paste a piece of code and I don't know if fits exactly in your case, in my it's part of multi dependent selects (country, state, city, neighbor).
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Doctrine\ORM\EntityRepository;

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('myfield');

    $builder = $formMapper->getFormBuilder();
    $ff = $builder->getFormFactory();
    $func = function (FormEvent $e) use ($ff) {
        $form = $e->getForm();
        if ($form->has('myfield')) {
            $form->remove('myfield');
        }
        $form->add($ff->createNamed('myfield', 'entity', null, array(
            'class' => '...',
            'attr' => array('class' => 'form-control'),
            'auto_initialize' => false,
            'query_builder' => function (EntityRepository $repository) use ($pais) {
                $qb = $repository->createQueryBuilder('estado');
                if ($pais instanceof ...) {
                    $qb = $qb->where('myfield.other = :other')
                            ->setParameter('other', $other);
                } elseif(is_numeric($other)) {
                    $qb = $qb->where('myfield.other = :other_id')
                            ->setParameter('other_id', $other);
                }
                return $qb;
            }
        )));
    };
    $builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
    $builder->addEventListener(FormEvents::PRE_BIND, $func);
}


text:
Q: cannot invoke * with an argument list of type ($T12, @lvalue CGFloat) The title is the error message that I receive compiling this line:
 let width : Float   = mainView.frame.size.width / 100.0 * value

The value variable is of Float type. What's wrong here?

A:
cannot invoke * with an argument list of type ($T12, @lvalue CGFloat)

Read answer in error:
mainView.frame.size.width has type CGFloat therefore you need cast CGFloat to Float
Try to set value as CGFloat or cast Float(image.size.width)

In playground
Option 1
let image = UIImage(named:"group_1.png") // just for example

let value:CGFloat = 10.0

let width:Float   = Float(image.size.width / 100.0 * value)

Option 2
let value:Float = 10.0
let width:Float   = Float(image.size.width) / 100.0 * value


text:
Q: How to call method "continue" without crash Xcode? I'm using pod AWSCore, and, in this pod, have a method called continue in class AWSTask.
I need call this method, but, if I try call this method, Xcode crash, and it think this is a builtin continue, instead of a method continue.

How to fix it? And, yes, I already open a issue.

A: Could you please use the following block of code and check if it still crashes?
let transferManager = AWSS3TransferManager.default()
let request = AWSS3TransferManagerDownloadRequest()
// set request object values as desired
transferManager?.download(request).continue({ task -> Any? in
    if let error = task.error {
        print("\(error)")
    }

    if let result = task.result {
        print("\(result)")
    }

    return nil
})

Thanks,
Rohan


text:
Q: Function Parameter Not Correctly Adding to JSON Object In my game that I am creating, I have a function that takes the name and amount of an item, and adds it to the JSON "Player Invetory".
The code is as following:
function inventory(addOrRemove, item, amount) {
console.log(item);
    if (addOrRemove == 'add') {
        if (player.inventory.item== undefined) {
            player.inventory.item= amount;
        } else {
            player.inventory.item= player.inventory.item+ amount;
        }
    }
console.log(player.inventory)
}

The output, when calling the function in this manner is as follows:
inventory('add','coin',10)
// In the console log on line 2, "item" is defined as "coin"
// The player invetory object as called for in the console on line 10 has one value, "item: 10"

Now, the problem is that it will not add to the array based on the function parameter. I want the player inventory object to be "player.inventory.coin: 10" instead of "player.inventory.item: 10". The same applies for any items, so that the inventory dynamically can add any type of unique item.
I looked for other similar questions but was unable to find anyone with the same problem as myself, although maybe that is because I'm not entirely sure what this problem is called myself, but I did put in the effort and am stumped.

A: You need to pass in the item variable to your inventory object like this:
player.inventory[item] = amount;

This will use the string 'coin' in the item variable and set that as a key in the inventory object:
player.inventory['coin'] = amount;

A: Like this:
if (player.inventory[item] == undefined) {
     player.inventory[item] = amount;
} else {
    player.inventory[item] = player.inventory[item] + amount;
    // or: player.inventory[item] += amount;
}


text:
Q: How do I link a .sks file to a .swift file in SpriteKit I saw that in XCode 6 there is a built in level editor. I could not find a lot of documentation on how to use it or how it works, but I was able to figure out how to use it to make SKSpriteNodes then link them to a .swift file using childNodeWithName(). When you make a new SpriteKit project, it starts with a GameScene.swift and a GameScene.sks. I was able to use these to make one level visually, then I could code for it in the GameScene.swift, but when I tried to make my own .sks and .swift file for a new level, I could not connect the .sks and the .swift file I had made. I tried following this tutorial exactly:
http://www.techotopia.com/index.php/An_iOS_8_Swift_Sprite_Kit_Level_Editor_Game_Tutorial#Creating_the_Archery_Scene
When I connected the two files no errors came up, and then when I transitioned to the scene it transitioned properly, but nothing that I added visually to the .sks showed up in the simulator. Please help, I've spent hours researching solutions for this. The very few tutorials and forums that I was able to find about the level editor only talked about the GameScene.swift and .sks that start with a new SpriteKit project.

A: This method will unarchive an sks file and initialise it as whichever SKNode subclass it is called on. This means you can unarchive a file as an SKNode (so the root node will be an SKNode) and add it as a child to your scene. You can also unarchive a file as GameScene or any SKNode subclass.
extension SKNode {
    class func unarchiveFromFile(file : NSString) -> SKNode? {
        if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
            var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
            var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)

            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as SKNode
            archiver.finishDecoding()
            return scene
        } else {
            return nil
        }
    }
}

Use it like this:
let scene = GameScene.unarchiveFromFile("GameScene")! as GameScene

or
let levelStuff = SKNode.unarchiveFromFile("Level 1")!
self.addChild(levelStuff)

A: By the time of this answer (Xcode 8.2.1) the 'simple' way of doing this for scenes:

*

*Select the .sks file in your Project Navigator so the Graphic Editor is displayed

*Go to the Utilities Area (on the right hand side)

*Click on Custom class tab (icon looks like a contact card)

*In "Custom class" enter the name name of the class in your .swift file


text:
Q: OWIN AuthenticationMiddleware invoked twice per request I have a trouble while using owin cookie authentication middleware:
When I added cookie authentication middleware to my Startup.Configuration, all of my middlewares will invoke twice per request, and this is my code:
public void Configuration(IAppBuilder app)
    {
        app.Use((context, next) =>
        {
            // this code will be executed twice per http request
            return next();
        });

        // my cookie middleware
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            AuthenticationMode = AuthenticationMode.Active
        });
    }

and then I writed a middleware myself which inherit from AuthenticationMiddleware with empty implement, and it's worked just the same -- all of my middlewares will invoke twice per request.
When I debugged the owin AuthenticationMiddleware source code:
 public override async Task Invoke(IOwinContext context)
    {
        AuthenticationHandler<TOptions> handler = CreateHandler();
        await handler.Initialize(Options, context);
        if (!await handler.InvokeAsync())
        {
            await Next.Invoke(context);
        }
        await handler.TeardownAsync();
    }

I found that await Next.Invoke(context); will cause all of my middlewares invoked again.
But when I use other middlewares(StaticFiles middleware, Webapi middleware), everything works fine.
Did I missed something about OWIN or AuthenticationMiddleware?
Why would my middleware invoked twice per request? Is it by design?

A: If all of your application is in Owin, you should add this middleware to the end of your pipeline, and your problem should be gone!
app.Run(async context =>
{
    context.Response.StatusCode = 404;
    await context.Response.WriteAsync("404");
});

This will keep the request in the owin context, and it won't get to default IIS modules. For some reason (I don't know what!) if a request goes out of Owin and no module handle it, owin request would run twice!!


text:
Q: Block access to ns1.example.com, mail.example.com I have a VPS (CentOS 7) with 2 IP addresses.
I am hosting my own DNS server using Bind. Running Apache. Amongst others I have "A" records for
ns1.example.com -> X.X.X.X
ns2.example.com -> Y.Y.Y.Y
mail.example.com -> X.X.X.X
server.example.com -> X.X.X.X (Fully Qualified Hostname)

If I type mail.example.com in my browser, it shows the website located at example.com.
How do I make mail.example.com inaccessible from a browser without affecting the DNS setup ?
Similarly how do I block access to ns1.example.com, ns2.example.com and server.example.com ?

A: Remove the wildcard definition from apache2 configuration and/or set it up so it only "answers" requests directed to example.com and www.example.com
It's not a DNS issue, it's an apache2 configuration issue
You should have something like the described set-up here:
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-centos-7
but replacing the  "*:80" parameter with your VPS IP that corresponds with example.com
<VirtualHost PUT_YOUR_VPS_IP_HERE>
    ServerName www.example.com
    ServerAlias example.com
</VirtualHost>

There are some other examples here:
https://httpd.apache.org/docs/2.2/vhosts/examples.html

A: You can use Alias * to catch any other trafic than thoose allowed in your virtual host, for this you have to use in the last position a virtual host with * as alias.
Like that only defined domain will be served.
<VirtualHost *:80>
ServerName example.com
ServerAlias server.example.com
DocumentRoot /var/www/default
...
</VirtualHost>

# /!\ THIS HAS TO BE ON THE LAST POSITION /!\
<VirtualHost *:80 *:443>
# [ Server Domain ]
ServerName localhost
ServerAlias *
# [ Cancel trafic ]
RewriteRule .* - [END,R=406]
# [ Custom Log ]
CustomLog ${APACHE_LOG_DIR}/other.log combined
</VirtualHost>

In my example only example.com & www.example.com will be allowed, all other domains or IP will have trafic cancelled.
To cancel the trafic you can use  a redirect to - and then add an error code, for example i used a RewriteRule to redirect to 406 Not Acceptable (R=406).
Here you can find the list of redirect codes:
https://fr.wikipedia.org/wiki/Liste_des_codes_HTTP


text:
Q: Handling unspecified routes in react-router I have an Express/React application that uses React Router, and I'm not sure how to handle unspecified routes from the React end of things.
My express configuration calls app.get('/*', handler), which renders index.html so that the routing responsibilities are passed off to React. How can I use React Router to handle routes that haven't been predetermined. For example, if I got to myapp.com/test, I get the following error:

Location "/test" did not match any routes

How can I configure react-router to serve a 404 page, or to redirect to the default route if the URL is unrecognized?

A: React Router has a similar directive:
<Route path="*" component={NotFound} status={404} />

This will render component NotFound and ensure 404 status is sent to the client in case you need it for server side rendering - universal/isomorphic apps.
Hope that helps


text:
Q: Break out of std::visit once the desired alternative is found I often find myself using the following pattern to get the desired variant type from a container of variants:
for(auto&& Variant : variantContainer)
{
    // If the variant types match, do something
    std::visit([this, &Variant](auto&& arg)
    {
        using argType = typename std::decay_t<decltype(arg)>;                                       // e.g. `Field<int>`
        if (std::holds_alternative<argType>(Variant))                                           // if the current variant has the same type as the field
        {
            // do something, then preferably stop checking
            // the other possible variants
        }
    }, Variant);
}

However, per cppreference.com's statement on std::visit complexity:

If the number of variants is larger than 1, the invocation of the callable object has no complexity requirements.

It's probably typically linear complexity, so I'm wondering if there is any mechanism to break out of std::visit early once I've gotten what I need from it?

A: I cannot think of a way you would be able to inform std::visit that you wish to "break out", without std::visit explicitly inspecting something like a return value. As an example, imagine a custom version of visit that expects a "special" return type:
struct visitor
{
    auto operator()(int, int)     { return continue_{}; }
    auto operator()(int, float)   { return break_{}; }
    auto operator()(float, int)   { return continue_{}; }
    auto operator()(float, float) { return continue_{}; }
};

Its implementation would be able to detect whether the invoked visitor::operator() overload returned a continue_ or a break_ and stop.

Regardless, I think you shouldn't worry much:

*

*libc++ implements multi-variant visitation by creating a constexpr matrix of function pointers and then invoking the matching one.

*libstdc++ seems to do something similar by generating a multidimensional "vtable".

A: One way is to capture a break flag by reference.
// surely you don't want a copy?
for(auto&& Variant : variantContainer)
{
    auto should_break = false;

    // If the variant types match, set the value
    std::visit([this, &should_break](auto&& arg)
    {
        // arg is one of the Ts... in the variant

        this->doTheRightThing(arg);
        if (shouldCauseBreak(arg))
            should_break = true;
    }, Variant);

    if (should_break)
        break;
}


text:
Q: Zend fetchRow() not working I'm trying to fetch a row with a where statement but for some reason it throws an error at me.
This is the line
$row = $this->getDbTable()->fetchRow("order = $order");
I've put a die(); before this line and it does die,
Then I've put a die(); after this line and the die() doesn't get executed but throws an error.
The error doesn't help me much it only says "An error occurred Application error", there's nothing in my php error log either.
Help!

A: Going by your comments, I would try doing the where part 'properly'? E.g.:
$select = $this->getDbTable()->select()->where('order = ?', $order);
$row = $this->getDbTable()->fetchRow($select);

What is the situation you are needing to select by order? Is there a primary key you can select by?
Update:
Given your comments, maybe use update directly:
$table = $this->getDbTable();

$data = array( 'order' => $order+1 );

$where = $table->getAdapter()->quoteInto('order = ?', $order);

$table->update($data, $where);


text:
Q: Ideals of Lattice. If $L$ is a lattice then the ideal $I$ of $L$ is a nonempty lower segment closed under join. I need to show that the set of ideals $I(L)$ of $L$ forms a lattice under $\subseteq$
I know the construction of join in case the ideals are of the ring. ($i_{1} + i_{2}$ from $I_1$ and $I_2$). But I cant figure out a similar definition of join for Ideals of Lattices.

A: Observe $I(L)$ is closed under intersection. This yields the meet. If $A,B\in I(L)$ then consider the intersection of all ideals containing $A\cup B$ (which is nonempty since $A\cup B\subseteq L\in I(L)$).
More generally, any semilattice which is complete with respect to one lattice operation can have the other lattice operation defined in this way, making it a (not just semi) lattice.

A: If a lattice is finite, then ideals are principal, which means that they are generated by a single element, i.e., they have the following form:
$$\downarrow a:=\{x\in L:x\leqslant a\}.$$
Consequently, join and meet are given as follows:
$$(\downarrow a)\otimes(\downarrow b)=\,\downarrow(a\wedge b),$$
$$(\downarrow a)\oplus(\downarrow b)=\,\downarrow (a\vee b).$$
Obviously, then $L\cong I(L)$.
For infinite lattices there are some results,... to be continued (if you want).


text:
Q: Time ordering and the `garch` function in `tseries` package in R I have fitted a garch function using the tseries package in R, and I have observed that the series of residuals produced by the GARCH model begin with 'NAs', equal to the max order of the model.
E.g. For a GARCH(3,5) with 2000 observations, I am observing that the first 5 values for the residuals are NA, and then the remaining 1995 are non-NA values.
My question is, why are the NAs at the start of the residual series? I have set my data up so that the most recent data is at the start of the vector, and the oldest data is at the end of the vector. I would have thought that the last 5 residuals (observations 1996 to 2000) are the ones that are NA, as that is when the process "begins".
Is there some sort of assumption in R that the inputs in time-series modelling are arranged in a traditional chronological order, such that the first observation should be the oldest one? Is there any way to tell the garch function that the data is arranged in reverse chronological order?

A:
Is there some sort of assumption in R that the inputs in time-series modelling are arranged in a traditional chronological order, such that the first observation should be the oldest one?

I think there is. Some classes such as ts have time series attributes making time indexing explicit, but if you use a simple vector, time series function in R will usually assume its first observation is the oldest one.

Is there any way to tell the garch function that the data is arranged in reverse chronological order?

I do not think you should attempt making the garch function deal with a reverse-ordered time series; rather, reverse it yourself before inputing into the function. For a vector x, you can use rev to reverse the order: rev(x).


text:
Q: How to generate all possible pairs of coordinates without repetition in numpy efficiently I am trying to generate all pairs of coordinates for pixels in an image with colors, without the pairs repeating (order doesn't matter, so ((1,1,1), (2,2,2) is the same as ((2,2,2), (1,1,1)) and we want to include this pair only once). Also it's important to me that the coordinates are stored in a numpy array.
Let's assume i have a 10x10 image. This means that the image has 100 pixels with 3 color channels what equals to 300 coordinates. This gives us 300*299/2 unique pairs of coordinates. Both using itertools.combinations() or normal python iteration , and then converting to np.array, is painstakingly slow with bigger images (on my pc for 32x32x3 image it takes 5s).
I am able to create a list of all pixels using
all_pixels = np.array(np.meshgrid(range(10), range(10), range(3))).T.reshape(-1, 3)
but that's because we don't have to consider repetitions. Doing that but trying to create pairs of pixels gives me duplicates. I guess i could remove duplicates in some smart way but i have no idea how to do it in an efficient way.
Any help will be greatly appreciated.
It's a bit crude , but for reference this is how i do this now:
    start = time.time()
    x, y, z = shape
    all_pixels = []
    for i in range(x):
        for j in range(y):
            if z > 1:
                for k in range(z):
                    all_pixels.append([i, j, k])
            else:
                all_pixels.append([i, j])
    first_pix = []
    second_pix = []
    for i in range(len(all_pixels)):
        first = all_pixels[i]
        for j in all_pixels[i+1:]:
            second = j
            first_pix.append(first)
            second_pix.append(second)
    print("generation of pixels took " + str(time.time() - start))
    return np.array(first_pix), np.array(second_pix)

A: Here is a straightforward numpy method, not sure how fast it is:
shape = 10,10,3
np.stack([*map(np.transpose, map(np.unravel_index, np.triu_indices(np.prod(shape),1), 2*(shape,)))],-2)

Output:
array([[[0, 0, 0],
        [0, 0, 1]],

       [[0, 0, 0],
        [0, 0, 2]],

       [[0, 0, 0],
        [0, 1, 0]],

       ...,

       [[9, 9, 0],
        [9, 9, 1]],

       [[9, 9, 0],
        [9, 9, 2]],

       [[9, 9, 1],
        [9, 9, 2]]])

Update: Same idea, same result but faster
np.column_stack(np.unravel_index(np.arange(np.prod(shape)),shape))[np.column_stack(np.triu_indices(np.prod(shape),1))]

A: Below example is cooler but slower than OP's solution :(
%%timeit
first_pix = []
second_pix = []
for i in range(len(pixels)):
    first = pixels[i]
    for j in pixels[i+1:]:
        second = j
        first_pix.append(first)
        second_pix.append(second)

3.57 ms ± 59.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
mixed = {frozenset((i, j)) for i in pixels for j in pixels if i != j}

36.5 ms ± 1.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Code
Create a list of all pixels, but we use tuples so they are hashable. We will see why later.
img_width = 10
img_height = 10
img_colors = 3

pixels = [(x, y, c) for x in range(img_width) for y in range(img_height) for c in range(3)]

Now we use sets to make sure we have no duplicates.
mixed = {frozenset((i, j)) for i in pixels for j in pixels if i != j}

Now we check that it has the correct number of values:
>>> desired_length = (len(pixels) * (len(pixels) - 1)) / 2
>>> assert len(mixed) == desired_length
True

Explanation
We use a 2 dimensional set comprehension to create permutations. It has the following format:
{(x, y) for x in xs for y in ys}

Because this is a set all items in it will be unique. This requires everything in the set to be hashable i.e. comparable to eachother for python
Because we do not only want the pixel combinations to be unique, we also want them to be order indepentently unique. Therefore we use a set again, but since a normal set is not hashable we use the internal type frozenset. Which is now actually a set of tuples. Which is hashable and order independent.
>>> frozenset([(0, 0, 1), (0, 0 , 2)]) == frozenset([(0, 0, 2), (0, 0 , 1)])
True

We have to add i != j to make sure we do not enter the same coordinates in a frozenset twice, resulting in an outcome of length 1. (for example set([(0, 0, 1), (0, 0, 1)]) equals {(0, 0, 1)}
>>> frozenset([(0, 0, 1), (0, 0 , 1)])
frozenset({(0, 0, 1)})

Full code
%%timeit

img_width = 10
img_height = 10
img_colors = 3

pixels = [(x, y, c) for x in range(img_width) for y in range(img_height) for c in range(3)]
mixed = {frozenset((i, j)) for i in pixels for j in pixels if i != j}

38.2 ms ± 2.46 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: 'vertically join' php arrays I'm having trouble finding the right function to rearrange my multidimensional-array. I will explain using an example.
so i have three different arrays, let's say:
$ID  (containing n numbers)

$Name (containing n names)

$Explanation (containing n explanations)

I have tried array($id, $name, $explanation), which returns a new array, containing the above three arrays as they were before. However I would like to have my new array in the following way:
array(
   array (1[0], football[0], played on grass[0])
   array (2[1], swimming[1], played in the water[1])
   array (3[2], diving[2], played under water[2])
   ....
   array (n+1[n], basketball[n], played indoors[n])
)

I would like my array this way so it can be processed more easily into my database. Thanks in advance!

A: I assume that all the three arrays are equal in length say $arr1,$arr2,$arr3, Try:
$result = array();
foreach($arr1 as $key=>$val){
  $result[] = array($val,$arr2[$key],$arr3[$key]);
}

Then for re-indexing result array starting from index 1 you can try like,
$result = array_unshift($result,null);
unset($result[0]);


text:
Q: How can I split a string in Python based on and or params effeciently? I have input string like ((display_name contain 'Fw-1111' or display_name contain 'P1') and site_name contain 'device').
Input can have any combination of filter in any order.
I want to fetch each filter separately based on type. e.g. all filter on display_name  should come together as single Input like (display_name contain 'Fw-1111' or display_name contain 'P1').
I used split string to parse it and get the filters separately. Although I was able to do but the code is clumsy. I think there should be a better way to achieve this in Python. Please let me know an efficient way to achieve this.
This is my sample clumsy code:
column_search =  ((display_name contain 'Fw-1111' or display_name
contain 'P1') and site_name contain 'device')

col_search_list = column_search.split('and')
if 'display_name' in col_search_list[0]:
     policy_filter = col_search_list[0]
elif 'site_name' in col_search_list[0]:
     site_filter = col_search_list[0]
if len(col_search_list) >1:
     if 'display_name' in col_search_list[1]:
         policy_filter = col_search_list[1]
     elif 'site_name' in col_search_list[1]:
         site_filter = col_search_list[1]

A: Loop over "col_search_list":
col_search_list = column_search.split('and')
for term in col_search_list:
    if 'display_name' in term:
         policy_filter = term
    elif 'site_name' in term:
         site_filter = term


text:
Q: Having issues using a nested loop to properly load an array This while loop does not properly store the values needed into the rectangle array.  The rectangles are used for pulling sprites from a sprite sheet.  The commented out code below works perfectly.  The inner loop works perfectly for setting the first row, but adding the outer loop messes up everything.  The value for the sizeOfEachSpriteX and sizeOfEachSpriteY are both 32 (the sprites are square). The spritesheet size is 96 wide by 128 tall.  It is 4 rows, and 3 columns of sprites.  The goal is to have the rectangle be declared as Rectangles [which row, which column], as the commented out code achieves.  It appears the later iterations overwrite the first iterations' data, and destroy the whole process.  I'm quite confused!
int n = 0;
int n2 = 0;
while (n2 < 5)
        {
            while (n < 4)
            {
                Rectangles[n2, n] = new Rectangle
                     (sizeOfEachSpriteX * n2,
                      sizeOfEachSpriteY * n,
                      sizeOfEachSpriteX,
                      sizeOfEachSpriteY);
                n++;
            }
            n2++;
        }

/*   This code works perfectly.
        Rectangles[0,0] = new Rectangle(0,0,32,32);
        Rectangles[0,1] = new Rectangle(0,32,32,32);
        Rectangles[0,2] = new Rectangle(0,64,32,32);
        Rectangles[0,3] = new Rectangle(0,96,32,32);
        Rectangles[1,0] = new Rectangle(32,0,32,32);
        Rectangles[1,1] = new Rectangle(32,32,32,32);
        Rectangles[1,2] = new Rectangle(32,64,32,32);
        Rectangles[1,3] = new Rectangle(32,96,32,32);
        Rectangles[2,0] = new Rectangle(64,0,32,32);
        Rectangles[2,1] = new Rectangle(64,32,32,32);
        Rectangles[2,2] = new Rectangle(64,64,32,32);
        Rectangles[2,3] = new Rectangle(64,96,32,32);
*/

A: You need to reset your n variable to 0 before each of the inner while loops, right now it reaches 4, and your inner while loop never will be entered again.
int n = 0;
int n2 = 0;
while (n2 < 5)
{
    n = 0;
    while (n < 4)
    {
        Rectangles[n2, n] = new Rectangle
                     (sizeOfEachSpriteX * n2,
                      sizeOfEachSpriteY * n,
                      sizeOfEachSpriteX,
                      sizeOfEachSpriteY);
        n++;
    }
    n2++;
}

A: You need to reset n to 0 when you are done with each inner loop
int n = 0;
int n2 = 0;
while (n2 < 5)
    {
        n = 0;
        while (n < 4)
        {
            Rectangles[n2, n] = new Rectangle
                 (sizeOfEachSpriteX * n2,
                  sizeOfEachSpriteY * n,
                  sizeOfEachSpriteX,
                  sizeOfEachSpriteY);
            n++;
        }
        n2++;
    }

What's happening is that for n2 > 0, n is already 4, so the inner loop is never executed.


text:
Q: kotlin Pass multiple values on CheckChanged using databinding In Kotlin checkbox from XML databinding I want to pass 3 arguments checked or not (Boolean) and Two Strings.
Currently I am passing as below
 android:onCheckedChanged="@{(switch, checked) -> availMasterVm.onCheckedChangedMondayMrng(checked)}"

when I add String I am getting error how to pass strings to the viewmodel method

A: You can pass the extra parameters in just the usual way. Just remember that for strings you need to use back-ticks(``) instead of double quotes("").
 android:onCheckedChanged="@{(switch, checked) -> availMasterVm.onCheckedChangedMondayMrng(checked, `Monday`, `Morning`)}"


text:
Q: Sorting List of Articles in Symfony I have a module called articles, where I display a list of articles that I uploaded. On the index, it's just lists all of the article.
But I was wondering how I could make it so that if I click on the author, for example, it will then take me to a page that only displays article by that author (and making the url pretty ex: articles/daniel) or by a different field such as by publication. I know how to make the queries obviously, but I don't understand if I should be making new templates for these things or just change parameters on the index page and check for them.

A: You can use an ORM object route to achieve this with minimal coding on your part.  I'm going to assume you're on Doctrine but if you're on Propel the implementation should be very similar (probably just using sfPropelRoute as your class).  In your application's config/routing.yml add your custom route:
author_articles:
  url:   /authors/:author
  param: { module: articles, action: author }
  class: sfDoctrineRoute
  options: { model: Article, type: list }

Note: I used the URL /authors/ instead of the /articles/ you requested so this route won't conflict with any of the actions in your articles module but feel free to use any URL you'd prefer in your config.
Clear your cache after saving those changes to make Symfony aware of the new route.  What this has done is told your app to take all URLs matching /authors/* and pass them through the author action of your articles module, generating a list of objects that matches the :author parameter in the URL.  The object route does this all automatically with just the configuration above.
Now in the author action of your articles module add:
public function executeAuthor() {
  $this->articles = $this->getRoute()->getObjects();
}

Now you have the query result in a variable for your action template.  In your authorSuccess.php template loop through the $articles array as you see fit.
To link to this route from your main list using an author's name you can use the url_for helper with the route you just created to generate the full URLs dynamically:
<a href="<?php echo url_for('@author_articles?author=' . $article['author']) ?>"><?php echo $article['author'] ?>

That's all there is to it.


text:
Q: Reading a file from command line, name of the file as an argument i should open and read this file from passing the name of it as an argument of the command line when i run the program, but it keep going through the same error which is the open failure error i set in my program.The file is the correct folder and i also printed the arguments too see the one containing the name of the program wasn't well stored but it was, it's just the fopen function that fails.. Can anybody help me?
Here's the code:
 int main(int argc, const char * argv[])
{
if(argc != 2)
{
    fprintf(stderr, "Error: please insert just the name of the file after the one of the program!\n");
    exit(EXIT_FAILURE);
}

FILE *foo;
foo = fopen(argv[1], "r");

if(foo == NULL)
{
    printf("Error: failed to open the file\n Argument: %s\n", argv[1]);
    exit(EXIT_FAILURE);

}

here i leave the screenshots
command line screenshot
how i place the txt file
its position
the program working properly if not run from the cmd line

A: Here's your problem:

Since you passed just the filename to the program, it looks in its current working directory. And as we see from the ls command on the previous command line, there are only two files in the current working directory:
main.c and prova. The file ex3.txt is not there.
Based on the screenshots, it appears that the current working directory for these command lines was ~/documents/computer science xcode project/21:12/ex3/ex3,
but the ex3.txt file is actually in the directory
<something obscured by pulldown>/ex3-<something>/Build/Products/Debug.
Apparently the IDE uses that Debug directory, not the ex3 directory,
as its current working directory,
since it manages to find ex3.txt there without requiring you to provide any directory path in front of the filename.


text:
Q: Anime: main character has a gem in his head, in which an old man resides later on, who can use blood magic The main character of this anime has a gem in his head, in which an old man resides later on, who can use blood magic.
Additionally, he learns how to forge magic weapons and touches pillars which are stopping demons from entering their world. He is in love with girl who's a half-human, half-demon who gets controlled a lot.
The anime looks as if it is based in old Japan.
I watched it half a year ago and it starts of with the main character fighting monsters. It has about 20 or more episodes and when you get to the end part of the series he goes to a special island to do something and gets an artifact called the blood slate.

A: I found out what it was called.
Spiritual Domain, also called Spirit Realm or Spirit Field is an adaptation of the Chinese novel, Ling Yu.

In the world of Ling Yu(Spiritual Field), there is a continent named Chilan(Red Tide), where warriors and their Spirit Weapons are classified into different levels. Families and clans follow a strict hierarchy, too. Under the leadership of the Xuantian Union, human warriors and the Evil Clan have been engaged in brutal fights on Nether Battlefield for hundreds of years. A Soul-devouring Beast sneaked into the Chilan Continent through a crevice on the Nether Battlefield before it ruthlessly slaughtered the Feng Town and the Gao Town. Qin Lie, a young man from the Ling Town, together with Ling Yushi and Gao Yu whom he had grown up with, was commanded to help the Xuantian Union in the conquest of the Soul-devouring Beast. He did not anticipate that he would be swallowed into a great conspiracy. To protect his friends and to rescue the one he loves, the powers hiding in his veins are awakening.

Opening Theme


text:
Q: take screenshot with Selenium WebDriver while keeping font of html (python) I'm trying to generate images from html files which contain different fonts with Selenium WebDriver. But when I take the screenshot, the image I got always returns the same font, but not with the same font in html file. Does anyone know how to deal with this problem?
Example of code in python
Font in html: Parkavenue, cursive but the font in image we got from screenshot is Arial.
## python

html ="""

shipments % S.A. sher,AD.; common
            %
            .KAZG.O.,,, C AND S.A.

WARD, S.L.
            Gross body Buena Contains &nbsp AT &nbsp Sciences surface

"""
driver = Firefox()

driver.get("data:text/html," + html)
png = driver.get_screenshot_as_png()

image_screenshot

A: try this:
sudo apt-get install fonts-unfonts-core
sudo apt-get install fonts-unfonts-extra
sudo apt-get update
sudo apt-get upgrade
sudo apt -f install

that fixed the fonts problem for me but I still can't render some fonts like hebrew so I guess this is not the perfect solution

A: One possible explanation would be your device not having the font installed. If that is the case, WebDriver will load the page in already installed Arial.
I had a similar problem when running a Selenium WebDriver on Colab. Colab has only 1-2 fonts preinstalled, so my screenshots of websites in Unicode languages (Armenian, Georgian, Arabic namely) appeared to have squares instead of actual characters because none of the default fonts support these languages. Uninstalling them and installing a custom font (Sylfaen) with this snippet solved the issue.
!rm -r /usr/share/fonts/truetype/humor-sans
!rm -r /usr/share/fonts/truetype/liberation
!cp sylfaen.ttf /usr/share/fonts/truetype
!fc-cache -vf

In your case, try:
cp parkavenue_cursive_font_file /usr/share/fonts/truetype
fc-cache -vf

After which, install and use Selenium.


text:
Q: What is Service-Now and how is it related to ITSM? I'm new to Service-Now, can anyone help me to find out what is ITSM and how Service-Now is related to it.
What is the best way to learn this tool so that it is easy to know and understand.

A: Service-Now started out as an Cloud ITSM Tool, now it contains much more and you can also create custom application on the Platform. But I would suggest you check out there Wiki and Community which is actually pretty good.
http://wiki.servicenow.com/index.php?title=Get_Started
https://community.servicenow.com/welcome
ITSM is broad topic, it's about Incident, Change, Problem Management and a proper CMDB. You will find enough on the web. Like on Wikipedia.
https://en.wikipedia.org/wiki/Book:IT_Service_Management


text:
Q: Nodejs streaming upload multiple files I am working on a command line application that is supposed to take an array of file names,
do transform operations ( text files, spreadsheets, etc payloads have to be rewritten into JSON objects ), and send results to an endpoint API ( api.example.com ).
I am considering a sequential read, and pipe result to an instance of -http, or -request,
But has no idea of where to start from. Is there any alternatives or strategy have you used to solve a similar problem?
Any algorithm, or point to an article or a similar question here on SO will be highly appreciated.
Thanks.
Update1. I found a link that may help in this google group https://groups.google.com/forum/#!topic/nodejs/_42VJGc9xJ4
To keep track of the final solution:
var request = require('request');
var file = fs.createReadStream(path)
      .pipe(request.put({url: url, headers:{'Content-Length': fileSize}}, function(err, res, body){
        if(err) {
          console.log('error', err);
        } else {
          console.log('status', res.statusCode);
          if(res.statusCode === 200) {
            console.log('success');
          }
        }
      }));

The remaining problem is how to make this work for "n" files, in case "n" is high - 100 text files or more.

A: After try and err, I solved this issue with Events, and I paste the answer just in case someone else is struggling to solve a similar problem.
var EventEmitter = require('events').EventEmitter;
var request        = require('request');
var util          = require('util');

function Tester(){
  EventEmitter.call(this);
  this.files = ['http://google.ca', 'http://google.com', 'http://google.us'];

}

util.inherits( Tester, EventEmitter );

Tester.prototype.run = function(){
  //referencing this to be used with the kids down-here
  var self = this;
  if( !this.files.length ) { console.log("Cannot run again .... "); return false; }
  request({ url : this.files.shift()}, function( err, res, body ) {
    console.log( err, res.statusCode, body.length, " --- Running the test --- remaining files ", self.files );
    if( !self.files.length ) self.emit( "stop" );
    else self.emit( "next" , self.files );
  });
};

//creating a new instance of the tester class
var tester = new Tester();
  tester.on("next", function(data){
       //@todo --- wait a couple of ms not to overload the server.
       //re-run each time I got this event
       tester.run();
  });
  tester.on("stop", function(data){
    console.log("Got stop command --- Good bye!");
  });
  //initialize the first run
  tester.run();
  //graceful shutdown -- supporting windows as well
  //@link http://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js
  if (process.platform === "win32") {
    require("readline").createInterface({
        input: process.stdin,
        output: process.stdout
    }).on("SIGINT", function () {
        process.emit("SIGINT");
    });
}

process.on("SIGINT", function () {
    // graceful shutdown
    process.exit();
});

console.log('Started the application ... ');

NB:

*

*For a quick test, here is the runnable

*I used get for a quick test, but post/put may as well.
I hope it help, feel free to leave a comment. Thanks.


text:
Q: Add Mobile Search Icon next fa fa-bars Wordpress Hello how to add search icon " icon-magnifier " next to  fa fa-bars in wordpress
The Icon show in Big Screen already but not in mobile version.
See picture
https://i.imgur.com/P6sYmaF.png


text:
Q: Mysterious empty page + subsequent "Overfull \vbox has occurred while \output is active" during a long string of sectioning commands Document in question: http://pastebin.tlhiv.org/nJhaYvfN
Page 3 is typeset as a blank page, while page 4 has the overfull (by almost 160pts!) \vbox during a long string of sectioning commands.

A: LaTeX has troubles breaking pages that are entirely made up of sectioning commands; insert some filler text into these sections.


text:
Q: django Edit records in Listview I have a ListView that lists all questions from the Question model.
the models.py is:
class Question(models.Model):
    question_text = models.CharField(max_length=200, unique=True)
    pub_date = models.DateField(verbose_name='date published')

    def __str__(self):
        return self.question_text

now I want users can edit question_text. I tried this in views.py:
class UpdateDirectry(generic.list.ListView, generic.edit.FormMixin):
    model = Question
    template_name = 'accounts/editable_directory.html'
    form_class = forms.EditListForm

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(UpdateDirectry, self).get_context_data()
        context['object_list'] = Question.objects.filter(question_text__startswith='Who')
        return context

and in the template:
<form method="post">
                {% csrf_token %}

                        #
                        Q
                        D

                    {% for object in object_list %}

                            {{ forloop.counter }}
                            <input type="text" value="{{ object.question_text }}">
                            {{ object.pub_date }}

                    {% endfor %}

                <input type="submit" value="Submit">
            </form>

I can edit the question_text but when I click submit button nothing happens (just a white page) and no records change in the database.
How can I really edit records with the submit button?
This is what the template shows:

Update 1: ## this is what I exactly want in view (this image is in admin with list_editable):
enter image description here
How can do the exact thing in a view?

A: Just use a ModelFormSetView from Django Extra Views:
from extra_views import ModelFormSetView

class UpdateDirectry(ModelFormSetView):
    model = Question
    template_name = 'accounts/editable_directory.html'
    form_class = forms.EditListForm

and in your template:
<form method="post">
   {{ formset }}
   <input type="submit" value="Submit" />
</form>

A: You have to import UpdateView from :
  from django.views.generic.edit import UpdateView
  from django.views.generic.edit import FormMixin
  from .forms import EditListForm

  class UpdateDirectry(UpdateView,  FormMixin):
         model = Question
         template_name = 'accounts/editable_directory.html'
         form_class = EditListForm


text:
Q: How to get the names of all files in a folder with path and with last modification date written into a CSV file? I need to get the filenames and date modified of all the files from a folder.
I had tried using the below command to get same. But it only gives me the list of files present in the folder and the date modified is missing.
Can someone help me out to modify the same and get the filenames and the date modified of the file as well.
dir /b /s > fileslist.csv

A: From command line, to retrieve the required information
for /r %a in (*) do @echo %~ta %~fa

For each folder from the current one and below (recursive, /r), for each file (that will be referenced by %a replaceable parameter), echo the timestamp of the file (%~ta) and the full name of the file (%~fa)
To use it inside a batch file, percent signs in for replaceable parameters need to be doubled
for /r %%a in (*) do @echo %%~ta %%~fa

To send the output to a file, just redirect the full output of the command
>"file.csv" ( for /r %%a in (*) do @echo %%~ta,"%%~fa" )

note: read the output of for /? to get the reference of all the available options

A: Based upon your opening post and subsequent comments I'd use the Where command:
(For /F "Tokens=2-3*" %A In ('Where/T .:*.zip') Do @Echo(%A,"%~nxC")>output.csv

You could also quote %A, (if you prefer that particular format).


text:
Q: Как удалить связку ключей в xubuntu? Была установлена связка ключей для приложения remmina. Спустя некоторое время пароль был забыт. Как мне удалить эту связку ключей или сбросить пароль?

A: Для того чтобы удалить связку ключей от remmina выполняем команды:
cd ~
cd .local/share/
sudo rm -R keyrings
sudo rm -R remmina

Ответ на данный вопрос.
Перезапускаем remina.


text:
Q: Python - Find matching elements between and within nested lists Background: I have a lengthy script which calculates possible chemical formula for a given mass (based on a number of criteria), and outputs (amongst other things) a code which corresponds to the 'class' of compounds which that formula belong to. I calculate formula from batches of masses which should all be members of the same class. However, given instrumentation etc limits, it is possible to calculate several possible formula for each mass. I need to check if any of the classes calculated are common to all peaks, and if so, return the position of the match/etc.
I'm struggling with working out how to do an iterative if/for loop which checks every combination for matches (in an efficient way).
The image included summarises the issue:

Or on actual screenshots of the data structure:
image link here -

As you can see, I have a list called "formulae" which has a variable number of elements (in this case, 12).
Each element in formulae is a list, again with a variable number of elements.
Each element within those lists is a list, containing 15 7 elements. I wish to compare the 11th element amongst different elements.
I.e.
formulae[0][0][11] == formulae[1][0][11]

formulae[0][0][11] == formulae[1][1][11]
...
formulae[0][1][11] == formulae[11][13][11]

I imagine the answer might involve a couple of nested for and if statements, but I can't get my head around it.
I then will need to export the lists which matched (like formulae[0][0]) to a new array.
Unless I'm doing this wrong?
Thanks for any help!

EDIT:
1- My data structure has changed slightly, and I need to check that elements [?][?][4] and [?][?][5] and [?][?][6] and [?][?][7] all match the corresponding elements in another list.
I've attempted to adapt some of the code suggested, but can't quite get it to work...
check_O = 4
check_N = 5
check_S = 6
check_Na = 7
# start with base (left-hand) formula
nbase_i = len(formulae)
for base_i in range(len(formulae)):    # length of first index
for base_j in range(len(formulae[base_i])):    # length of second index
    count = 0
    # check against comparison (right-hand) formula
    for comp_i in range(len(formulae)):    # length of first index
        for comp_j in range(len(formulae[comp_i])):    # length of second index
            if base_i != comp_i:
                o_test = formulae[base_i][base_j][check_O] == formulae[comp_i][comp_j][check_O]
                n_test = formulae[base_i][base_j][check_N] == formulae[comp_i][comp_j][check_N]
                s_test = formulae[base_i][base_j][check_S] == formulae[comp_i][comp_j][check_S]
                na_test = formulae[base_i][base_j][check_Na] == formulae[comp_i][comp_j][check_Na]
                if o_test == n_test == s_test == na_test == True:
                                    count = count +1
                else:
                    count = 0
            if count < nbase_i:
                        print base_i, base_j, comp_i,comp_j
                o_test = formulae[base_i][base_j][check_O] == formulae[comp_i][comp_j][check_O]
                n_test = formulae[base_i][base_j][check_N] == formulae[comp_i][comp_j][check_N]
                s_test = formulae[base_i][base_j][check_S] == formulae[comp_i][comp_j][check_S]
                na_test = formulae[base_i][base_j][check_Na] == formulae[comp_i][comp_j][check_Na]
                if o_test == n_test == s_test == na_test == True:
                            count = count +1
            else:
                count = 0
            elif count == nbase_i:
                matching = "Got a match! " + "[" +str(base_i) + "][" + str(base_j) + "] matches with " + "[" + str(comp_i) + "][" + str(comp_j) +"]"
                print matching
        else:
            count = 0

A: I would take a look at using in such as
agg = []
for x in arr:
    matched = [y for y in arr2 if x in y]
    agg.append(matched)

A: Prune's answer not right, should be like this:
check_index = 11

# start with base (left-hand) formula
for base_i in len(formulae):    # length of first index
  for base_j in len(formulae[base_i]):    # length of second index

    # check against comparison (right-hand) formula
    for comp_i in len(formulae):    # length of first index
      for comp_j in len(formulae[comp_i]):    # length of second index
        if formulae[base_i][base_j][check_index] == formulae[comp_i][comp_j][check_index]:
          print "Got a match"
          # Here you add whatever info *you* need to identify the match

A: I'm not sure I fully understand your data structure, hence I'm not gonna write code here but propose an idea: how about an inverted index?
Like you scan once the lists creating kind of a summary of where the value you look for is.
You could create a dictionary composed as follows:
{
   'ValueOfInterest1': [ (position1), (position2) ],
   'ValueOfInterest2': [ (positionX) ]
}

Then at the end you can have a look at the dictionary and see if any of the values (basically lists) have length > 1.
Of course you'd need to find a way to create a position format that makes sense to you.
Just an idea.

A: Does this get you going?
check_index = 11

# start with base (left-hand) formula
for base_i in len(formulae):    # length of first index
  for base_j in len(formulae[0]):    # length of second index

    # check against comparison (right-hand) formula
    for comp_i in len(formulae):    # length of first index
      for comp_j in len(formulae[0]):    # length of second index
        if formulae[base_i][base[j] == formulae[comp_i][comp_j]:
          print "Got a match"
          # Here you add whatever info *you* need to identify the match


text:
Q: Add line break in a query (MySqli) What do I do for making som line breaks between the rows?
echo "
Resultat:

" . $row['resultat']. $row['resultat2']. $row['resultat3'] ;

A: Erm... put some line breaks?
$row['resultat']."
".$row['resultat2']."...";


text:
Q: How to store (in a variable) the Firestore document data that was read from database in Xcode I am trying to read data from Firebase Firestore, but there is no way to store the document data in a variable, because those variables will just be local and will be "garbage collected"
I tried making a function that tries to return the document content, but that resulted in an error because the "getDocument" method does not allow a return type.
docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        var dataValues = document.data()!.values
        self.textInput = dataDescription
        //I first tried doing it without the word self, but it gave an error insisting that I add self, but adding it makes it a local variable and not the String variable defined in the class
        //textInput is a String
        print("Document data: \(document.data()!.values)")
        //This will print out everything in the document
    } else {
        print("Document does not exist")
    }
}

I am trying to see if I can set any variable to the document data and still be able to access the data after reading the database.

A: I will suggest you to take look to https://firebase.google.com/docs/firestore/manage-data/transactions , Firebase have one of the most complete documentation, this will help you, to be exact you should do it like this:
let sfReference = db.collection("cities").document("SF")

db.runTransaction({ (transaction, errorPointer) -> Any? in
    let sfDocument: DocumentSnapshot
    do {
        try sfDocument = transaction.getDocument(sfReference)
    } catch let fetchError as NSError {
        errorPointer?.pointee = fetchError
        return nil
    }

    guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
        let error = NSError(
            domain: "AppErrorDomain",
            code: -1,
            userInfo: [
                NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
            ]
        )
        errorPointer?.pointee = error
        return nil
    }

    // Note: this could be done without a transaction
    //       by updating the population using FieldValue.increment()
    transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
    return nil
}) { (object, error) in
    if let error = error {
        print("Transaction failed: \(error)")
    } else {
        print("Transaction successfully committed!")
    }
}

as described in the Firebase Documentation.


text:
Q: rtree python polygon index Sorry for a very basic questions about rtree.
I would like to check whether the point is inside the polygon and the distance (point to the nearest point in polygon) as well. I was thinking about using No-SQL database, but both MongoDb and GeoCouch support Polygon records, but don't provide searches like:
- what polygons are around the point
(for example, I want to find near what polygons a user is currently located; and after that check what in the precise distance from the user to the nearest polygon point)

So, I want to figure out how to make these kind of spatial searches using python and related libraries only (shapely, geopy, rtree).
Here are the steps I am following:

*

*I have shapefile with the targeted polygons (saved from QGis)

*I want to make Rtree Index, to improve performance when working with Shapely and geopy

I am wondering, whether I can:

*

*make Rtree Index for shapefile directly?

If not. I can use shapefile lib to collect polygon coordinates or bounding boxes:
>>> shapes[33].points
[[120.9937913, 24.7902669], [120.9939797, 24.790369], [120.994035, 24.7902849], [120.9938467, 24.7901828], [120.9937913, 24.7902669]]

>>> shapes[33].bbox
[120.9937913, 24.7901828, 120.994035, 24.790369]

Now I am a bit confused, and trying to understand how to create rtree index file for my polygons:
>>> idx = index.Index()  //creating index
>>> left, bottom, right, top = (24.7901828, 24.790369, 120.9937913, 120.994035) // can I put bbox coordinates here? I assume that coordinates are in the form [xmin, xmax, ymin, ymax]
>>> idx.insert(0, (left, bottom, right, top))

Would it be a right way for me to make Rtree Index?:
import shapefile
from rtree import index
sf = shapefile.Reader("polygons.shp")
idx = index.Index()
shapes = sf.shapes()
id_num = 0
for shape in shapes:
    sh = shape.bbox
    xmin = sh[1]
    ymin = sh[0]
    xmax = sh[3]
    ymax = sh[2]
    idx.insert(id_num, (xmin,ymin,xmax,ymax))
    id_num = id_num + 1

After I execute the script above, I can get the following result from idx.bounds:
>>> idx.bounds
[24.7796055, 120.9839184, 24.7986571, 121.0025152]

To what bounds these coordinates are related to? Is it the bbox for the all the polygons?
Is this a right way to check whether there are polygons near the Point?
Assuming that the point coordinates are 24.789077, 120.999792
>>> list(idx.nearest((24.789077, 24.789077, 120.999792, 120.999792)))
[1, 2, 13, 29, 61, 62, 59, 60, 27, 28, 55, 5, 26, 54, 78, 49, 50, 3, 9, 10, 22, 72, 43, 39, 42, 85, 40, 8, 17, 76, 77, 36, 73, 71, 33, 34, 69, 63, 66, 64]

I am getting these results and not quite sure what they mean.. What does "nearest" exactly mean here? I cannot measure the distance here, like 5 meters.. so what is the "nearest" output here and how it's calculated?

A: Your questions are answered in Rtree's docs, which come with the source and are online at http://toblerity.github.com/rtree/tutorial.html.
You can make your shapefile indexing code much simpler:
for i, shape in enumerate(shapes):
    idx.insert(i, shape.bbox)

Use Python's enumerate() function for this kind of thing whenever possible. It's tidy and foolproof.


text:
Q: Issue plotting a scatterplot with matplot I tried to plot some figures inside a for loop from jupyter notebook:
for i in range(4):
    df = pd.DataFrame()
    df['x'] = features[:, 0]
    df['y'] = features[:, 1]

    plt.plot(df["x"], df["y"])
    plt.show()

I got the following for the first figure. Do you know what is the problem please?

A: Use pyplot.scatter() for scatter graph and pyplot.plot() for line graph.


text:
Q: connect_to_splunk() takes exactly 2 arguments (1 given) Splunk_WAN_Methods
class Splunk_Methods(object):

    def __init__(self, username, password, hostname, port):
        self.count = 0  # number of devices to get data for. "0" means no limit
        self.HOST = hostname
        self.PORT = port
        self.USERNAME = username
        self.PASSWORD = password

    def connect_to_splunk(self, app):
        '''
        Purpose: Connects to splunk and returns connection_id object handler.
        Input: none
        Output: connection object handler
        '''
        splunk_connection_service = client.connect(
            host=self.HOST,
            port=self.PORT,
            username=self.USERNAME,
            password=self.PASSWORD,
            OWNER="wanro",
            app=app,  # app context has to be defined for get_device_hostname function to work
            verify=False)  # to disable ssl check

        return splunk_connection_service

Main.py
from Splunk_WAN_Methods import Splunk_Methods

if __name__ == '__main__':
    # Connect to splunk
    LOCAL_DIR = os.path.dirname(os.path.realpath(__file__))
    DIR_PATH = os.path.abspath(os.path.join(LOCAL_DIR, os.pardir))
    print DIR_PATH
    sys.path.append(DIR_PATH)

    print LOCAL_DIR
    print DIR_PATH

    with open("%s\environment.conf" % LOCAL_DIR, 'r') as config_file:
        CONFIG_DATA = json.load(config_file)
        print CONFIG_DATA

    ENVIRONMENT = "wan"
    SPLUNK_VARS = CONFIG_DATA[ENVIRONMENT]['splunk']
    #print SPLUNK_VARS

    splunk_api_instance = Splunk_Methods(SPLUNK_VARS['username'],SPLUNK_VARS['password'],SPLUNK_VARS['hostname'],SPLUNK_VARS['port'] )
    #print splunk_api_instance

    splunk_connection = splunk_api_instance.connect_to_splunk('wansa_dashboard_app')
    #print splunk_connection

    splunk_api_instance.get_saved_search_result(splunk_connection, 'ospf_nbrs')
    print splunk_connection
    print SPLUNK_VARS

    class_splunk_methods = Splunk_Methods('username', 'password', 'hostname', 'port')
    try:
        splunk_connection_service = class_splunk_methods.connect_to_splunk()
    except  Exception as e:
        print "Could not connect to Splunk"
        print e
        sys.exit(1)

    #Get todays date
    now = datetime.datetime.now()
    today_date = now.strftime("%Y-%m-%d %H:%M:%S") #2018-09-13 13:02:39

Result with Error
C:\Users\U6067069\eclipse-workspace\Int_DESC_NEW\Unit_test_audit\network_compliance_engine1\code
C:\Users\U6067069\eclipse-workspace\Int_DESC_NEW\Unit_test_audit\network_compliance_engine1
{u'wan': {u'splunk': {u'username': u'xxx', u'password': u'xxx', u'hostname': u'xxx', u'xxx': u'xxx'}}}

"uk2-corewan-p3","Bundle-Ether3","ld4-corewan-p1","Bundle-Ether3"
"uk1-corewan-pe3","TenGigE0/1/1/0","uk2-corewan-p3","TenGigE0/0/1/2"
"uk2-corewan-p3","TenGigE0/0/1/2","uk1-corewan-pe3","TenGigE0/1/1/0"
"lo5-corewan-p1","FortyGigE0/0/0/1","uk2-corewan-p3","FortyGigE0/4/0/1"

<splunklib.client.Service object at 0x04074B30>
Could not connect to Splunk
connect_to_splunk() takes exactly 2 arguments (1 given)

A: def __init__(self, username, password, hostname, port):

This means that you have to pass all these paramaters when you instantiate Splunk_Methods(), eg
Splunk_Methods('user','pass','google.com',1337)


text:
Q: Prove difficult integral equality which is continuous and periodic function and has a primitive.
Let $f:\mathbb{R}\rightarrow \mathbb{R}$ be a continuous and periodic function with period $P$ and let $F$ be a primitive of $f$.
  Prove that:
  $$\lim_{n\rightarrow \infty }\frac{1}{n}\sum_{k=1}^{n}\frac{F(k)}{k}\cdot f\left ( \frac{k}{n} \right )=\frac{1}{P}\cdot \int_{0}^{P}f(x)dx\cdot \int_{0}^{1}f(x)dx$$

I know that $\frac{1}{P}\cdot \int_{0}^{P}f(x)dx=f(c)$ where $c\in (0,P)$ and that the LHS of the equation could be written as a Riemann sum, but I haven't found something helpful yet.


text:
Q: Question incorrectly stated as answer and vice versa Is there something up with the review queue today? In the text it mentions first question but it is really an answer.

Or it mentions first answer when it is really a question.


text:
Q: Trying to upload files with Multer to NodeJS app running on Kubernetes Pods (3 replicas) I have a NodeJS app that is running on a Kubernetes cluster which has 3 pods replicas. I use Multer to upload the files to a specific folder, /public/upload with other folders in it. When I upload a profile photo, for example, it is saved on /public/upload/profiles. I want that for photos that are uploaded on one Pod, to show up on all running Pods, so for that reason I use a "Persistent Volume" and its respective "Persistent Volume Claim" connected to the /public/upload, but the uploaded photos are not showing up on all the Pods, only on the Pod that the upload was done. I leave below the whole code for Kubernetes Volume and VolumeClaim and the Multer app. I would like to have the files uploaded on one Pod to show up on all Pods, but I can't find any solution online. I thought that by creating a Persistent Volume this would be done automatically. Am I doing something wrong? Is there a configuration for this? Is it an error on configuring the Volumes?
Thank you very much for your help!

Volumes Deployment file:
kind: PersistentVolume
apiVersion: v1
metadata:
  name: testapp-volume
  labels:
    type: local
spec:
  capacity:
    storage: 5Gi
  storageClassName: manual
  persistentVolumeReclaimPolicy: Delete
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/app-folder/uploads"

---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: testapp-volumeclaim
  namespace: testapp-namespace
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: manual

Pods and Service Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: testapp-deployment
  namespace: testapp-namespace
  labels:
    app: testapp-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: testapp-deployment
  template:
    metadata:
      labels:
        app: testapp-deployment
    spec:
      containers:
        - name: testapp-container
          image: /* Repository */
          ports:
            - containerPort: 2000
          imagePullPolicy: Always
          volumeMounts:
            - mountPath: /public/uploads
              name: testapp-volume
      imagePullSecrets:
        - name: testapp-secret
      volumes:
        - name: testapp-volume
          persistentVolumeClaim:
            claimName: testapp-volumeclaim

---

apiVersion: v1
kind: Service
metadata:
  name: testapp-deployment
  namespace: testapp-namespace
spec:
  type: ClusterIP
  selector:
    app: testapp-deployment
  ports:
    - protocol: TCP
      port: 5000
      targetPort: 2000

Multer code:
var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './public/uploads/' + req.body.folder)
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        var ext = path.extname(file.originalname);
        ext = ext.toLowerCase();
        console.log("FILE -> " + file.originalname + " ; RANDOM NUM -> " + generateRandomNumber(12) );
        cb(null, generateRandomNumber(14) + '_' + datetimestamp + '' + ext);
    }
});

var file_upload = multer({
    storage: storage,
    fileFilter: function (req, file, callback) {
        var ext = path.extname(file.originalname);
        ext = ext.toLowerCase();
        if(ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
            return callback(new Error('Only documents are allowed'));
        }
        callback(null, true)
    },
    limits:{
        fileSize: 1024 * 1024 * 100
    }
});


text:
Q: MS SQL Server Data Anonymise I have this requirement: we are going to restore production database into UAT for testing few use cases. We should anonymise required data (Ex: SSN, Credit Card etc) from all types of users (including sysadmin, db owner). No one should be able to get real records.
Also application/UI layer not going to implement any changes (to decrypt or unmask) because of time line.
I have tried below option but not able to achieve my use case

*

*Dynamic Masking - Admin Can able to view

*Always Encrypted - It encrypts records (not  mask)

*Static Mask - This override actual data and will miss real record

We have to anonymise the data from all users with out missing actual records. What is the best option to achieve this?


text:
Q: CRUD in react-redux, showing post details from enother page I am new in react-redux, and have a problem with state managment i think. I want to get post details from main table on home page, to show post details in details page...When i click on button details i change a path "/details/1, and i want to show post deteils with id=1. i get {post: undefined, getDetails: ƒ}
action.js
export const postDetails = (data, id) => ({
        type: "POST_DETAILS",
        post: data,
        id: id
})

reducer.js
case "POST_DETAILS":
    return state.posts.map((post) => {
        if(post.id === action.id) {
            return {
                ...post,
                post: post
            }
        }
    })

container- GetDetails.js
const mapStateToProps = state => ({ post: state.post });

const mapDispatchToProps = dispatch => {
    return {
        getDetails: (data, id) => dispatch(postDetails(data, id))
    };
};

const GetDetails = connect(
    mapStateToProps,
    mapDispatchToProps
)(Details)

export default GetDetails;

component-Details.js
class Details extends React.Component {
    constructor(props){
        super(props);
    }

    componentDidMount() {
        this.props.getDetails(this.props.post, this.props.id);
    }

    render() {
        return (

                Details page

                        {this.props.post}

        )
    }
}

export default Details;

A: Your reducer is decimating its own state until state becomes undefined. You are starting with a state that is an object, but you are returning only one field of that object.
Starting with a state like this:
{
  loading: false,
  posts: [
    {
      id: 1
      post: 'foo',
      author: 'bar'
    },
    {
      id: 2
      post: 'fooz',
      author: 'barz'
    }
  ]
}

Dispatching an action like this:
{
  type: "POST_DETAILS",
  id: 1,
  post: 'this is never accessed'
}

will result in an array
[
  {
    id: 1
    post: {
      id: 1
      post: 'foo',
      author: 'bar'
    },
    author: 'bar'
  },
  undefined
]

Dispatching the action again will result in the state being undefined.
A third time will result in an error.
In your reducer, you probably meant to do something like this instead.
case "POST_DETAILS":
    return { ...state, posts: state.posts.map((post) => {
          if(post.id === action.id) {
              return {
                  ...post,
                  post: action.post
              }
          } else {
              return post
          }
      })
    }


text:
Q: Conditional recode in R I have ten gender variables from 2007-2017 (gender1, gender2,...,gender17).
I want to create an overall_gender variable equal to the most recent gender record.
Ideally I want to use a loop that says something like: if gender17 = "N/A", use gender16, if gender16 != "N/A"; and so on.
For example:
       ID y1 y2 y3 y4 y5 y6 y7 y8 y9 y10
1 person1  M  M  M  M  M  M  M  M  M  NA
2 person2  M  M  M  M  NA NA NA NA NA NA
3 person3  F  F  F  F  F  F  NA NA NA NA
4 person4  M  M  M  M  F  F  F  NA NA NA

Desired output:
       ID Gender
1 person1      M
2 person2      M
3 person3      F
4 person4      F

Any ideas on how to do this?

A: You could do something like this, using tail and is.na to identify the latest non-NA value
#example data
df <- data.frame(Gender1=c("M","F"),Gender2=c("M","M"),
                 Gender3=c(NA,"M"),Gender4=c(NA,NA),stringsAsFactors = FALSE)

df$overall_gender <- apply(df,1,function(x) tail(x[!is.na(x)],1))

df

  Gender1 Gender2 Gender3 Gender4 overall_gender
1       M       M    <NA>      NA              M
2       F       M       M      NA              M

A: With dplyr + tidyr:
library(dplyr)
library(tidyr)

bind_cols(df, df %>%
  gather(variable, Gender, -ID) %>%
  na.omit() %>%
  arrange(ID, variable) %>%
  group_by(ID) %>%
  slice(n())) %>%
  select(-variable, -ID1)

Result:
       ID y1 y2 y3 y4   y5   y6   y7   y8   y9 y10 Gender
1 person1  M  M  M  M    M    M    M    M    M  NA      M
2 person2  M  M  M  M <NA> <NA> <NA> <NA> <NA>  NA      M
3 person3  F  F  F  F    F    F <NA> <NA> <NA>  NA      F
4 person4  M  M  M  M    F    F    F <NA> <NA>  NA      F

Data:
df = read.table(text = "       ID y1 y2 y3 y4 y5 y6 y7 y8 y9 y10
                1 person1  M  M  M  M  M  M  M  M  M  NA
                2 person2  M  M  M  M  NA NA NA NA NA NA
                3 person3  F  F  F  F  F  F  NA NA NA NA
                4 person4  M  M  M  M  F  F  F  NA NA NA", header = TRUE)

A: Here is a fairly compact solution, assuming that the column names will always have the form "y*" with * a number:
library("dplyr")

# where `dat` is the table in the post:
dat %>%
  reshape2::melt(id.vars="ID") %>%
  filter(!is.na(value)) %>%
  mutate(variable = as.numeric(gsub("y", "", as.character(variable)))) %>%
  group_by(ID) %>%
  summarize(gender = value[variable==max(variable)])

You can use mutate() instead of summarize() if you want to maintain the information in the long-form dataset (all the info in the original table, except doesn't list the NA's). But if you do that, make sure to pipe the result into ungroup() right after!


text:
Q: XCode NSMutableURLRequest not hitting the web server I have several series of images stored in folders on a web server. The folder hierarchy looks something like this…
WebServer's Web Folder
   _20160123161915_4671579
       Final
          t1.jpg
          t2.jpg
          i1.jpg
          i2.jpg
       Recall
          t1.jpg
          t2.jpg
          i1.jpg
          i2.jpg
       Initial
          t1.jpg
          t2.jpg
          i1.jpg
          i2.jpg

The user selects one of the series, initial, Recall, or Final from a list on the iPad and the series is retrieved from the server and displayed. I am using the following code to retrieve the images. In this example I am retrieving the the jpgs that start with a t…
for (int i = 0; i < imageCount; i++) {
    fileName = [NSString stringWithFormat:@"t%i.jpg", i+1];
    imagePath = [NSString stringWithFormat:@"_%@/%@/%@", [opHelper ID], [seriesArray objectAtIndex:thumbsSeriesIndex], fileName];
    urlString = [[NSString stringWithFormat:@"http://%@/%@", [opHelper hostIP], imagePath] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    url = [NSURL URLWithString:urlString];
    imageURL = [NSMutableURLRequest requestWithURL:url];
    NSURLResponse *response;
    NSError *error;
    imageData = [NSURLConnection sendSynchronousRequest:imageURL returningResponse:&response error:&error];
        //consume the imageData
}

This works except for once in a while I get back blank images for one of the series. In my example, I would get good images with Initial and Recall, but Final comes back with blanks. A 500kb file is requested and imageData gets 800 bytes. I can watch the server hit count increase for each image request. If a series fails the server does not get hit at all. ie. If in the above example file hierarchy I select Recall the server count increases by 4, same with Initial, but if I select Final the server count does not increment.
Here are the actual NSURLs being sent…
url NSURL * @"http://192.168.1.100/_20160123161915_4671579/Final/t1.jpg"    0x80a7f640
url NSURL * @"http://192.168.1.100/_20160123161915_4671579/Recall%201/t1.jpg"   0x804fbcf0
url NSURL * @"http://192.168.1.100/_20160123161915_4671579/Initial/t1.jpg"  0x8088da30

The url for Final in this case was acting up and not hitting the server, but I don't see anything that jumps out at me in the URLs that might be suspect. Does anyone see anything in my code that might be contributing to this problem? I know it is not a file issue as even if I rename one of the working folders so that the requested file cannot be found, the server gets hit and the iPad receives blank images without any errors.
Thanks for any help.
John

A: Ok. It was a cache issue. I fixed it by modifying the cache policy...
 imageURL = [NSMutableURLRequest requestWithURL:url];
 imageURL.cachePolicy = NSURLRequestReloadIgnoringCacheData;

John


text:
Q: Matplotlib changing underlying data for scatter plot with widget buttons I have a plot in which I want to plot the following two data sets
x1,y1 = np.random.normal(0,1, (2,20)) # dataset 1
x2,y2 = np.random.normal(0,1, (2,20))

# Next, I create a plot and the PathCollection  from the scatter
fig, ax = plt.subplots()
ax = plt.gca()
p =  ax.scatter(x1, y1)

# I create two functions, each set the data using a different data set
def set_data1(event):
    p.set_offsets(x1, y2)
    plt.draw()

def set_data2(event):
    p.set_offsets(x2, y2)
    plt.draw()

# Location for the buttons
btn_1_loc = fig.add_axes( [0.02, 0.90, 0.2, 0.075])
btn_2_loc = fig.add_axes( [0.02, 0.80, 0.2, 0.075])

# Now, actually add the buttons
btn_1 = Button(btn_1_loc, 'Button 1')
btn_1.on_clicked(set_data1)

btn_2 = Button(btn_2_loc, 'Button 2')
btn_2.on_clicked(set_data2)

This creates a plot, with buttons. When I click the buttons, the data is not changed. If instead I change the color of the points with p.set_facecolor(color1) and color2, the plot does change and update.
How do I change the (x,y) location of my points using these two buttons?

A: set_offsets takes a 2D array, you're passing 2 individual arrays.
Solution:
def set_data1(event):
    p.set_offsets(np.column_stack((x1, y1)))
    plt.draw()

def set_data2(event):
    p.set_offsets(np.column_stack((x2, y2)))
    plt.draw()


text:
Q: Heuristic approach to winding number I'm working on problem 8.23 of Rudin's PMA, that is:

Let $\gamma:[a,b]\to\mathbb C$ be a closed curve, $\gamma \in C^1([a,b])$ and $\gamma(t) \neq 0 \ \forall t\in [a,b]$. Show that $$\text {Ind}(\gamma)=\frac{1}{2 i \pi} \int _a ^b \frac{\gamma '}{\gamma}$$
  is an integer.

My idea was to express $\gamma$ in polar coordinates: $$\gamma(t)=r(t)e^{i\theta (t)},$$
so that $$\gamma '(t)=r'(t)e^{i\theta(t)}+r(t)e^{i\theta (t)}\cdot i\theta'(t)$$
and $$\frac{\gamma'(t)}{\gamma(t)}=\frac{r'(t)}{r(t)}+i\theta'(t).$$
Integrating over $[a,b]$ and noting that the first term vanishes:$$\frac{\theta(b)-\theta(a)}{2\pi}.$$
Since $\gamma (a)=\gamma (b)$ and $e^{i\theta}$ has period $2\pi$, this is an integer.
Now, there are some issues that I don't know how to fix. Let $x,y$ denote $\text{Re}\gamma $ and $\text {Im} \gamma$. Since $\gamma \in C^1$, follows that $x,y\in C^1$ and consequently $r=\sqrt{x^2+y^2}\in C^1$.
What about $\theta$? Suppose for example that I define $\theta (a)$ to be the smallest positive that satisfies $\frac{\gamma(a)}{r(a)}=e^{i\theta(a)}$. I know that, then, I could define $\theta$ locally via $\tan ^{-1}$ and I would get a $C^1$ function. But how can I define a function $\theta\in C^1$ that keeps count of the windings around zero?

A: You can locally, in a neighbourhood of each $t\in [a,b]$ define a family $\theta_{t,k}$ of differentiable argument functions via all possible branches of $\tan^{-1}$ or $\cot^{-1}$. Since $[a,b]$ is compact, $\gamma$ is uniformly continuous, hence there is a $\delta > 0$ such that for all $t\in [a,b]$, you can define a differentiable argument of $\gamma(t)$ at least on the neighbourhood $[t-\delta,t+\delta] \cap [a,b]$ of $t$. Then you can cover $[a,b]$ with finitely many such intervals, and glue together a family of local arguments to obtain a differentiable global argument. Starting with an arbitrary choice of $\theta_{a,0}$, extend it by $\theta_{a+\delta, k_1}$ such that $\theta_{a,0}(a+\delta/2) = \theta_{a+\delta,k_1}(a+\delta/2)$ to obtain a differentiable argument on $[a,a+2\delta]$. Since the two glued-together argument functions agree in one point of the overlap and are continuous, and their difference can take only integral multiples of $2\pi$ as values, they agree on the entire overlap of their domains. Continue until you have reached $b$.