text:
Q: Proving that the sum of the first $2n$ terms of the series $1^2 - 3^2 + 5^2 - \cdots$ is $-8n^2$ by induction
Use mathematical induction to prove the following for the first $2n$ terms of the series $$1^2 - 3^2 + 5^2 - 7^2 + \cdots = -8n^2.$$

As we have odd numbers that are squared we could use $n = 2k-1$.
But the $2$ sides do not equate for $n=1$ or $2k-1$ (if you set $k=1$).
Also need to find the sum to $2n+1$ terms.

A: Here is the main part of the inductive step:
\begin{align}
\sum_{i=1}^{2(k+1)}(-1)^{i-1}(2i-1)^2&=\sum_{i=1}^{2k}(-1)^{i-1}(2i-1)^2+\underbrace{(-1)^{2k+1}(4k+3)^2}_{i=2k+2}+\underbrace{(-1)^{2k}(4k+1)^2}_{i=2k+1}\\[0.5em]
&= -8k^2-(4k+3)^2+(4k+1)^2\\[0.5em]
&= -8k^2-16k-8\\[0.5em]
&= -8(k^2+2k+1)\\[0.5em]
&= -8(k+1)^2.
\end{align}
Do you see where the induction hypothesis was used?

A:
As we have odd numbers that are squared we could use n = 2k-1

You are summing the sequence:  $\{1^2-3^2, 5^2-7^2, 9^2-11^2, \ldots (4n-3)^2-(4n-1)^2, \ldots\}$

But the 2 sides do not equate for n=1 or 2k-1 (if you set k=1)

See above. The first term is $-8$, and so...

Also need to find the sum to (2n+1) terms.

You need to show that if the sum of the first $n$ terms is $-8 n^2$, then if you add $-16(n+1)+8$ you obtain $-8(n+1)^2$.

A: $$a_n = \sum_{k=1}^{n}(-1)^{k+1}(2k-1)^2 $$
You need to rewrite your function to accommodate your analysis. If you have to analyse every pair of values you could rewrite it as:
$$b_m = \sum_{k=1}^{m}(4k-3)^2-(4k-1)^2$$
But that's
$$\sum_{k=1}^{m}(4k-3)^2-(4k-1)^2 = \sum_{k=1}^{m}(16k^2-24k+9 - 16k^2+8k-1) = \sum_{k=1}^{m}(-16k+8)$$
So:
for $$n = 2 \implies m = 1$$
$$\sum_{k=1}^{1}(-16k+8) = -16 + 8 = -8$$
Now, assuming for $2n$ works, what's $2n+2$ in $a_n$. But that's the same for testing $m+1$ assuming $m$ is true for $b_n$
$$\sum_{k=1}^{m+1}(-16k+8) = \left(\sum_{k=1}^{m}(-16k+8)\right) -16(m+1)+8  = -8m^2 -16m  -16 +8 =-8m^2 -16m  -8 = -8(m+1)^2$$

A: $1^2−3^2+5^2−7^2+⋯=−8n^2$
Last term of this series is $(4n-3)^2-(4n-1)^2$
$\Rightarrow P(n):1^2−3^2+5^2−7^2+⋯+(4n-3)^2-(4n-1)^2=−8n^2$
For n=1
$\Rightarrow P(1):1^2−3^2=−8(1)^2$
$\Rightarrow P(1):-8=−8$ which is true
Let P(k)be true,
$P(k):1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2=−8k^2$.......(1)
We have to prove P(k+1) as true.
$P(k+1):1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2+(4(k+1)-3)^2-(4(k+1)-1)^2=−8(k+1)^2$
$LHS=1^2−3^2+5^2−7^2+⋯+(4k-3)^2-(4k-1)^2+(4k+1)^2-(4k+3)^2$
$=-8k^2+(4k+1)^2-(4k+3)^2$
$=-8k^2+16k^2+8k+1-(16k^2+24k+9)$
$=-8k^2-16k-8=-8(k^2+2k+1)=-8(k+1)^2$=RHS
Therefore P(k+1) is true.So by Induction principle,P(n) is true for all $n$


text:
Q: NGX-CHIPS not rendering Firebase returned list I am using NGX-Chips in Angular. I am saving the typed in chips into Firebase and retrieving them.
Problem is, when it tries to render the saved chips, it can't and throws an error.
Before posting this question, I tried to read through and follow this issue on GitHub and added the displayBy and identifyBy tag with no avail.
THE ERROR
Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

HTML Code
<tag-input
     (onAdd)="onCategoryAdded($event, product.external_id)"
    [displayBy]="'display'"
    [identifyBy]="'$key'"
    [(ngModel)]="product.categories"
    [ngModelOptions]="{standalone: true}"
    theme="minimal"
    placeholder="Categories"
>
 <tag-input-dropdown [autocompleteItems]="categories"></tag-input-dropdown></tag-input>
</tag-input>

In my controller, I set an observable item, listen for value changes and assign those to mentioned observable.
public products: Observable<any[]>;

ngOnInit() {
   this.products = this.afd.list('/products').valueChanges();
}

onCategoryAdded(event, product) {
  this.afd.database.ref('/products').orderByChild('external_id').equalTo(product).once('value', (snapshot) => {
    snapshot.forEach((product) => {
      this.afd.database.ref('/products').child(product.key).child('categories').push({
        'display' : event.display,
        'value' : event.value
      });
    });
  });
}

product.categories prints out like below when I add {{product.categories | json}} to my html.
{ "-LfN8VhSrWBye-8ukSAq": { "display": "Featured", "value": "Featured" } }

Should I alter how I save the categories in Firebase so it returns a different value or should I transform the returned value somehow within the controller?

A: Just as described in the error NGX-CHIPS is waiting for an array and you are passing an object
Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
You are passing this to NGX-CHIPS

{ "-LfN8VhSrWBye-8ukSAq": { "display": "Featured", "value": "Featured" } }

you need to convert this json/object to an array you can do that using the map operator
// don't forget to import the operator

import { map } from 'rxjs/operators'

ngOnInit() {
   this.products = this.afd.list('/products').valueChanges().pipe(
map(list => {

      const productsArray = Object.keys(list).map(key => {
         const item = list[id]; // [{display: 'Featured', value: 'Featured'}]
         item.key = key;  // [{key: "-LfN8VhSrWBye-8ukSAq", display: 'Featured', value: 'Featured'}]
         return item;
      });

   }));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to join two dataframes with different key column names in pydatatable? I have a X dataframe as,
DT_X = dt.Frame({

    'date':['2020-09-01','2020-09-02','2020-09-03'],
    'temp':[35.3,32.9,43.2]

})

Out[4]:
   | date        temp
-- + ----------  ----
 0 | 2020-09-01  35.3
 1 | 2020-09-02  32.9
 2 | 2020-09-03  43.2

[3 rows x 2 columns]

Another dataframe Y as,
DT_Y = dt.Frame({

    'stop_date' : ['2020-08-01','2020-09-01','2020-09-03','2020-09-07'],
    'is_arrested':[True,False,False,True]

})

Out[6]:
   | stop_date   is_arrested
-- + ----------  -----------
 0 | 2020-08-01            1
 1 | 2020-09-01            0
 2 | 2020-09-03            0
 3 | 2020-09-07            1

[4 rows x 2 columns]

Now I would like to perform JOIN operation on X and Y, for that i'm supposed to assign a key on X dataframe as,
DT_X.key='date'

Out[8]:
date       | temp
---------- + ----
2020-09-01 | 35.3
2020-09-02 | 32.9
2020-09-03 | 43.2

[3 rows x 2 columns]

Next I'm joining X and Y as ,
DT_Y[:,:,join(DT_X)]

Here it is throwing out an error as ,
In [9]: DT_Y[:,:,join(DT_X)]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-a3bc1690fb98> in <module>
----> 1 DT_Y[:,:,join(DT_X)]

ValueError: Key column `date` does not exist in the left Frame

Of course date is not existed in DT_Y, it has a column name as stop_date.
How to perform join operations in this scenario ?? i.e No match of column names.
Note :
An work around for this is to change the column name of DT_Y as
DT_Y.names = {'stop_date':'date'}

DT_Y[:,:,join(DT_X)]

The joined DT can be viewed as,
Out[11]:
   | date        is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA

[4 rows x 3 columns]

Here is the expected output:
Out[13]:
   | stop_date   is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA

[4 rows x 3 columns]

A: Right now, join() only supports the same column names in the both frames, please refer to documentation for more details. However, there is an open issue to improve the join functionality/API.
Meanwhile, if you prefer not to rename the columns you can do the following
DT_Y_date = DT_Y[:, {"date":f[0], "is_arrested":f[1]}]
DT_YX_joined = DT_Y_date[:, :, join(DT_X)]

Then, DT_YX_joined will have the data you are looking for
   | date        is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA

You can even do a one-liner like
DT_YX_joined = DT_Y[:, {"date":f[0], "is_arrested":f[1]}][:, :, join(DT_X)]

but it may not be readable enough. Also note, that no data copies are created here, it is only the column name that changes.


text:
Q: Setting Group Owner using workflow 2013 and REST We wanted to have a group created while specifying the group owner upon creation. Is that possible?
The rest call to /_api/currentsite/sitegroups using POST will create a group, but there is an "Owner" field that I'm trying to specify, and the type is an "SP.Principal" but I'm not sure how to do that...
Any ideas?

A: I'm using Powershell and CSOM to do this so there has to be a way to do it in REST I would think.
Function Set-GroupOwner{

    Param(
        [Parameter(Mandatory=$true,HelpMessage="The URL of the site collection",Position=0)][ValidateNotNull()]
        [string]$SiteUrl,

        [Parameter(Mandatory=$true,HelpMessage="The group that needs updated",Position=1)][ValidateNotNull()]
        [string]$GroupToUpdate,

        [Parameter(Mandatory=$true,HelpMessage="The desired group owner",Position=2)][ValidateNotNull()]
        [string]$GroupOwner

    )
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password)

    $owner = $context.Web.SiteGroups.GetByName($GroupOwner)
    $group = $context.Web.SiteGroups.GetByName($GroupToUpdate)

    $group.Owner = $owner
    $group.Update()
    $context.ExecuteQuery()

    $context.Dispose()
}

I adapted it from  https://stackoverflow.com/a/25654742/318776. Hope it helps.


text:
Q: Enum in Javascript In Javascript I'm going to read data (strData). But the data are String values, but I have to work with Integer values.
For example:
intData = strData;

...where strData could be "A", "B", or "C".
But intData should be 1 for "A", 2 for "B", or 3 for "C".
I could just do an If-else statement, but I have to get strData very often. In this case, I always have to "if-else" the content of strData. So I need something to keep the code as short as possible. An one-time allocation of the Integer values to the String values. How I have to impelement that?
Thanks for your help!

A: intData = ({ A: 1, B: 2, C: 3})[strData]
For example (transcript from Chrome debugger console):
>  (function() { var strData = "C"; return ({ A: 1, B: 2, C: 3})[strData]; })()
<- 3

A: I think you should use Object.Freeze with plain object:
var ENUM = Object.freeze({a: 1});
ENUM['a'];


text:
Q: transformToXml returns false but libxml_get_last_error() empty I am trying to transform an XML file using XSL in PHP. Both the XML and XSL files are loaded correctly from the local file system, but when I call:
$xslt->transformToXml($xml)

it returns false, yet both libxml_get_last_error() and libxml_get_errors() are empty.
Is there a way I can debug this or get some useful errors?
NB. My error_reporting is E_ALL | E_STRICT, display_errors is on.


text:
Q: Flutter - Upload file from gallery or camera to firestore => I get an error: _CastError (Null check operator used on a null value) I'm trying to take picture from Gallery or Camera, and upload it to Firestore.
I have a problem when I get into the Gallery/Camera, and I don't take any picture. When I want to 'pop' back from Gallery\Camera without any image taken, I get an error:
_CastError (Null check operator used on a null value)
in this row:
await ref.putFile(imageFile!);

I had the same problem when I tried just to take picture from Gallery/Camera without uploading it to Firestore, but I solved it with this code:
if (pickedFile == null) {
      imageFile ==
          Image.network(
              'https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-1577909_1280.png');
    } else {
      setState(() {
        imageFile = File(pickedFile.path);
      });

The complete code from this screen is below:
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:test_two/screens/screen_three.dart';

class ScreenFour extends StatefulWidget {
  ScreenFour({Key? key}) : super(key: key);

  @override
  State<ScreenFour> createState() => _ScreenFourState();
}

class _ScreenFourState extends State<ScreenFour> {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  File? imageFile;
  String? imageUrl;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('SEND IMAGE TO FIRESTORE')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
                onTap: () {
                  _showImageOrGalleryDialog();
                },
                child: const Text(
                  '''TAP TO IMPORT PICTURE FROM CAMERA OR GALLERY AND SEND IT TO FIRESTORE''',
                  textAlign: TextAlign.center,
                )),
            const SizedBox(
              height: 10,
            ),
            Container(
              height: 100,
              width: 100,
              decoration: BoxDecoration(
                border: Border.all(width: 1, color: Colors.white),
                borderRadius: BorderRadius.circular(16),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: imageFile == null
                    ? Image.network(
                        'https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-1577909_1280.png',
                        fit: BoxFit.fill,
                      )
                    : Image.file(
                        imageFile!,
                        fit: BoxFit.fill,
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _getImagesFromGallery() async {
    final User? user = _auth.currentUser;
    final _uid = user?.uid;
    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
      maxWidth: 1080,
      maxHeight: 1080,
    );

    // I had the same problem here, so I wrote the code below, and it worked
    if (pickedFile == null) {
      imageFile ==
          Image.network(
              'https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-1577909_1280.png');
    } else {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
    Navigator.pop(context);

    // Upload image to Firestore
    final ref = FirebaseStorage.instance
        .ref()
        .child('userImages')
        .child(_uid! + '.jpg');
    await ref.putFile(imageFile!);
    imageUrl = await ref.getDownloadURL();
    FirebaseFirestore.instance
        .collection('profileImages')
        .doc(_uid)
        .set({'userImage': imageUrl});
  }

  void _getImagesFromCamera() async {
    final User? user = _auth.currentUser;
    final _uid = user?.uid;
    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
      maxWidth: 1080,
      maxHeight: 1080,
    );
    if (pickedFile == null) {
      imageFile ==
          Image.network(
              'https://cdn.pixabay.com/photo/2016/08/08/09/17/avatar-1577909_1280.png');
    } else {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
    Navigator.pop(context);

    // Upload image to Firestore
    final ref = FirebaseStorage.instance
        .ref()
        .child('userImages')
        .child(_uid! + '.jpg');
    await ref.putFile(imageFile!);
    imageUrl = await ref.getDownloadURL();
    FirebaseFirestore.instance
        .collection('profileImages')
        .doc(_uid)
        .set({'userImage': imageUrl});
  }

  void _showImageOrGalleryDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('please choose an option'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  _getImagesFromCamera();
                },
                child: Row(
                  children: const [
                    Padding(
                      padding: EdgeInsets.all(8.0),
                      child: Icon(Icons.camera),
                    ),
                    Text(
                      'Camera',
                    )
                  ],
                ),
              ),
              InkWell(
                onTap: () {
                  _getImagesFromGallery();
                },
                child: Row(
                  children: const [
                    Padding(
                      padding: EdgeInsets.all(8.0),
                      child: Icon(Icons.image),
                    ),
                    Text(
                      'Gallery',
                    )
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

I'm really stuck with this code for few days.
Thank you guys in advance for your help!


text:
Q: Why isn't this PHP mysql_query getting the correct info from my database? I'm relatively new to this, so sorry if I'm posting in the wrong place.
I've got a table in my database which holds 4 things - id, time put in and user and message (for a basic chat-room style thing).
I'm trying to call these using a PHP page. But my page just gets returned blank when I put an argument in the address bar. I'm trying to call it so that only lines with a certain user in the user column get shown. My code is below - can anybody see what I am doing wrong?
The URL of the file is http://freedom-apps.co.uk/chat/messages.php. You see a load of entries - at the start, there is u m u m u m. U represents the user entered, m is the message. So I tried:
http://freedom-apps.co.uk/chat/messages.php?user=u
which returns an error. Any ideas?
My code is:
<?php
header( 'Content-type: text/xml' );
mysql_connect('localhost:/var/lib/mysql/mysql.sock',
              'freedom_ASAPPS', '********');
mysql_select_db( 'freedom_chat_alpha' );
if ( $_REQUEST['user'] ) {
    $user = mysql_escape_string($_REQUEST['user']);
    $result = mysql_query('SELECT * FROM chatitems WHERE user = '$user'
              ORDER BY added LIMIT 50');
} else {
    $result = mysql_query('SELECT * FROM chatitems ORDER BY added LIMIT 50');
}
?>
<chat>
<?php
while ($row = mysql_fetch_assoc($result)) {
?>
<message added="<?php echo( $row['added'] ) ?>"
    id="<?php echo( $row['id'] ) ?>">
    <user><?php echo( htmlentities( $row['user'] ) ) ?></user>
    <text><?php echo( htmlentities( $row['message'] ) ) ?></text>
</message>
<?php
}
var_dump($result);
mysql_free_result($result);
?>
</chat>

I believe it is something wrong with line 6 and 7, or in the way I call the php page with the argument (see above).  I've being referring to the book I have used to learn this stuff, and still can't figure it out (Learning PHP, MySQL, and JavaScript: A Step-by-Step Guide to Creating Dynamic Websites).
Thanks,
Sam

A: $result = mysql_query('SELECT * FROM chatitems WHERE user = '$user' ORDER BY added LIMIT 50');

This is a syntax error - you're missing the string concatenation operators:
$result = mysql_query('SELECT * FROM chatitems WHERE user = ' . $user . ' ORDER BY added LIMIT 50');
                                                            ^^^------^^^^--- here

Alternatively, use double-quoted strings:
$result = mysql_query("SELECT * FROM chatitems WHERE user = '$user' ORDER BY added LIMIT 50");

Getting a blank page suggests you've got display_errors turned off in php.ini. You should turn that on while debugging/developing. You're just shooting yourself in the foot hiding the very messages that would have told you what the problem was.


text:
Q: Submit when I press enter issue, html form I made a simple form in html with angular and bootstrap. My problem is that when I press enter in an input, it calls my submit method from ng-click.
<form id="detaliiCursa" class="form-horizontal">

 Detaliile cursei

    Sursa:

      <input id="sourcePoint" type="text" class="form-control" name="sourcePoint" ng-model="detaliiCursa.sursa"/>

    Destinatie:

      <input id="destinationPoint" type="text" class="form-control" name="destinationPoint" ng-model="detaliiCursa.destinatie"/>

      <button type="submit" class="btn btn-primary" name="submit" value="submit" ng-click="submit()">Submit</button>

</form>

Do you know how can I call "submit()" only when I press Submit button?
Thanks.

A: You could change your button type from submit to button. While input type is submit it tries to submit a form on enter click of any input element of the form.
HTML

    <button type="button" class="btn btn-primary" name="submit" value="submit" ng-click="submit()">Submit</button>

Working Plunkr


text:
Q: Flatten / collapse one-to-many table and keep the 'many' attributes separate I have a data set that contains intersection data.  Each intersection node has up to 6 links which is identified by IN_LINK and OUT_LINK attributes.  I want to create a new dataset that includes the intersection node value (NODE) and all of its accompanying links as a single record.
[NODE] [LINK_1] [LINK_2] etc...
 5465    45687    9831    etc...
How would I code this in python?

A: From your screenshot I see you are using ArcGIS. I do not know if you have the required Info/Advanced license, but there is a Pivot Table tool that may do what you want. It can flatten one-to-many relationships in a table, and unlike the two related questions below, it actually creates new attribute fields for each of the values instead of writing them all to a single field. There are Python code samples, including stand-alone script, at the linked help page.
If you don't have access to the Pivot Table tool, or want to do it without relying on that, there are two questions with slightly different approach answers that partially solve the problem already here on GIS.SE:

*

*Collapsing multi-row output of one-to-many spatial join to single-row in ArcPy?

*Summary table with a field that shows components of each summarized record
Both provide code/script solutions, but both also write the values to a single field. If you want separate attributes, you would have to add some code that would then add the necessary number of new fields and split the values from the single field to their individual ones.


text:
Q: Passing useState function as prop to another component Im trying to pass a useState function to another prop, but i get the following error:
Uncaught RangeError: Maximum call stack size exceeded
I added the useState function as a handleevent for a buttonClick in the child component, and im assuming that error means it gets called in a loop? Can anyone help me understand the issue here? The code is as follows:
    function App() {
        const[personListe, setPersonListe] = useState([
          {
            firstName:'Test',
            lastName:'testing',
            getFullName:function()
            {
                return `${this.firstName} ${this.lastName}`
            },
            age:28
            },
        ]);

      return (<>

Welcome to my react page!

          <Inputfields personListe={personListe} addPerson={setPersonListe} />
          <PersonList personListe={personListe}/>
        </>
      );
    }

Child component(Inputfields.js):
export default function Inputfields({personListe}, {addPerson})
{
    function addPerson()
    {
        let firstName = document.getElementById("firstNameID");
        let lastName = document.getElementById("lastNameID");
        let age = document.getElementById("ageID");
        if(firstName.value.length < 1 || lastName.value.length < 1 || age.value.length < 1)
        {
            alert("Please fill out all the fields!");
        }
        else
        {
            addPerson(
                {
                    firstName:firstName.value,
                    lastName:lastName.value,
                    age:age.value
                }
            );
            firstName.value = "";
            lastName.value = "";
            age.value = "";

        }
    }
    return(
        <>
            <Input id="firstNameID" placeholder="First name" />

            <Input id="lastNameID" placeholder="Last name" />

            <Input id="ageID" placeholder="Age" type="number" />

            <Button variant="contained" sx={{marginTop:2}} onClick={addPerson}>Add person</Button>
        </>
    );
}

A: There are two issues here.  First, you're not destructuring the props correctly.  There is one props object passed to the component, not two.  Destructure the two props from that one object:
export default function Inputfields({personListe, addPerson})

Second, and much more importantly... You never use the addPerson prop being passed here.  The very first thing your component does is shadow that variable with a new function of the same name:
function addPerson()
{
  //...
}

Then that function recursively calls itself until the stack overflows.
Don't shadow the variable.  Give the function its own name.  For example:
function myAddPerson()
{
  //...
}

Then within that function you can call the addPerson which was passed to the component.  In the JSX markup call your local function:
<Button variant="contained" sx={{marginTop:2}} onClick={myAddPerson}>Add person</Button>

Basically this isn't a React issue at all.  This is plain JavaScript.  If you assign a new value to a variable (and defining a function by the same name does exactly that) then the original value is lost.

A: you didn't destruct the props function properly you need to do it like that.
export default function Inputfields({personListe,addPerson}) {...rest of your code}


text:
Q: Custom swing component - Turning a node into text I'm writing a custom swing component (something completely new, but think JTree or JList). I'm trying to follow the general design of JTree, JTable, JList etc for consistency (I've also seen various poor 3rd party components abandon the separable model and/or renderer approach).
So, I have a model full of nodes, the component itself and a renderer. At some point the node has to be turned into text and displayed by a renderer. I'm not clear on the best way to do this:

*

*Pass the node itself (as Object) to the renderer, and let the renderer decide how to display it.

*

*This is how JList does it.

*Requires a customised renderer just to change the text.

*Allows great flexibility in how to display the node (doesn't even have to be text).

*Pass the node itself (as Object) to the renderer, but have a convertValueToText() method in the component class.

*

*This is how JTree does it.

*Renderers can be just as flexibile as before - don't have to use this method.

*Have to override component to change the text transformation.

*As above, but delegate convertValueTotext() to the model.

*

*This is how JXTable does it.

*The model is probably the best place for this method - and it's easier to override there.

I don't want to have to customise the renderer just to change the text, but I'd like to be able to customise the renderer to do more than display a model-displayed string (else why bother with renderers). I really don't like the fact that JXTable uses reflection to look for convertValueToText() in the model - this smells of bad magic to me.
Can anyone shed any light on this oft-neglected part of Swing?
SOLUTION
What I ended up doing was this:

*

*Add a method to the model which returns a string for the given node. Importantly, this can be null to indicate that the renderer should know what to do or that we simply can't provide anything useful.

*The component has the same method, and passes the call on to the model. This is important for view-model separation. The renderer calls this method, so it doesn't talk to the model directly.

*The default renderer calls the above method and if it's not null, it uses it, otherwise it can call toString on the value, or provide a default, or whatever.

This leaves developers a choice when they want to override the displayed value
  - Override the method with a non-null return value knowing that the default renderer will display this text.
  - Provide a custom renderer which is passed the actual node object so it can do "clever" things if it needs to.
I'm quite happy with it - it "feels" right, it works, and it's easy to use.
Thanks for your perspectives!

A: Good question. This is not specific to Swing, but a philosophical question about the difference between a model and a view.
In general, is converting objects into text the job of the model or the view? My purist head says that actually you want a hierarchy of views - one to convert object model to text, and one to display the text. You might even want more than two - for instance, object-to-text, text-to-document-structure, document-structure-to-HTML, and then CSS to present to the user.
However, pragmatism says this may get too hard to remember and maintain. So in your circumstance I would suggest: think about how likely it is you'll ever want to extract non-text data from the model. If it is not very likely, then put the equivalent of convertValueToText in the model.
Otherwise, allow the component to either use a renderer, if it is given one, or else take the object value and convert it to text internally.
This allows maximum flexibility and probably makes things feel most natural to the users of the API. I believe this is the JTable model though I haven't used Swing for a long time.

A: AFAIK neither JList nor JTree require the renderer to render text. The renderer gets passed the data object and return a JComponent which gets positioned as a child in Tree/List itself and then rendered.
I would go with this. A renderer for text would simply return a JLabel. If you want to be able to change the way, the text is constructed pass a Formatter to the TextRender, and you are done.

*

*Stephan

A: If you had to write your own component do it as simple as possible. In a lot of cases if you need a custom renderer then you don't care about interpretation by component or model. Model holds your data. And in this case is also custom written. From my point of view the good choice is based on first option. Provide DefaultRenderer which implements AbstractRenderer and add there all methods like toText(Object o) and so on. Then allow me to decide whether I want to use default functionality or I prefer to wrote my own. Do you really need custom component? To make it works correctly it is a LOT of work. Is this component worth all this?


text:
Q: Question about Eigen::MatrixXd column-wise calculation Is there anyway to apply the column-wise calculation as follows?
(each column divided by the last entry of the column)
Eigen::MatrixXd A(3,5), B(3,5);

A << 1, 4, 9, 16, 25,
     2, 4, 6, 8, 10,
     1, 2, 3, 4, 5;

B = (A.col) / (A.bottomerows<1>).col;

and B would be:
B = 1, 2, 3, 4, 5,
    2, 2, 2, 2, 2,
    1, 1, 1, 1, 1;

A: The functions you are looking for are .hnormalized() and .homogeneous(). Both can be applied .colwise() like this:
Eigen::MatrixXd B = A.colwise().hnormalized().colwise().homogeneous();

You can achieve the same with some .replicate() magic like this:
Eigen::MatrixXd B = A.array() / A.row(2).replicate(A.rows(),1).array();

(if A was an ArrayXXd, instead of a MatrixXd, you don't need to write the .array())


text:
Q: Reloading Page Shows 404 error message after Enabling AngularJS HTML5 mode I have enabled HTML5 mode for my app. I have put the following code for the configuration, as shown below
return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {

$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';

$routeProvider.when('/', {
    templateUrl: '/pages/index.html',
    controller: 'indexCtrl'
});
$routeProvider.when('/about',{
    templateUrl: '/pages/about.html',
    controller: 'AboutCtrl'
});

Also I have done some changes in .htaccess file as below
RewriteEngine On
Options FollowSymLinks

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

Also I have done some changes in index.html also liek
<base href="/">

A: Did you set a
<base href="">

tag inside your head tag?
$location Relative Links


text:
Q: Get number of idle CPU counts in python windows In multi-threading programming, wanted to start threads only according to number to idle CPUs available.
How can I get number of idle CPUs in python windows.
In linux
import os
os.getloadavg()

seems helpful.
Is that anyway to get in python on windows env ?
Thanks in advance.

A: This works for python with a version >= 2.6
import multiprocessing

multiprocessing.cpu_count()

http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count


text:
Q: How to create a Biztalk Map that transforms hierarchical XML to flat file I try to transform a hierarchical XML file to a flat file schema using Biztalk 2010.
It works fine. Every file is mapped. But the hierarchy is destroyed.
My input xml structure looks like this:
<root>
    <node>
        <element1></element1>
        <element2></element2>
        <subnode1>
            <element1></element1>
            <element2></element2>
        </subnode1>
        <subnode2>
            <element1></element1>
            <element2></element2>
        </subnode2>
    </node>
</root>

The flat file schema looks like this:
<root>
    <node>
        <element1></element1>
        <element2></element2>
    </node>
    <subnode1>
        <element1></element1>
        <element2></element2>
    </subnode1>
    <subnode2>
        <element1></element1>
        <element2></element2>
    </subnode2>
</root>

My input is like this:
<root>
    <node>
        <element1>Test1</element1>
        <element2>Test2</element2>
        <subnode1>
            <element1>Sub11</element1>
            <element2>Sub12</element2>
        </subnode1>
        <subnode2>
            <element1>Sub21</element1>
            <element2>Sub22</element2>
        </subnode2>
    </node>
    <node>
        <element1>Test3</element1>
        <element2>Test4</element2>
        <subnode1>
            <element1>Sub31</element1>
            <element2>Sub32</element2>
        </subnode1>
        <subnode2>
            <element1>Sub41</element1>
            <element2>Sub42</element2>
        </subnode2>
    </node>
</root>

What I expect as output is:
Test1;Test2
Sub11;Sub12
Sub21;Sub22
Test3;Test4
Sub31;Sub32
Sub41;Sub42

But what I get is:
Test1;Test2
Test3;Test4
Sub11;Sub12
Sub21;Sub22
Sub31;Sub32
Sub41;Sub42

Any ideas how I can make Biztalk keep the hierarchy?

A: I don't have the BizTalk Mapper at hand right now so I only can provide a Xslt solution but basically it will illustrate that you need your map to iterate over your node elements to preserve the structure.
If you want to achieve this using pure BizTalk Mapping you need a grouping node in your flat output structure to connect your source node element to which will force the map to create the for-each loop like in the following Xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:output method="text" indent="no" />

    <xsl:template match="/">
        <xsl:for-each select="root/node">
            <xsl:value-of select="element1" />
            <xsl:text>;</xsl:text>
            <xsl:value-of select="element2" />
            <xsl:text>
</xsl:text>
            <xsl:value-of select="subnode1/element1" />
            <xsl:text>;</xsl:text>
            <xsl:value-of select="subnode1/element2" />
            <xsl:text>
</xsl:text>
            <xsl:value-of select="subnode2/element1" />
            <xsl:text>;</xsl:text>
            <xsl:value-of select="subnode2/element2" />
            <xsl:text>
</xsl:text>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

You may need to adjust the line breaks (
) to your output schema needs.


text:
Q: Changing installation type with VS 2013 project installer extension I made a C# winform app in VS 2013, I used the project installer extension to build an installer.
Everything works fine, the installer builds successfully and the program installs successfully.
The problem is that the program will not run unless I first right click the program's icon and check the "run as administrator" box, which is really not needed given the scope of the app (a mailing app with html templates and a simple SQLite DB).
I was able to use Advanced Installer and it made it very easy to change the installation type to "per-user only" rather than "requires admin rights".
But I set myself on figuring how to do it with the VS project installer extension and have had no luck so far.
Would anyone be so kind as to point out how I can change the installation type using the VS project installer extension?
EDIT
Here is the output log from building the installer:
1>------ Build started: Project: HolidayMailer, Configuration: Debug x86 ------
1>  HolidayMailer -> C:\Users\SAMI\Documents\GitHub\bitsbeflippin-holiday-mailer\HolidayMailer\HolidayMailer\bin\x86\Debug\HolidayMailer.exe
------ Starting pre-build validation for project 'HolidayMailerInstaller' ------
------ Starting pre-build validation for project 'HolidayMailerInstaller' ------
------ Pre-build validation for project 'HolidayMailerInstaller' completed ------
------ Pre-build validation for project 'HolidayMailerInstaller' completed ------
2>------ Build started: Project: HolidayMailerInstaller, Configuration: Debug ------
2>------ Build started: Project: HolidayMailerInstaller, Configuration: Debug ------
Building file 'C:\Users\SAMI\Documents\GitHub\bitsbeflippin-holiday-    mailer\HolidayMailer\HolidayMailerInstaller\Debug\HolidayMailerInstaller.msi'...
Building file 'C:\Users\SAMI\Documents\GitHub\bitsbeflippin-holiday- mailer\HolidayMailer\HolidayMailerInstaller\Debug\HolidayMailerInstaller.msi'...
Packaging file 'HolidayMailer.exe'...
Packaging file 'HolidayMailer.exe'...
Packaging file 'System.Data.SQLite.EF6.dll'...
Packaging file 'System.Data.SQLite.EF6.dll'...
Packaging file 'System.Data.SQLite.dll'...
Packaging file 'System.Data.SQLite.dll'...
Packaging file 'EntityFramework.dll'...
Packaging file 'EntityFramework.dll'...
Packaging file 'System.Data.SQLite.Linq.dll'...
Packaging file 'System.Data.SQLite.Linq.dll'...
Packaging file 'HolidayMailer.exe.config'...
Packaging file 'HolidayMailer.exe.config'...

A: Are you using the Advanced Installer VS extension? If so, you can just hit the button "Edit in Advanced Installer" from the upper side of the project view, and make the change you want the IDE of Advanced Installer, as not all options are available in the VS extension.


text:
Q: Disabling All Next Form input field if currnt input has an error or warning I am using a registration form where the user details are checked on keyup event. I would like to disable all the next input field if the current input has an error. I noted that if a user fill incorrect data and start filling the next field. The error is no longer shown. I am using keyup to check the user data. Or you can suggest a way I can keep showing the user that there is an error in specific input fields even if he has started filling another input. This is my jquery code
 var spaceReg=/\s/;
 var onlylettersReg=/^[A-Za-z]+$/i;
 var lowUpperCaseReg=/(?=.*[a-z])(?=.*[A-Z])/;
 var symbolsCheckReg=/[-!$%^&*(){}<>[\]'" . '"|#@:;.,?+=_\/\~]/;
 var noCheckReg=/\d/;
 var timerId=0;
 clearTimeout (timerId);

$("form input[type=text],form input[type=password]").on("keyup",function(event){
    timerId=setTimeout(function(){
    $('.form_error,.form_warning,.form_warning').fadeOut(3000);
    $('.error_indicator img,.success_indicator img,.warning_indicator img').fadeOut(3000);
    },1000 );
});

 $("#firstname").on("keyup",function(event){

  timerId= setTimeout(function(){
 var dataValid = true;
 var firstname= $('#firstname').val();
  if( firstname === "" ) //Validation against empty field for fullname
{
              dataValid=false;
$('#firstname_warning').html('');
                $("#firstname_response").html('
Please enter your firstname  in the required field to proceed. Thanks.
');
                }
             else if(onlylettersReg.test(firstname) ===false) //Validation for working email address
{
                dataValid=false;
             $('#firstname_error').html('');

$("#firstname_response").html('
Sorry, your name should contain  only letters. Thanks.
');
$("#firstname").focus();
}
              else if(firstname.length>15) //Validation for working email address
{
                 dataValid=false;
               $('#firstname_error').html('');
$("#firstname_response").html('
Sorry, your name should have max of 15 characters. Thanks.
');
$("#firstname").focus();
}

              if(dataValid===true){
                      $('#firstname_success').html('').fadeIn(3000);
               }else{
                     $('#firstname_success').html('').hide();
               }
    },2000);
});

$("#lastname").on(" keyup",function(event){
   var dataValid=true;
 timerId= setTimeout(function(){
 var lastname= $('#lastname').val();

        if( lastname=== "" ) //Validation against empty field for telephone number
{
             dataValid=false;
             $('#lastname_warning').html('');

$("#lastname_response").html('
Please enter your last name in the required field to proceed. Thanks.
');
$("#lastname").focus();
}
             else if(lastname.length>15) //Validation for working email address
{
              dataValid=false;
              $('#lastname_error').html('');

$("#lastname_response").html('
Sorry, your name should have max of 15 characters. Thanks.
');
$("#lastname").focus();
}
             else if(onlylettersReg.test(lastname) ===false) //Validation for working email address
{
              dataValid=false;
               $('#lastname_error').html('');

$("#lastname_response").html('
Sorry, your name should contain  only letters. Thanks.
');
$("#lastname").focus();
    }
             if(dataValid===true){
                       $('#lastname_success').html('').fadeIn(3000);
               }else{
                     $('#lastname_success').html('').hide();
                     $(this).nextAll().hide();
               }
  },2000);

});

This is my form

<form action="" method="post" id="" autocomplete="off">

First Name:

<input name="firstName" type="text" id="firstname" autocomplete="off"
      value=""/>

Last Name:

<input name="lastName" type="text"  id="lastname" autocomplete="off"
      value=""/>

show me how i can ensure that if an error or warnin is continuously show even if the user focus in the next fields and will not be able to sumbit data
Thank you

A:
No Problem with Your code Dude...
    You need Little changes.
    Change dataValid variable as a global variable and set as true and check in each validation

Revised Code
var spaceReg=/\s/;

var onlylettersReg=/^[A-Za-z]+$/i;
 var lowUpperCaseReg=/(?=.*[a-z])(?=.*[A-Z])/;
 var symbolsCheckReg=/[-!$%^&*(){}<>[\]'" . '"|#@:;.,?+=_\/\~]/;
 var noCheckReg=/\d/;
 var timerId=0;
var dataValid = true;
 clearTimeout (timerId);

$("form input[type=text],form input[type=password]").on("keyup",function(event){
    timerId=setTimeout(function(){
    $('.form_error,.form_warning,.form_warning').fadeOut(3000);
    $('.error_indicator img,.success_indicator img,.warning_indicator img').fadeOut(3000);
    },1000 );
});

 $("#firstname").on("keyup",function(event){

  timerId= setTimeout(function(){
// var dataValid = true;
 var firstname= $('#firstname').val();
  if( firstname === "" ) //Validation against empty field for fullname
{
              dataValid=false;
$('#firstname_warning').html('');
                $("#firstname_response").html('
Please enter your firstname  in the required field to proceed. Thanks.
');
                }
             else if(onlylettersReg.test(firstname) ===false) //Validation for working email address
{
                dataValid=false;
             $('#firstname_error').html('');

$("#firstname_response").html('
Sorry, your name should contain  only letters. Thanks.
');
$("#firstname").focus();
}
              else if(firstname.length>15) //Validation for working email address
{
                 dataValid=false;
               $('#firstname_error').html('');
$("#firstname_response").html('
Sorry, your name should have max of 15 characters. Thanks.
');
$("#firstname").focus();
}

              if(dataValid===true){
                      $('#firstname_success').html('').fadeIn(3000);
               }else{
                     $('#firstname_success').html('').hide();
               }
    },2000);
});

$("#lastname").on(" keyup",function(event){
  // var dataValid=true;
 timerId= setTimeout(function(){
 var lastname= $('#lastname').val();
       if(dataValid == true) /* Checking for errors.. Enters if there is NO errors*/
   {
        if( lastname=== "" ) //Validation against empty field for telephone number
  {
             dataValid=false;
             $('#lastname_warning').html('');

$("#lastname_response").html('
Please enter your last name in the required field to proceed. Thanks.
');
$("#lastname").focus();
}
             else if(lastname.length>15) //Validation for working email address
{
              dataValid=false;
              $('#lastname_error').html('');

$("#lastname_response").html('
Sorry, your name should have max of 15 characters. Thanks.
');
$("#lastname").focus();
}
             else if(onlylettersReg.test(lastname) ===false) //Validation for working email address
{
              dataValid=false;
               $('#lastname_error').html('');

$("#lastname_response").html('
Sorry, your name should contain  only letters. Thanks.
');
$("#lastname").focus();
    }
             if(dataValid===true){
                       $('#lastname_success').html('').fadeIn(3000);
               }else{
                     $('#lastname_success').html('').hide();
                     $(this).nextAll().hide();
               }
  }
  },2000);

});

U can Use Validate Plugin for simpler validation


text:
Q: Disable/enable a JSF input component depending on value of another input component I have two radio buttons:
<h:selectOneRadio value="#{bean.choice}">
    <f:selectItem itemValue="yes" itemLabel="YES" />
    <f:selectItem itemValue="no" itemLabel="NO" />
</h:selectOneRadio>

<p:calendar value="#{bean.date}" />

If the "no" button is selected, the text input field of the calendar should be disabled (greyed out). How can I do this?

A: You can have method in your myBean which is a valueChangeListener event.
   private boolean caldisabled;  // with getter and setter

   public void checkSelectedVal(ValueChangeEvent event){

      String selectedVal=event.getNewValue().toString();
      if("NO".equalsIgnoreCase(selectedVal)){
         caldisabled=true;
      } else if("YES".equalsIgnoreCase(selectedVal)){
        caldisabled=false;
      }
}

And in your view in primefaces calendar component set disabled attribute
<h:selectOneRadio value="#{myBean.yesNo}" valueChangeListener="#{mybean.checkSelectedVal}">
    <f:selectItem itemValue="yes" itemLabel="YES" />
    <f:selectItem itemValue="no" itemLabel="NO" />
    <f:ajax event="click" execute="@this" render="mycal"/>
</h:selectOneRadio>

<p:calendar id="mycal" value="#{myBean.date}" disabled="#{myBean.caldisabled}"/>

And there should be another way to do this. I think as this calendar component is Jquery datepicker you should be able to do it using scripting alone with no need to go to bean and make ajax call

A: Just let the target input component's disabled attribute check the value of the source input and use <f:ajax> in the source component to update the target component. It will cause the disabled attribute to be re-evaluated. No need for a value change listener nor an additional property.
<h:selectOneRadio value="#{bean.choice}">
    <f:selectItem itemValue="yes" itemLabel="YES" />
    <f:selectItem itemValue="no" itemLabel="NO" />
    <f:ajax render="calendar" />
</h:selectOneRadio>

<p:calendar id="calendar" value="#{bean.date}" disabled="#{bean.choice eq 'no'}" />

See also:

*

*Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

*When to use valueChangeListener or f:ajax listener?

A: For me this last solution works fine, but I had to change the event from event="click" to event="change".


text:
Q: Rest API of neteller show invalid client Error $username = 'MerchantXYZ';
$password = 'B81dff9bb4020a89e8ac44cdfdcecd702151182fdc952272661d290ab2e5849e31bb03deede';
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, "https://api.neteller.com/v1/oauth2/token?grant_type=client_credentials");
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Cache-Control:no-cache"));
curl_setopt($curl, CURLOPT_POSTFIELDS, array("scope"=>"default"));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$serverOutput = curl_exec($curl);
echo $serverOutput;

I am using this code but every time show me { "error": "invalid_client" } this message. I have checked my API and IP address, everything is perfect.

A: There are 4 reasons why you may get { "error": "invalid_client" } when trying to get a token.

*

*You are using client_id + client_secret from your test account on the production environment or vice versa.

*Your client_id or client_secret values are wrong.

*The IP address from which your application is making outgoing requests is not white-listed in your merchant account.

*You are not sending the Authorization header properly.

Check points 1) - 3); From your example I can see you can rule out point 4) as a possible reason.
Also, you don't need this line:
curl_setopt($curl, CURLOPT_POSTFIELDS, array("scope"=>"default"));

According to the documentation you shouldn't post anything in the body of the request when getting a token. Where did you get this example from?


text:
Q: How can I programmatically limit the execution of a Play 2.4 module to a single host? Just to give some background, I have a Play 2.4 application which uses Scala 2.11.8.

I deploy it to an AWS stack using OpsWorks which has 2 available instances. In the application have a module which uses an ActorSystem scheduler to periodically execute a method to do some cleanup operation. When running one instance of the app locally the cleanup works fine, but once the app is deployed the cleanup is unnecessarily run on every instance.
My question is not specific to the stack I am using, but rather a high-level approach to programmatically limit an operation to a single instance once the app is deployed. For the purpose of this question, assume I do not have access to the stack configuration.

I've searched for similar questions on S.O. but can't seem to find this particular issue. I also don't want to hardcode hostnames because that isn't a reliable solution.

A: Here is a suggestion that you could possible do:

*

*Containerise your application using Docker

*Use an orchestrator like Kubernetes or Docker Swarm

*Set up service discovery for your application server (Your play application in this case)

*Set up a Load Balancer that fronts your application server

*By sending a HTTP request to your server (your Load Balancer), it is guaranteed that the request lands in just one instance of your application server which will then perform the needed clean up job.


text:
Q: Show that the function is positive
Let $f:\mathbb R\to\mathbb R$ be a Lipschitz continuous, monotone increasing function, with $f(0)=0$, if a function $\phi$ satisfies;
$\displaystyle\cases{
\phi'(t)=f(-\phi(t))-f(\phi(t))  & \cr
\phi(0)=1
}$,
why must be $\phi(t)>0$ $\forall t\in\mathbb R\ ?$

Actually this is not the exercise, only a part of it, which I don't understand, any help is appreciated.

A: The function $G\colon \mathbb{R}\to \mathbb{R};\; G(u) = f(-u) - f(u)$ is Lipschitz continuous with $G(0) = 0$.
So the solutions to the differential equation
$$y' = G(y)\tag{$\ast$}$$
to a given initial condition are unique by the Picard-Lindelöf theorem. It is easily verified that $\psi(t) = 0$ is a solution of $(\ast)$ for the initial condition $y(t_0) = 0$. Hence any solution of $(\ast)$ that is nonzero at some point $t_0\in\mathbb{R}$ is nonzero on its complete domain of existence [which is $\mathbb{R}$, again by Picard-Lindelöf].
The given $\phi$ is positive at $t_0 = 0$ by the initial condition, it is a solution of $(\ast)$ by assumption, hence it is positive on all of $\mathbb{R}$ by the uniqueness of solutions.


text:
Q: Need help for troubleshooting/diagnostic Sitecore Website Few days we stuck in different problem after code drop. Everything was fine earlier but after code drop Memory and CPU uses are approx 100% and even website was not stable. It was throwing errors 'Value cannot be null'. But Sitecore admin interface was always accessible and we can preview website from Master Database.
We did publish (Republish  Site/Nodes, Smart publish, incremental publish also) but cannot figure out problem. Could you please help, how could we troubleshoot in such situation?

A: If preview is working and the main website is not, you likely have content items (either templates, sublayouts, or fields) that are not in a publishable state.
If you still have the package you used to install your update, it should have the content items that were added, which would help you track down which items to check for.
Additionally, you can write code to crawl your Templates tree and find any items that are not in the final state of workflow.

A: Thanks all for your providing help.
We solved this issue while analyzing root cause.
Sitecore was running agents after certain time interval and it was failing to complete it because on dependency on another thing. So at last all thing mess with creating a dead end loop. Which was eating all CPU memories. So it was not communicating well with database servers to get data.
After resetting IIS, all jobs are ended for a while and it works after same dead loop.


text:
Q: Подтянуть url фотографии объекта с Yandex maps Как получить url фотографии объекта в ответ на запрос с координатами или адресом объекта?

A: API Яндекс.Карт ограниченно работает с данными организаций и может показать по координатам лишь панорамы. Возможности получить ссылки на отдельные фотографии нет.
Большая часть фотографий привязана к конкретным организациям. Открыть их альбом несложно, используя ссылку вида https://yandex.ru/maps/org/1671141286/gallery/ Но даже в метаданных организаций нет информации о привязанных снимках.


text: Q: Drawing a compound image from smaller images I want to draw an image on canvas constituted from smaller images, and make the new compound image scroll-able both horizontally and vertically as well as enable zoom-in, zoom-out and pan functionality. Any suggestions as to which View (container) I should use?


text:
Q: Beta testing and in-app purchase We are using TestFlight for beta testing and we have an IAP store in our app.
Will the Beta Testers be able to buy the packages from the sandbox environment?
How can we test this?

A: If the Beta Testers have a proper development provisioning profile installed on their device, then yes.
For development versions of the app, the app will run in the Sandbox environment for IAPS, Game Center,.. and the beta testers will be able to buy the in-app purchase by logging in as a test user associated with the iTunes Connect account(which you need to create first under the "Users - Test Users" tab within iTunes Connect).


text:
Q: Xcode 9.2 is re-indexing from scratch each time I open it, even if nothing changed I have a project (big project), that takes about 30 minutes to be indexed by Xcode. Xcode consumes 100% of my CPU for 30mn.
OK why not, that sounds a bit rude to use 100% of the CPU for a background task, but why not.
Now, if after 30 minutes, I quit Xcode, and re-open it, without touching a single file of my project, it starts again to index for 30 minutes.
Is this the intended behaviour? Is there a way to fix it? I don't want to turn off inedxing, I tried it, and code completion is HS.

A: Try adding this flag to your build settings.
Xfrontend -warn-long-expression-type-checking=400

It will cause warning where the compiler take a long time to deduce a complex expression.

This may cause a build error which will go away after you find the slow expressions and then remove the build flag.


text:
Q: httpclient.execute(httpget) Doesn't seem to work (Android) I'm trying to get a daily quote from

http://quotesondesign.com/api/3.0/api-3.0.json?callback=json

I call this method in my onCreate
But when i try to execute the httpclient.execute();
it escapes to the catch statement...
What am I doing wrong?
I did include the <uses-permission android:name="android.permission.INTERNET" />
in my manifest file.
public String getJson(){
        String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(quoteUrl);

        httpget.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        String aJsonString = null;
        try {
            HttpResponse response = httpclient.execute(httpget);
            Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();
            JSONObject jObject = new JSONObject(result);
            aJsonString = jObject.getString("quote");

        } catch (Exception e) {
            //Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }

        return aJsonString;
    }

EDIT: here is the onCreate()
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //verbergt notificatiebalk
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.splash);

    jsonstring = getJson();
    Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
    //Toast.makeText(this, jsonstring, Toast.LENGTH_LONG).show();
    //tot hier testen
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);

            finish();
        }
    }, SPLASH_TIME_OUT);
}

Thank you in advance!

A: In your code you have
String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";

While the URL you want to fetch is
http://quotesondesign.com/api/3.0/api-3.0.json?callback=json

Notice how in your code you have callback=? while the URL has callback=json.

A: After Android 4.2, you can't make Http Request on the UI-Thread (the "main" thread). You need to do it in a seperate thread.
You can find an example on this website or in this stackoverflow post: HttpClient.execute(HttpPost) on Android 4.2 error

A: Update: Actual answer with code now vailable:
private class AsyncQuoteDownload extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        String jsonData = getJson(); //or, if the jsonData var is available from everywhere, just put myR.run(); here, return null, and append the data directly in onPostExecute
        return jsonData;
    }

    @Override
    protected void onPostExecute(String result) {
        (TextView)findViewById(R.id.Quote).append(result).append("\"");
    } //  \" makes it put an actual " inside a string
}

Old answer:
I bet your stacktrace (which isn't as an error because oyu catch it, but it's in the log) reads something like "Network on Main Thread"?
Because that's something you're trying to do, and that's something you aren't allowed to do. Instead, put it in an AsyncTask:
onCreate(){ //beware pseudo code because it doesn't matter
    //do stuff
    setContentView(...); //Above here, everything stays as is.
    //below here, only that:
    new GetQuoteTask.execute();
}

class GetQuoteTask extends AsyncTask<Void, Void, String>{
    String doInBackground(...){ //<- pseudo code, code completion is your friend
        String result = getJson();
        Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
        return result;
    }
    onPostExecute(String result){
        maybePutYourStringSomewhereAKAUpdateUI();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}


text:
Q: Exiting PCL viewer: wasStopped() not changing value even though window was closed I've been trying to use the PCL Visualizer according to this tutorial on the PCL website and am using the following methods to visualize a point cloud:
boost::shared_ptr<pcl::visualization::PCLVisualizer> createViewer (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud, std::string& viewerName)
{
    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer (viewerName));

    viewer->setBackgroundColor (0, 0, 0);
    viewer->addPointCloud<pcl::PointXYZ> (cloud, viewerName);
    viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, viewerName);
    viewer->addCoordinateSystem (1.0);
    viewer->initCameraParameters ();

    return viewer;
}

void visualizePointCloud (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
    std::string viewerName = "3D Viewer: Cloud";

    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
    viewer = createViewer(cloud, viewerName);

    while (!viewer->wasStopped())
    {
        viewer->spinOnce(100);
        boost::this_thread::sleep (boost::posix_time::microseconds (100000));
    }
}

Everything visualizes fine, but I can't seem to get out of the loop!
If you close the viewer window by clicking the "x", nothing happens, wasStopped() still returns false, and the program is stuck.
Anybody know how to terminate the viewer properly so the program can go on with the rest of the code? Am I just being stupid?
Many thanks in advance!
P.S.: I´m on Mac OS 10.13.6 with PCL 1.8.1 (installed via Homebrew).

A: I'm a bit embarrased, but the answer is really simple... accicentally stumbled onto it after trying Flumenque's solution... As it turns out everything was working like it should, I was just too simple to realize it:
The viewer can be terminated with a press of "q" on the keyboard. However, you have to click inside the visualization area first, even if the window already has the focus!
Thought I'd write it up just in case somebody else matches my stupidity... ;)

A: You can close an open viewer at any time with the method
viewer->close();

I guess it was added in PCL 1.6: http://www.pcl-users.org/How-to-close-the-window-of-a-PCLViewer-and-how-to-make-it-stop-by-code-td3824712.html


text:
Q: c++ vector with struct to map? I have a vector with this struct:
struct AB
{
      int id, x, y;
}

x and y are coordinates.
The data in the vector looks like this:

*

*id 22   x 53.2    y 8.90

*id 22   x 53.3    y 8.91

*id 25   x 53.4    y 8.92 ...

You can see that some id's contain more than one coordinate. Therefore, I am looking for a way to save the data in a different form. Which is more suitable to work with the data further. Has anyone a tip?

A: It all depends on how do you fill and use the data. If there is one-time load of all the data just at the beginning and then only using the loaded data, it could be actually beneficial to keep the vector, load all the data, sort it once according to the ids and then use the sorted vector - because of the contiguous block which has better locality and thus much better cache behavior (contrary to the ordered or unordered map structures that imply chasing pointers all around the place, which is not very cache friendly). This can also work if the new items are only added rarely. Note that this would have the same big-O as having a balanced tree-based map (if you'll do binary search in the sorted vector), as long as new items do not need to be added after the sorting.
If the new items are added frequently, you can use std::multimap (or unordered which works based on hashes), or map/unordered_map of vectors of points.
The decision which one is better for you should be based on measurements of current speed and the speed after the change (you generally don't want the "improved" version to be slower than the original one).


text:
Q: Calculate a column of times to find the difference against a static time In Excel, how can I calculate a column time differences from a static time?
Example shown below. I want to know how many minutes past 08:00 AM the value in each row is.
Desired result:
Column A, input      | Col B, Difference in minutes compared to 08:00 AM
                     |
1/11/2016 7:55:00 AM | -5
1/11/2016 7:57:00 AM | -3
1/11/2016 7:57:00 AM | -3
1/11/2016 7:58:00 AM | -2
1/11/2016 7:59:00 AM | -1
1/11/2016 7:59:00 AM | -1
1/11/2016 8:03:00 AM | 3
1/11/2016 8:06:00 AM | 6
1/11/2016 8:15:00 AM | 15
1/11/2016 8:25:00 AM | 25

What is the formula for this?

A: Try this:
=((HOUR(A1)-HOUR(TIME(8,0,0)))*60)+(MINUTE(A1)-MINUTE(TIME(8,0,0)))


text:
Q: Error while using webbrowser So I want to use a webbrowser to show an html file, and print it. I can load the file, but when I try to use webBrowser1.ShowPrintDialog(); I have a script error. I tried to disable this with webBrowser1.ScriptErrorsSuppressed = true; but it doesn't work.
The weird part is that when I run my code in debug(F5), it works, but not in "normal" mode (Ctrl + F5).
My code so far is very simple:
public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("http://google.com");
}

private void button1_Click(object sender, EventArgs e)
{
    webBrowser1.ScriptErrorsSuppressed = true;
    webBrowser1.ShowPrintDialog();
}


text:
Q: What would the best follower be for skyrim? What would be the best follower a Mage like me could have? I have a level 72 nord mage and I play on master difficulty, and I need something that'll keep the random encounters in check. Something strong, but melee, so I can spam the enemy with destruction spells and level up destruction on the go. I don't want the enemy killed too quick. I mainly use destruction (level 63) but I do rely heavily on conjuration (level 100) I have all the perks for conjuration, and decent thralls, but I need someone I don't have to CONSTANTLY resurrect. I currently have the dwarven sphere follower from the dragonborn dlc, and marcurio of riften as a follower, but he kills everything from a distance before I even see it.

A: You're probably best off with an essential follower like Mjoll the Lionness.  She won't ever die, and she wears heavy armor so she'll tank hits for you.  That said, if you don't have the Unofficial Skyrim Patch then J'zargo from the College of Winterhold will keep leveling with you since he doesn't have a cap, so he may end up with more health than even heavy armor class followers (as I recall, he has a thing for wearing armor too).
A full list can be found here: http://www.uesp.net/wiki/Skyrim:Followers, the page mentions that "Seven permanent followers are essential as well: Derkeethus (due to a bug), Mjoll, two Dark Brotherhood Initiates, Cicero, Serana and Frea are essential."  As far as what you are looking for, Frea is also mainly focused on melee, although she uses Light Armor as well as Alteration and Restoration magic.


text:
Q: extract html to a helper method rails I have a helper in my app with this code:
module ApplicationHelper
  def cms(key)
    if Text.find_by_key(key)
      Text.find_by_key(key).content
    else
      nil
    end
  end

  def cms2(key)
    if Text.find_by_key(key)
      Text.find_by_key(key)
    else
      nil
    end
  end
end

and in my view files i have this:
<%if cms('front2')==nil%>
    <%if admin_signed_in?%>
        <%=link_to "create", new_text_path(:key => 'front2')%>
    <%end%>
<%else%>
    <%=raw(cms('front2'))%>
    <%if admin_signed_in?%>
        <%=link_to("Edit", edit_text_path(cms2('front2')), :class=>"editcms")%>
    <%end%>
<%end%>

I want to extract the html portion of this code so i can call a helper like this:
<%= new_method('front2') %>

A: # app/helpers/application_helper.rb
include ActionView::Helpers::UrlHelper
module ApplicationHelper
  def cms(key, admin_signed_in)
    if key.nil?
        if admin_signed_in
            if Text.find_by_key(key)
              link_to 'create', new_text_path(:key => key)
            else
              nil
            end
        end
    else
        text = Text.find_by_key(key).content
        if admin_signed_in
            "#{text} #{link_to('Edit', edit_text_path(cms2(key)), :class => 'editcms')}".html_safe
        else
            text
        end
    end
  end
end

# in your view
<%= cms('front_2') %>


text:
Q: code not working for advent of code 2020 day 2 part 1 my output wasn't the answer and I also had the valids list to check all the valids and I can confirm that my way of checking if something is valid is most definitely wrong, but I don't know how to fix it
the question: https://adventofcode.com/2020/day/2
my output is 450 and this is the puzzle input: https://pastebin.com/MBHaMr7m
#Day 2 part 1
count = 0
valid = 0
#valids = []

with open('inputs\input2.txt') as f:
    data = f.read()
    data = data.replace(" ", "")
    data = data.replace("-", "")
    data = data.replace(":", "")

data = [str(x) for x in data.splitlines()]
data = [list(x) for x in data]

for i in range(len(data)):
    for j in data[i][3:]:
        if data[i][2] == j:
            count += 1

        if count >= int(data[i][0]) and count <= int(data[i][1]):
            valid += 1
            #valids.append(data[i])
            count = 0

        else:
            count = 0

#print(valids)
print(valid)

When I printed valids, the passwords were all invalid, my way of checking if it is correct is most likely wrong and I still can't figure out what is wrong with my code, please help.
(couldnt find a good title for the question btw)

A: You are making invalid assumptions about the input, in particular that each range consists of two single-digit numbers. Try something like
with open(r'inputs\input2.txt') as f:
    for line in f:
        lowhigh, character, password = line.strip().split()
        low, high = lowhigh.split('-')
        low = int(low)
        high = int(high)

        # Now check if <character> occurs between <low> and <high> times in <password>


text:
Q: Find the solution of $(1-x^2)y'' - 2xy' + 14y = 5x^3$ Find the solution of $$(1-x^2)y'' - 2xy' + 14y = 5x^3.$$
There are no answers ( although I could substitute them), so I'd like to know if my general approach is correct:
1) I would find the solution to the homogeneous equation $$(1-x^2)y'' - 2xy' + 14y = 0$$ which has the solution of the Legendre polynomial with l = $\frac12 (-1 + \sqrt{57}).$ So it is a linear combination of the even and odd solutions.
2) For the inhomogenuous solutions, I took linear combinations of $P_1(x)$ and $P_3(x)$, which gives $$C_1(-2 + 14)x + C_2(-6 + 7)(5x^3 -x) = 5x^3$$.
The coefficient of $C_2$ is then $1$ and the coefficient of $C_1$ is $1/12$.
Is the approach correct?


text:
Q: Extending Error gives wrong stack trace information This question is not the same as Extended Errors do not have message or stack trace, which deals with es6 extends, but I'm using es5.
Here's my code
test.js
function FooError(message) {
    this.stack = (new Error(message)).stack;
    console.log('this.stack', this.stack);
    console.log('new_error_stack', (new Error(message)).stack);
    console.log('after');
}
FooError.prototype = new Error;

throw new FooError("foo");

This gives the following output : with node version 6.4 (node test.js)
this.stack Error
    at Object.<anonymous> (/tmp/test.js:7:22)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
new_error_stack Error: foo
    at Error.FooError (/tmp/test.js:4:33)
    at Object.<anonymous> (/tmp/test.js:9:7)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
after

/tmp/test.js:9
throw new FooError("foo");
^
Error
    at Object.<anonymous> (/tmp/test.js:7:22)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

as you can see, the 'this.stack' doesn't show the same thing at all than the 'new_error_stack', eg, the this.stack shows the stack as if the error was thrown when the require was called. Also, the thrown stack is also "incorrect".
I took the code from https://stackoverflow.com/a/5251506/1993501 , and since I want to use instanceof FooError, I use the line FooError.prototype = new Error.
As you can see, the 'new_error_stack' gives the expected output, but I would have expected both values to be equal.
This has the effect that errors are not very useful for users of my library, see corresponding issue : https://github.com/open-xml-templating/docxtemplater/issues/245
What exactly is happening, and how can I prevent it and keep proper error types (eg being able to use instanceof) ?

A: I found a possible solution to your problem, but I'm not entirely sure it fixes all of your issues. I'm using Error.prototype instead of new Error (which is what you had). I found this solution from the first answer provided to this question: How do I create a custom Error in JavaScript?
I also changed your console.log lines to concatenate the two strings, as I was using alert() to display the output for testing purposes.
Kevin Hakanson goes over why you may or may not want to go with this solution in his answer. Here's the code to answer your question:
function FooError(message) {
    this.stack = (new Error(message)).stack;
    console.log('this.stack ' + this.stack);
    console.log('new_error_stack ' + (new Error(message)).stack);
    console.log('after');
}

FooError.prototype = Error.prototype;

throw new FooError("foo");

You may want to use a try/catch block with that last line.


text:
Q: How do I add a Modal to a complex Ionic app? I have an ionic app set up with a similar navigation style as this codepen:
http://codepen.io/calendee/pen/JdtuG
HTML:

    <title>Ionic Template</title>

    <link href="http://code.ionicframework.com/0.9.27/css/ionic.min.css" rel="stylesheet">

<ion-nav-view></ion-nav-view>

Javascript:
angular.module('ionicApp', ['ionic'])

    .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('entry', {
                url : '/entry',
                templateUrl : 'entry.html',
                controller : 'EntryPageController'
            })

            .state('main', {
                url : '/main',
                templateUrl : 'mainContainer.html',
                abstract : true,
                controller : 'MainController'
            })

            .state('main.home', {
                url: '/home',
                views: {
                    'main': {
                        templateUrl: 'home.html',
                        controller : 'HomePageController'
                    }
                }
            })

            .state('main.info', {
                url: '/info',
                views: {
                    'main': {
                        templateUrl: 'info.html',
                        controller : 'InfoPageController'
                    }
                }
            })

            .state('main.tabs', {
                 url: '/tabs',
                 views: {
                     'main': {
                         templateUrl: 'tabs.html',
                         controller : 'TabsPageController'
                     }
                 }
            })

        $urlRouterProvider.otherwise('/entry');
    }])

    .controller('MainController', [ '$scope', function($scope) {
        $scope.toggleMenu = function() {
            $scope.sideMenuController.toggleLeft();
        }
    }])

    .controller('EntryPageController', [ '$scope', '$state', function($scope, $state) {
        $scope.navTitle = 'Entry Page';

        $scope.signIn = function() {
            $state.go('main.home');
        }
    }])

    .controller('HomePageController', [ '$scope', '$state', function($scope, $state) {
        $scope.navTitle = 'Home Page';

        $scope.leftButtons = [{
            type: 'button-icon icon ion-navicon',
            tap: function(e) {
                $scope.toggleMenu();
            }
        }];
    }])

    .controller('InfoPageController', [ '$scope', '$state', function($scope, $state) {
        $scope.navTitle = 'Info Page';

        $scope.leftButtons = [{
            type: 'button-icon icon ion-navicon',
            tap: function(e) {
                $scope.toggleMenu();
            }
        }];
    }])

    .controller('TabsPageController', [ '$scope', '$state', function($scope, $state) {
        $scope.navTitle = 'Tab Page';

        $scope.leftButtons = [{
            type: 'button-icon icon ion-navicon',
            tap: function(e) {
                $scope.toggleMenu();
            }
        }];
    }])

I have search and tried many different things but I can't seem to figure out how to add a modal to one of the pages. I can do it in a simpler app with only one type of navigation, but this codepen has two types of navigation (side menu and tabs on certian pages) and the controllers are split differently then I am used to and I don't know where to initialize the $ionicModal. I have tried putting in the main controller as well as the home page controller, but if I do, then I get a blank page. Any help would be very much appreciated!
Sorry if I am doing this wrong. I usually don't come on here often.

A: You should post your attempt that didn't work.  Then I could help more.  However, my wild guess is that the template path you specified is not correct.
Also, please don't post so much code.  Most of this is irrelevant to the issue.  If you want someone to take time to help, then take time to ask concisely.
Here is a working modal example: http://codepen.io/calendee/pen/AHIuh/
    // Load the modal from the given template URL
$ionicModal.fromTemplateUrl('modal.html', function($ionicModal) {
    $scope.modal = $ionicModal;
}, {
    // Use our scope for the scope of the modal to keep it simple
    scope: $scope,
    // The animation we want to use for the modal entrance
    animation: 'slide-in-up'
});

});
and then on your button (or whatever opens the modal)
ng-click="modal.show()"


text:
Q: FME Desktop - Combining two weighted fields into one I have two feature classes that I have spatially joined using the spatial relator. There are two city fields in this new feature. For the sake of the example, we can refer to them as Cities A and Cities B. Some values are null in both fields, however the Cities A is more accurate.
How do I combine Cities A and Cities B into a new field with priority given to Cities A, assuming it is not null. i.e. if Cities A is null and Cities B has a value, we use Cities B. If Cities A and B both have values for a feature, then only Cities A would be used.

A: In FME that process you are speaking of is actually easier to imagine in the sense of a conditional value rather than a weighted value. The easiest way to accomplish this is through the attribute manager, let me show you.
Given this table:

We use an attribute manager with a conditional statement to create and populate the third field, resulting in this output:

Screenshot of how to access Conditional Value Dialogue Box:

Screenshot of conditional statement:


text:
Q: Vector similarity search in iOS Is there an implementation of vector similarity search that works in iOS?
I have a set of ~10K+ vectors. When I get a new vector, I'd like to find the top K vectors from the set that are most similar to the new vector.
This can be done either in a loop: compute similarity between every vector in the set and the new vector, and pick the top K.
There are more efficient ways (e.g. FAISS or ScanNN) that can scale to millions of vectors, but they don't work on iOS. Is there an implementation of vector similarity search that works in iOS?
Edit 1:
I've found this project https://github.com/hora-search/hora-ios, but it looks dead. Has anyone tried it out?


text:
Q: Correct way to seed DB with users when using Web Api Identity and Tokens I have a MVC Wab API and I've started modifying it to include some of my own tables using a code first approach.
I'm having trouble with seeding the AspNetUsers table with initial data which then works with my (the default) token based authentication.
When I seed the database, the SecurityStamp field is not populated and it seems this is critical to the token based authentication.
Registering an account via the AccountController generates this fine, however when I see the table via the code below, the security stamp is not populated...understandably so.
    context.Users.Add(new ApplicationUser
    {
        Email = "damo2@email.co.uk",
        UserName = "damo2@email.co.uk",
        PasswordHash = new PasswordHasher().HashPassword("Som3Pass!")
    });

There appears to be a UpdateSecurityStampAsync method which I assume will generate the Security Stamp, but I can't figure out how to call / used it while seeding. (I don't know what to do with  here..I'm still a novice)
Questions are:

*

*What is the correct way to seed the user table when using MVC WebAPI & Individual accounts.

*If I should be using the UpdateSecurityStampAsync method, how?

A: For question 2, The steps are:
Add / Update the users in the context.
Create a UserStore.  The UserStore is basically the data layer wrapper for ASP Identity. It controls how ASP Identity works with the database.
Create a UserManager.  The UserManager is basically the implementation of ASP Identity.  ASP Identity "out of the box" contains many methods, most of which are empty (exp: SendSMS, VerifyTwoFactorToken).  The developer is supposed to implement the methods they care about.
However, the UpdateSecurityStamp method is one of the methods with a default implementation. So we luck out.
Call UserManager.UpdateSecurityStamp(UserJustUpdated.Id).
  public override void Seed(ApplicationDbContext context)
  {
      //The UserStore is ASP Identity's data layer. Wrap context with the UserStore.
      UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context);

      //The UserManager is ASP Identity's implementation layer: contains the methods.
      //The constructor takes the UserStore: how the methods will interact with the database.
      UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

      //Add or Update the initial Users into the database as normal.
      context.AddOrUpdate(
          x => x.Email,  //Using Email as the Unique Key: If a record exists with the same email, AddOrUpdate skips it.
          new ApplicationUser() { Email = "damo2@email.co.uk", UserName = "damo2@email.co.uk", PasswordHash = new PasswordHasher().HashPassword("Som3Pass!") },
          new ApplicationUser() { Email = "2ndUser@email.co.uk", UserName = "Jane Doe", PasswordHash = new PasswordHasher().HashPassword("MyPassword") }
      );

      //Save changes so the Id columns will auto-populate.
      context.SaveChanges();

      //ASP Identity User Id's are Guids stored as nvarchar(128), and exposed as strings.

      //Get the UserId only if the SecurityStamp is not set yet.
      string userId = context.Users.Where(x => x.Email == "damo2@email.co.uk" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

      //If the userId is not null, then the SecurityStamp needs updating.
      if (!string.IsNullOrEmpty(userId)) userManager.UpdateSecurityStamp(userId);

      //Repeat for next user: good opportunity to make a helper method.
      userId = context.Users.Where(x => x.Email == "2ndUser@email.co.uk" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDetault();

      if (!string.IsNullOrempty(userId)) userManager.UpdateSecurityStamp(userId);

      //Continue on with Seed.
  }

As far as question 1, there are many ways.  Which one is correct is a larger discussion.  Most efficient? most secure? least work?
The main problem with the seeding approach are having the passwords as plain text.  Your environment will determine if that is a serious concern or not.


text:
Q: Fill missing line numbers into file using sed / awk / bash I have a (tab-delimited) file where the first "word" on each line is the line number. However, some line numbers are missing. I want to insert new lines (with corresponding line number) so that throughout the file, the number printed on the line matches the actual line number. (This is for later consumption into readarray with cut/awk to get the line after the line number.)
I've written this logic in python and tested it works, however I need to run this in an environment that doesn't have python. The actual file is about 10M rows. Is there a way to represent this logic using sed, awk, or even just plain shell / bash?
linenumre = re.compile(r"^\d+")
i = 0
for line in sys.stdin:
    i = i + 1
    linenum = int(linenumre.findall(line)[0])

    while (i < linenum):
        print(i)
        i = i + 1

    print(line, end='')

test file looks like:
1   foo 1
2   bar 1
4   qux 1
6   quux    1
9       2
10  fun 2

expected output like:
1   foo 1
2   bar 1
3
4   qux 1
5
6   quux    1
7
8
9       2
10  fun 2

A: Like this, with awk:
awk '{while(++ln!=$1){print ln}}1' input.txt

Explanation, as a multiline script:
{

    # Loop as long as the variable ln (line number)
    # is not equal to the first column and insert blank
    # lines.

    # Note: awk will auto-initialize an integer variable
    # with 0 upon its first usage

    while(++ln!=$1) {
        print ln
    }
}

1 # this always expands to true, making awk print the input lines

A: I've written this logic in python and tested it works, however I need to run this in an environment that doesn't have python.
In case you want to have running python code where python is not installed you might freeze your code. The Hitchhiker's Guide to Python has overview of tools which are able to do it. I suggest first trying pyinstaller as it support various operation system and seems easy to use.

A: This might work for you (GNU join, seq and join):
join -a1 -t' ' <(seq $(sed -n '$s/ .*//p' file)) file 2>/dev/null

Join a file created by the command seq using the last line number in file with file.


text:
Q: devExpress searchLookupEdit not setting value I have multiple searchLookupEdit controls on a form. All but one are working.
here is the code to populate one that is working
Private _list As sbList
_list = ag.ListByName("RMATroubleCode")
sluTroubleCode.Properties.DataSource = _list.Items

sluTroubleCode.EditValue = _item.TroubleCode.Value

here is the one that will not work
    Private Sub populate_SKUOrdered(ByRef ctl As SearchLookUpEdit)
        Dim ag As New cpAssemblyQuery()
        Dim l As List(Of cpAssembly) = ag.TopLevelAssemblies()

        ctl.Properties.DataSource = l
    End Sub

populate_SKUOrdered(sluCreateSKUOrdered)
 sluCreateSKUOrdered.EditValue = _item.SKU_OriginallyOrdered.Value

I have verified that  sluCreateSKUOrdered has a DisplayMember and ValueMember property set correctly. They are both set to "SKU" so that is pretty simple.
The dropdown does contain the expected # of items.
The SKU i am trying to set is 'RM45'. So thats pretty simple to verify. It is not a case of trailing or leading spaces...
Are there some trouble shooting steps I can take? I am confident this is a case of simple oversight, but I can not find anything on DevExpress to help me resolve this issue.

A: I am using a ORM,  it is necessary to use the following code
ctl.Properties.DisplayMember = "SKU.Value"
    ctl.Properties.ValueMember = "SKU.Value"

The other controls were using interfaces, or simpler objects, so there was not a good analogy there.


text:
Q: Cordova Plugin FCM reset notifications when enter app via homescreen Guys I'm having a problem, all notifications work great, I can receive push with the callback javascript even background when I enter the app and foreground, but how can i reset or clean my app's notification bar when the user access app via home screen? Is there any way to achieve this? I'm using cordova with ionic and the https://github.com/fechanique/cordova-plugin-fcm does not seem to achieve this, thanks in advance.

A: Solved this by installing phonegap-plugin-push, this plugin doesn't support this kind of thing as reseting notifications/badges


text:
Q: Compute the following expectation with non-independant random variables. Let $X_1$, $X_2$ and $X_3$ be three independant random variables valued in $\mathbb{R}$ on a probability space $(\Omega,\mathcal{A},\mu)$ with the same density function $f \in L^1(\mathbb{R})^+$.
We then denote $Y_1=X_1+X_2$, $\ Y_2=X_1+X_3$ and $Y_3=X_2+X_3$. These three random variables have the same density
$$g(x)=\int_\mathbb{R} f(y)f(x-y) \ \mathrm{d}y$$
but however they are not independant.
I'm trying to compute the quantity
$$\mathbb{E} \left[\max(Y_1,Y_2) \mathcal{1}_{\{Y_1 \geq Y_3\}} \mathcal{1}_{\{Y_2 \geq Y_3\}} \right] $$
however I'm unable to use a transfer theorem since $Y_1$, $Y_2$ and $Y_3$ doesn't form a family of independant random variables. If they were, I could write something like :
$$\mathbb{E} \left[\max(Y_1,Y_2) \mathcal{1}_{\{Y_1 \geq Y_3\}} \mathcal{1}_{\{Y_2 \geq Y_3\}} \right] = \int_{(x,y,z) \in \mathbb{R}^3 \atop x \leq z  \text{ and } y \leq z  } g(x) g(y) g(z) \max(x,y) \ \mathrm{d}x \mathrm{d}y \mathrm{d}z$$
but it's not possible to write that in that case. Is there a way to deal with such expectation involving non-independant random variables ?
All ideas or advices are welcomed.


text:
Q: sending post data via php file_get_contents doesnt work i tried both solutions found here, but seems to work not form me
my request is build like this:
<?php
class RequestObject {
  public $p1 = 1;
  public $p2 = 2;
}
$requestObject = new RequestObject();

$requestString = http_build_query($requestObject);
  // ^^ returns 'p1=1&p2=2'

// $requestUrl = "http://address/api?fn=li_con"; // old with failure response
$requestUrl = "http://address/api/?fn=li_con";
$requestParameters = array(
    "http" => array(
        "method" => "POST",
        "header"  => "Content-type: application/x-www-form-urlencoded",
        "content" => $requestString
    )
);
$streamContext = stream_context_create($requestParameters);
$result = file_get_contents($requestUrl, false, $streamContext);
echo "$result";

my api makes a simple response of post and get array as json string:
<?php
switch(filter_input(INPUT_GET, 'fn')) {
    case 'li_con' :
      echo json_encode(array($_POST, $_GET));
      break;
    default:
      echo "action not found";

}

all i get back is this string:
[[],{"fn":"li_con"}]

so, what is wrong? why do i not get the post parameters in my api?

A: A small bug: add ; on line echo "action not found". It gave me error when testing.
Beside that, it is working fine in my local testing. I used PHP development server, and here is my result (I removed div tag):
[{"p1":"1","p2":"2"},{"fn":"li_con"}]

I am using Arch Linux with PHP 7.0.10. Maybe there is something wrong with your environment? Please mention you PHP version, Web Server and its config, and how do you test your client script.


text:
Q: Dynamic HTML audio player I have audio links that are being pulled in from a database. I want to have a play and pause button for each song and a progress bar that shows whatever song is playing. Currently the play buttons only will play the last song on the list not each individual song and I don't know why.
<?php
include '../../header.php';
session_start();
if(!$_SESSION['logged']){
    header("Location: index.php");
    exit;
}
?>

Title

Description

<audio id="theplayer" controls></audio>

<?php
$tableUser = $_SESSION['username'];
 $con = mysqli_connect("127.0.0.1:3306","localhost","","songstorage");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$result = mysqli_query($con,"SELECT * FROM $tableUser");
while($row = mysqli_fetch_array($result))
  {
      echo "

";
      echo  "
".$row['songid']."
";
      echo "
".$row['title']."
";
      echo "
".$row['description']."
";
      echo "
<button onclick='playaudio()' type='button'>Play</button><audio id='".$row['songid']."'><source src='".$row['url']."'></audio>
";
      echo "

";
      echo "";
      $audioid = array($row['songid']);
       var_dump($audioid);
       }
?>

<audio id="testaudio"><source src="18secFX.wav"></audio>

<?php
//  $songids = mysqli_query($con,"SELECT songid FROM $tableUser");
//$songarray = mysqli_fetch_row($songids);
//var_dump($songarray);

?>

<?php
  mysqli_close($con);
?>
<button onclick="playaudio()" type="button">Play Video</button>
<button onclick="pauseaudio()" type="button">Pause Video</button>

A: Try dynamically generating your buttons and passing a value to the onclick function:
<button onclick="playaudio(".$row['songid'].")" type="button">Play Video</button>

and then in your function:
 function playaudio(songid){
 document.getElementById(songid).load();
 document.getElementById(songid).play();
}


text:
Q: Send result of sql query in email using PowerShell I am trying to send the results of an av SQL query in an email using PowerShell through Azure Runbook. The SQL query works and the results prints to the console but it won't print in an email. Instead, I get the following text in my email "System.Data.DataRow". The connection with my DB works fine and it outputs to the console just doesn't print in an email.
Here is what I have so far:
$SqlQuery = "SELECT
          SUM([Cost]) AS [Sum Cost]
      FROM [dbo].[TestData]
      ;"

$DataSet = New-Object System.Data.DataSet
    $SqlCmd.CommandText = $SqlQuery
    $SqlAdapter.Fill($DataSet)
    $DataSet.Tables[0]

Send-MailMessage -From "me@gmail.com" -To "you@gmail.com" -Subject "Sum cost" -Body "This is the Sum Cost: $($DataSet.Tables[0])" -SmtpServer mail.net -Credential $Cred -Port $Eport

A: The problem is that there's no defined way in the system to turn a DataTable into a string. That means you have to do it.
You could do something like this:
$Body = $DataSet.Tables[0] | ConvertTo-Html -As Table

Or something like this to format it as a table or list and then stringify that output:
$Body = $DataSet.Tables[0] | Format-Table -AutoSize | Out-String

There are caveats and problems with both approaches, like the default formatting on the HTML table is pretty terrible and Format-Table has a max width that can be difficult to overcome, but this method is generally what you need to use.

Alternately, if your query truly returns a single row with a single column, you could easily just pull the data yourself out of the DataSet:
$SumCost =  $DataSet.Tables[0].Rows[0].'Sum Cost'

Send-MailMessage -From "me@gmail.com" -To "you@gmail.com" -Subject "Sum cost" -Body "This is the Sum Cost: $SumCost" -SmtpServer mail.net -Credential $Cred -Port $Eport

Or, if it really is that simple, you could use SqlCommand.ExecuteScalar instead of messing around with the DataSet and DataAdapter entirely. ExecuteScalar is designed to just return the first column of the first row of the result set and that's it. Then you can just do:
$SqlCmd.CommandText = $SqlQuery

try {
    $SqlConnection.Open()
    $SumCost = $SqlCmd.ExecuteScalar()
}
finally {
    $SqlConnection.Dispose()
}

And $SumCost should just be your value.