问:
Are the QtGlobal declarations accessible in PyQt5?
I'm attempting to use the some of the functions in the QtGlobal Header File, but cannot identify where they are. Namely, the qMax and qMin functions.

I've tried using it in the following ways:

```<code>qMax(190, fontHeight * 12)
QtCore.qMax(190, fontHeight * 12)
QtGui.qMax(190, fontHeight * 12)
QtWidgets.qMax(190, fontHeight * 12)
</code>```

The first method has the following response:

```<code>NameError: name 'qMax' is not defined
</code>```

The final 3 all have essentially the same error, just with QtCore substituted with whichever module I was attempting to import them from.

```<code>AttributeError: module 'PyQt5.QtCore' has no attribute 'qMax'
</code>```

I cannot see why these functions would not be included somewhere, but I just can't figured out how to use them.

So are they included, and if so, how do I call them?

答:
The QtGlobal functions are in the QtCore module, but not everything is included:

```<code>>>> print(' '.join(x for x in dir(QtCore) if x[0] == 'q'))
qAbs qAddPostRoutine qAddPreRoutine qChecksum qCompress qCritical qDebug
qErrnoWarning qFatal qFloatDistance qFormatLogMessage qFuzzyCompare qInf
qInstallMessageHandler qIsFinite qIsInf qIsNaN qIsNull qQNaN
qRegisterResourceData qRemovePostRoutine qRound qRound64 qSNaN
qSetFieldWidth qSetMessagePattern qSetPadChar qSetRealNumberPrecision
qSharedBuild qUncompress qUnregisterResourceData qVersion qWarning
qrand qsrand
</code>```

There seems little point in including qMin and qMax. Python already has min and max, which offer a far superior API.

PS:

I suppose I should add that min/max will work fine with Qt types, so long as they implement the less-than operator (__lt__):

```<code>>>> x = QtGui.QStandardItem('1')
>>> y = QtGui.QStandardItem('2')
>>> min(x, y).text()
'1'
>>> max(x, y).text()
'2'
</code>```

Body:
I'm attempting to use the some of the functions in the QtGlobal Header File, but cannot identify where they are. Namely, the qMax and qMin functions.

I've tried using it in the following ways:

qMax(190, fontHeight * 12)
QtCore.qMax(190, fontHeight * 12)
QtGui.qMax(190, fontHeight * 12)
QtWidgets.qMax(190, fontHeight * 12)

The first method has the following response:

NameError: name 'qMax' is not defined

The final 3 all have essentially the same error, just with QtCore substituted with whichever module I was attempting to import them from.

AttributeError: module 'PyQt5.QtCore' has no attribute 'qMax'

I cannot see why these functions would not be included somewhere, but I just can't figured out how to use them.

So are they included, and if so, how do I call them?

Body:
The QtGlobal functions are in the QtCore module, but not everything is included:

>>> print(' '.join(x for x in dir(QtCore) if x[0] == 'q'))
qAbs qAddPostRoutine qAddPreRoutine qChecksum qCompress qCritical qDebug
qErrnoWarning qFatal qFloatDistance qFormatLogMessage qFuzzyCompare qInf
qInstallMessageHandler qIsFinite qIsInf qIsNaN qIsNull qQNaN
qRegisterResourceData qRemovePostRoutine qRound qRound64 qSNaN
qSetFieldWidth qSetMessagePattern qSetPadChar qSetRealNumberPrecision
qSharedBuild qUncompress qUnregisterResourceData qVersion qWarning
qrand qsrand

There seems little point in including qMin and qMax. Python already has min and max, which offer a far superior API.

PS:

I suppose I should add that min/max will work fine with Qt types, so long as they implement the less-than operator (__lt__):

>>> x = QtGui.QStandardItem('1')
>>> y = QtGui.QStandardItem('2')
>>> min(x, y).text()
'1'
>>> max(x, y).text()
'2'


来源: stackexchange

问:
Trouble allowing user to exit
I am simply trying to allow a user to exit program when they enter "Q"

but my program right now just takes "Q" as another input and runs the program. This is supposed to be a piglatin translator still working on the consonant cluster problem

```<code>import java.util.Scanner;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";

            String word = userWord.next();

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") ||
                    firstLetter.equals("i") || firstLetter.equals("o")
                    || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }

            if (word.equals("Q")) {
                System.exit(0);
            }
        }
    }
}
</code>```

答:
As per my understanding you just want to stop the execution when ever user give 'Q' or 'q' so you should stop JVM from running your application.Try this.</p>

```<code>if(firstLetter.equals("Q") || firstLetter.equals("q")){
    System.exit(0);//static method for stopping the JVM from System class
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Trouble allowing user to exit

Body:
I am simply trying to allow a user to exit program when they enter "Q"

but my program right now just takes "Q" as another input and runs the program. This is supposed to be a piglatin translator still working on the consonant cluster problem

import java.util.Scanner;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";

            String word = userWord.next();

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") ||
                    firstLetter.equals("i") || firstLetter.equals("o")
                    || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }

            if (word.equals("Q")) {
                System.exit(0);
            }
        }
    }
}

Body:
As per my understanding you just want to stop the execution when ever user give 'Q' or 'q' so you should stop JVM from running your application.Try this.

if(firstLetter.equals("Q") || firstLetter.equals("q")){
    System.exit(0);//static method for stopping the JVM from System class
}


答:
Try running this now. Slight modification in if-else statement.    </p>

```<code>import java.util.Scanner;
public class Assignment_4_Piglatin {
    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);
        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");
            String firstLetter = "something";
            String word = userWord.next();

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o")
                || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else if (word.equals("Q")) {
                System.exit(0);
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }
        }
        userWord.close();
    }
}
</code>```

Title: Trouble allowing user to exit

Body:
Try running this now. Slight modification in if-else statement.

import java.util.Scanner;
public class Assignment_4_Piglatin {
    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);
        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");
            String firstLetter = "something";
            String word = userWord.next();

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o")
                || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else if (word.equals("Q")) {
                System.exit(0);
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }
        }
        userWord.close();
    }
}


问:
Ionic - How to remove sidemenu on login page only?
I need to remove sidemenu only on my login page. Otherwise remain. How it can be done? I'm using command ionic ionic start myApp sidemenu to create the project.

app.js

```<code>.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('login', {
      url: "/login",
      templateUrl: "templates/login.html",
      controller: 'LoginCtrl'
    })

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/menu.html",
      controller: 'AppCtrl'
    })

    .state('app.search', {
      url: "/search",
      views: {
        'menuContent' :{
          templateUrl: "templates/search.html"
        }
      }
    })
</code>```

login page

```<code><ion-view title="Login">
  <ion-content>
      <div class="list">
        <label class="item">
          <button class="button button-block button-positive" type="submit" ng-click="login()">Log in</button>
        </label>
      </div>

  </ion-content>
</div>
</code>```

答:
```<code>.state('login', {
        url: '/login',
        controller: 'LoginCtrl',
        templateUrl: 'templates/loginpage.html'
    })
.state('app.account', {
        url: '/account',
        views: {
            'menuContent': {
                templateUrl: 'templates/account.html',
                controller: 'AccountCtrl'
            }
        }
    })
</code>```

Body:
I need to remove sidemenu only on my login page. Otherwise remain. How it can be done? I'm using command ionic ionic start myApp sidemenu to create the project.

app.js

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

    .state('login', {
      url: "/login",
      templateUrl: "templates/login.html",
      controller: 'LoginCtrl'
    })

    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl: "templates/menu.html",
      controller: 'AppCtrl'
    })

    .state('app.search', {
      url: "/search",
      views: {
        'menuContent' :{
          templateUrl: "templates/search.html"
        }
      }
    })

login page

<ion-view title="Login">
  <ion-content>

          <button class="button button-block button-positive" type="submit" ng-click="login()">Log in</button>

  </ion-content>


问:
javascript minimax algorithm tic tac toe, not always giving the best move
I have been trying to use minimax algorithm for my tic tac toe game to make my AI unbeatable. However it doesn't always return the optimal move.

```<code>AI = X; human = "O"

var board =  ["x", "x", "-",
               "-", "o", "o",
               "-", "-", "-"]
</code>```

It gives the board above index[2] as the optimal move which is correct.

However, with the board below, the answer it gives is index[3], which will allow the human player to win on its turn.

```<code>var boardB = ["x","x","o",
             "-","o","-",
             "-","_","-"];

var player = 'x';
var opponent = 'o';

function isMovesLeft(board){
    for (var i = 0; i<board.length; i++){
        if (board[i] =='-'){
            return 'true';
        }
        else{
            return 'false';
        }
    }
}

function evaluate(){
    for (var i = 0; i < board.length; i += 3) {
        if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
            if (board[i] == player){
                return +10;
            }
            else if(board[i]== opponent){
                return -10;
            }
        }
    }
    for (var j = 0; j < board.length; j++) {
        if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
            if (board[j] == player){
                return +10;
            }
            else if(board[j] == opponent){
                return -10;
            }
        }
    }

  if ((board[4]==board[0] && board[4]==board[8]) || (board[4]==board[2] && board[4]==board[6])) {
    if (board[4]==player){
        return +10;
    }
    else if (board[4]==opponent){
        return -10;
    }
 }

return 0;
}

function minimax(board, depth, isMax){
    var score = evaluate(board);

    if (score == 10){
        return score;
    }

    if (score == -10){
        return score;
    }

    if (isMovesLeft(board) =="false"){
        return 0;
    }

    if (isMax == "true"){
        var best = -1000;

        for (var i = 0; i< board.length; i++){
            if (board[i]=='-'){
                board.splice(i, 1, player);
                var value = minimax(board, depth+1, "false");
                best = Math.max(best, value);

                board.splice(i, 1, "-");
            }
         }
         return best;
     }

    else if (isMax == 'false'){
        var best = 1000;
        for (var i = 0; i<board.length; i++){
            if (board[i]=='-'){
             board.splice(i, 1, opponent);
             var value = minimax(board, depth+1, "true");
             best = Math.min(best, value);

             board.splice(i, 1, "-");
            }
         }
        return best;
      }
}

function findBestMove(board){
    var bestVal = -1000;
    var bestMove= -1;

    for (var i = 0; i<board.length; i++){
        if (board[i]=='-'){
            board.splice(i, 1, player);
            var moveVal = minimax(board, 0, "false");

            board.splice(i, 1, "-");

            if (moveVal > bestVal)
            {
                bestMove = i;
                bestVal = moveVal;
            }
        }
    }
    alert("bestVal is : " + bestVal + "<br> best Move is : " + bestMove;)
}
</code>```

I wonder what is wrong with my code. Below are some websites that I used as references:

http://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-3-tic-tac-toe-ai-finding-optimal-move/

https://blog.vivekpanyam.com/how-to-build-an-ai-that-wins-the-basics-of-minimax-search/

But I still can't figure out the reason why it's not always returning the optimal move.
I hope someone can lead me to the right direction. Thanks in advance!

答:
If you see the moveVal for each i you'll see that it's zero.

That's because in the minimax function you call isMovesLeft which when false returns 0.

The problem with your program is that isMovesLeft always returns false.

You should change it to :

```<code>function isMovesLeft(board){
    for (var i = 0; i<board.length; i++){
        if (board[i] =='-'){
            return 'true';
        }
    }
return false;
}
</code>```

This change should have your program get 6 as the best move.

The parameter depth is never used anywhere.

You can use it while returning the score: return score/depth

This will ensure that the short term consequences of losing/winning have more effect than long term.

Body:
I have been trying to use minimax algorithm for my tic tac toe game to make my AI unbeatable. However it doesn't always return the optimal move.

AI = X; human = "O"

var board =  ["x", "x", "-",
               "-", "o", "o",
               "-", "-", "-"]

It gives the board above index[2] as the optimal move which is correct.

However, with the board below, the answer it gives is index[3], which will allow the human player to win on its turn.

var boardB = ["x","x","o",
             "-","o","-",
             "-","_","-"];

var player = 'x';
var opponent = 'o';

function isMovesLeft(board){
    for (var i = 0; i<board.length; i++){
        if (board[i] =='-'){
            return 'true';
        }
        else{
            return 'false';
        }
    }
}

function evaluate(){
    for (var i = 0; i < board.length; i += 3) {
        if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
            if (board[i] == player){
                return +10;
            }
            else if(board[i]== opponent){
                return -10;
            }
        }
    }
    for (var j = 0; j < board.length; j++) {
        if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
            if (board[j] == player){
                return +10;
            }
            else if(board[j] == opponent){
                return -10;
            }
        }
    }

  if ((board[4]==board[0] && board[4]==board[8]) || (board[4]==board[2] && board[4]==board[6])) {
    if (board[4]==player){
        return +10;
    }
    else if (board[4]==opponent){
        return -10;
    }
 }

return 0;
}

function minimax(board, depth, isMax){
    var score = evaluate(board);

    if (score == 10){
        return score;
    }

    if (score == -10){
        return score;
    }

    if (isMovesLeft(board) =="false"){
        return 0;
    }

    if (isMax == "true"){
        var best = -1000;

        for (var i = 0; i< board.length; i++){
            if (board[i]=='-'){
                board.splice(i, 1, player);
                var value = minimax(board, depth+1, "false");
                best = Math.max(best, value);

                board.splice(i, 1, "-");
            }
         }
         return best;
     }

    else if (isMax == 'false'){
        var best = 1000;
        for (var i = 0; i<board.length; i++){
            if (board[i]=='-'){
             board.splice(i, 1, opponent);
             var value = minimax(board, depth+1, "true");
             best = Math.min(best, value);

             board.splice(i, 1, "-");
            }
         }
        return best;
      }
}

function findBestMove(board){
    var bestVal = -1000;
    var bestMove= -1;

    for (var i = 0; i<board.length; i++){
        if (board[i]=='-'){
            board.splice(i, 1, player);
            var moveVal = minimax(board, 0, "false");

            board.splice(i, 1, "-");

            if (moveVal > bestVal)
            {
                bestMove = i;
                bestVal = moveVal;
            }
        }
    }
    alert("bestVal is : " + bestVal + "
 best Move is : " + bestMove;)
}

I wonder what is wrong with my code. Below are some websites that I used as references:

http://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-3-tic-tac-toe-ai-finding-optimal-move/

https://blog.vivekpanyam.com/how-to-build-an-ai-that-wins-the-basics-of-minimax-search/

But I still can't figure out the reason why it's not always returning the optimal move.
I hope someone can lead me to the right direction. Thanks in advance!

Body:
If you see the moveVal for each i you'll see that it's zero.

That's because in the minimax function you call isMovesLeft which when false returns 0.

The problem with your program is that isMovesLeft always returns false.

You should change it to :

function isMovesLeft(board){
    for (var i = 0; i<board.length; i++){
        if (board[i] =='-'){
            return 'true';
        }
    }
return false;
}

This change should have your program get 6 as the best move.

The parameter depth is never used anywhere.

You can use it while returning the score: return score/depth

This will ensure that the short term consequences of losing/winning have more effect than long term.


问:
Adding Command Line Arguments to shortcut with .bat file
I am trying to add command line arguments after created a shortcut in a .bat file. Here is my code:

```<code>@echo off

set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"

echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\dny.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "%USERPROFILE%\Desktop\deney\zf.exe" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%

cscript /nologo %SCRIPT%
del %SCRIPT%
</code>```

I want to add this: /server xxx.xxx.net

After all I should see this on shortcut path:

C:\Users\Username\Desktop\dny\zf.exe /server xxx.xxx.net

答:
I found the answer by adding this between targetpath and save commands:</p>

```<code>echo oLink.Arguments = "/server xxx.xxx.net" >> %SCRIPT%
</code>```

Body:
I am trying to add command line arguments after created a shortcut in a .bat file. Here is my code:

@echo off

set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"

echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\dny.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "%USERPROFILE%\Desktop\deney\zf.exe" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%

cscript /nologo %SCRIPT%
del %SCRIPT%

I want to add this: /server xxx.xxx.net

After all I should see this on shortcut path:

C:\Users\Username\Desktop\dny\zf.exe /server xxx.xxx.net

Body:
I found the answer by adding this between targetpath and save commands:

echo oLink.Arguments = "/server xxx.xxx.net" >> %SCRIPT%


问:
What is the _UID used for in Cappuccino?
Cappuccino defines a _UID property for every instance of objects it creates, but is this used for anything?</p>

答: It's used in dozens of places, which you could see by doing something like "git grep UID" on the source code. Most often it is used as a hash key. Also, it's spelled "Cappuccino."</p>

ContentLicense: CC BY-SA 2.5


问:
Powershell IE object finding correct element
I am trying to access an element of a popup window, which seems to be embedded in an iframe.  Below is the html I am dealing with. The line I am interested in below is ...OK.../a> . I have left some html out as it is rather large and I did not think it would be helpful. If needed I can post. I have tried many combinations to access this but so far nothing gets that OK button. Below is my best guess code that does not work.

```<code>$ie.Document.getElementsByTagName("A") | Where {$_.getAttributeNode
('class').Value -eq 'btn btn3d PopupBtn'}
</code>```

```<code><html>
<head>...</head>
  <body>
    <iframe id="12345"src="https://example.com/html/messagepopup.html"
     frameborder="0" style="width:100%; height: 154px;">
     <!-- COMMENT HERE about the software
     -->
     <html>
     <head>
     <link href="https://example.com/path/to/custompage.css"rel=stylesheet">
     </link>
     </head>
     <body class="popupmsg" onload="onload()">
     <div class="PopupMsgFooter" id="PopupMsgFooter">
     <a class="btn bnt3d PopupBtn" href="#" arid="2"arwindowid="0">OK</a>
     </body>
     </html>
     </iframe>
 </body>
</html>
</code>```

答:
The button is inside an iframe, and an iframe has its own separate DOM.

Find the iframe element

Find the button inside the iframe's contentDocument

```<code>$iframe = $ie.Document.getElementsByTagName('iframe') |
    Where { $_.src -contains '/messagepopup.html' }
$ok = $iframe.contentDocument.getElementsByTagName('a') |
    Where { $_.className -eq 'btn bnt3d PopupBtn' }
</code>```

Body:
I am trying to access an element of a popup window, which seems to be embedded in an iframe.  Below is the html I am dealing with. The line I am interested in below is ...OK.../a> . I have left some html out as it is rather large and I did not think it would be helpful. If needed I can post. I have tried many combinations to access this but so far nothing gets that OK button. Below is my best guess code that does not work.

$ie.Document.getElementsByTagName("A") | Where {$_.getAttributeNode
('class').Value -eq 'btn btn3d PopupBtn'}

...

     <link href="https://example.com/path/to/custompage.css"rel=stylesheet">
     </link>

     OK

Body:
The button is inside an iframe, and an iframe has its own separate DOM.

Find the iframe element

Find the button inside the iframe's contentDocument

$iframe = $ie.Document.getElementsByTagName('iframe') |
    Where { $_.src -contains '/messagepopup.html' }
$ok = $iframe.contentDocument.getElementsByTagName('a') |
    Where { $_.className -eq 'btn bnt3d PopupBtn' }


问:
Change package name for Android in React Native
I used react-native init MyApp to initialise a new React Native app.
This created among others an Android project with the package com.myapp.

What's the best way to change this package name, for example to: com.mycompany.myapp?

I tried changing it in AndroidManifest.xml but it created other errors, so I'm assuming it's not the way.

Any idea?

答:
I have a solution based on @Cherniv's answer (works on macOS for me). Two differences: I have a Main2Activity.java in the java folder that I do the same thing to, and I don't bother calling ./gradlew clean since it seems like the react-native packager does that automatically anyways.

Anyways, my solution does what Cherniv's does, except I made a bash shell script for it since I'm building multiple apps using one set of code and want to be able to easily change the package name whenever I run my npm scripts.

Here is the bash script I used. You'll need to modify the packageName you want to use, and add anything else you want to it... but here are the basics. You can create a .sh file, give permission, and then run it from the same folder you run react-native from:

```<code>rm -rf ./android/app/src/main/java

mkdir -p ./android/app/src/main/java/com/MyWebsite/MyAppName
    packageName="com.MyWebsite.MyAppName"
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/Main2Activity.java
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/MainActivity.java
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/MainApplication.java
    sed -i '' -e "s/.*package=\".*/    package=\""$packageName"\"/" ./android/app/src/main/AndroidManifest.xml
    sed -i '' -e "s/.*package = '.*/  package = '"$packageName"',/" ./android/app/BUCK
    sed -i '' -e "s/.*applicationId.*/    applicationId \""$packageName"\"/" ./android/app/build.gradle

    cp -R ./android/app/src/main/javaFiles/ ./android/app/src/main/java/com/MyWebsite/MyAppName
</code>```

DISCLAIMER: You'll need to edit MainApplication.java's comment near the bottom of the java file first. It has the word 'package' in the comment. Because of how the script works, it takes any line with the word 'package' in it and replaces it. Because of this, this script may not be future proofed as there might be that same word used somewhere else.

Second Disclaimer: the first 3 sed commands edit the java files from a directory called javaFiles. I created this directory myself since I want to have one set of java files that are copied from there (as I might add new packages to it in the future). You will probably want to do the same thing. So copy all the files from the java folder (go through its subfolders to find the actual java files) and put them in a new folder called javaFiles.

Third Disclaimer: You'll need to edit the packageName variable to be in line with the paths at the top of the script and bottom (com.MyWebsite.MyAppName to com/MyWebsite/MyAppName)

Body:
I have a solution based on @Cherniv's answer (works on macOS for me). Two differences: I have a Main2Activity.java in the java folder that I do the same thing to, and I don't bother calling ./gradlew clean since it seems like the react-native packager does that automatically anyways.

Anyways, my solution does what Cherniv's does, except I made a bash shell script for it since I'm building multiple apps using one set of code and want to be able to easily change the package name whenever I run my npm scripts.

Here is the bash script I used. You'll need to modify the packageName you want to use, and add anything else you want to it... but here are the basics. You can create a .sh file, give permission, and then run it from the same folder you run react-native from:

rm -rf ./android/app/src/main/java

mkdir -p ./android/app/src/main/java/com/MyWebsite/MyAppName
    packageName="com.MyWebsite.MyAppName"
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/Main2Activity.java
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/MainActivity.java
    sed -i '' -e "s/.*package.*/package "$packageName";/" ./android/app/src/main/javaFiles/MainApplication.java
    sed -i '' -e "s/.*package=\".*/    package=\""$packageName"\"/" ./android/app/src/main/AndroidManifest.xml
    sed -i '' -e "s/.*package = '.*/  package = '"$packageName"',/" ./android/app/BUCK
    sed -i '' -e "s/.*applicationId.*/    applicationId \""$packageName"\"/" ./android/app/build.gradle

    cp -R ./android/app/src/main/javaFiles/ ./android/app/src/main/java/com/MyWebsite/MyAppName

DISCLAIMER: You'll need to edit MainApplication.java's comment near the bottom of the java file first. It has the word 'package' in the comment. Because of how the script works, it takes any line with the word 'package' in it and replaces it. Because of this, this script may not be future proofed as there might be that same word used somewhere else.

Second Disclaimer: the first 3 sed commands edit the java files from a directory called javaFiles. I created this directory myself since I want to have one set of java files that are copied from there (as I might add new packages to it in the future). You will probably want to do the same thing. So copy all the files from the java folder (go through its subfolders to find the actual java files) and put them in a new folder called javaFiles.

Third Disclaimer: You'll need to edit the packageName variable to be in line with the paths at the top of the script and bottom (com.MyWebsite.MyAppName to com/MyWebsite/MyAppName)


问:
Conway's Game of Life recursive step function
To help me begin to understand Haskell, I'm implementing Conway's Game of Life and ran into a snag in my step function trying to build a 2D list. Relevant definitions below:

```<code>data Cell = On | Off deriving (Eq, Show)

type Board = [[Cell]]
type Coord = (Int, Int)
type IndexedBoard = [[(Coord, Cell)]]

testBoard =     [[On, On,  On]
                ,[On, Off, On]
                ,[On, On,  On]]

numNeighbors :: Board -> Coord -> Int
-- Returns the number of live neighbors given a Board and a Coord on that board
-- assume this is implemented correctly, because it's a bunch of code
-- that you don't otherwise need to read, and it passes tests.

addIndexes :: Board -> IndexedBoard
addIndexes xs = [[((x,y), el) | (x,el) <- zip [0..] row] | (y,row) <- zip [0..] xs]
removeIndexes :: IndexedBoard -> Board
removeIndexes = map (map snd)
-- addIndexes testBoard is
-- [ [((0, 0), On), ((1, 0), On),  ((2, 0), On)]
--   ,((0, 1), On), ((1, 1), Off), ((2, 1), On)]
--   ,((0, 2), On), ((1, 2), On),  ((2, 2), On)] ]
-- and removeIndexes . addIndexes = id
</code>```

My step function is where I'm having trouble. I'm not sure how to build the 2D list I expect without mutual recursion (which I'm trying to avoid arbitrarily).

```<code>step :: Board -> Board
step board = removeIndexes . step' . addIndexes $ board where
    step' :: IndexedBoard -> IndexedBoard
    step' [] = []
    step' ([]:rest) = step' rest
    step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))
    newCell :: Int -> Cell -> Cell
    newCell 2 On = On
    newCell 3 _ = On
    newCell _ _ = Off
</code>```

I expect the follow output from step testBoard:

```<code>[[On,  Off, On ]
,[Off, Off, Off]
,[On,  Off, On ]]
</code>```

But am instead getting:

```<code>[[On],  [Off], [On]
,[Off], [Off], [Off]
,[On],  [Off], [On]]
</code>```

I understand that's because my recursive case of step' gives [(coord, newCell (numNeighbors board coord) cell)] : ..., but if I pull that out of the list I get the following error:

```<code>[1 of 1] Compiling Main             ( gameoflife.hs, interpreted )

gameoflife.hs:51:44: error:
    • Couldn't match type ‘(Coord, Cell)’ with ‘[(Coord, Cell)]’
      Expected type: IndexedBoard
        Actual type: [(Coord, Cell)]
    • In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
      In an equation for ‘step’:
          step board
            = removeIndexes . step' . addIndexes $ board
            where
                step' :: IndexedBoard -> IndexedBoard
                step' [] = []
                step' ([] : rest) = step' rest
                step' (((coord, cell) : restrow) : rest)
                  = (coord, newCell (numNeighbors board coord) cell)
                    : (step' (restrow : rest))
                newCell :: Int -> Cell -> Cell
                newCell 2 On = On
                newCell 3 _ = On
                newCell _ _ = Off

gameoflife.hs:51:96: error:
    • Couldn't match type ‘[(Coord, Cell)]’ with ‘(Coord, Cell)’
      Expected type: [(Coord, Cell)]
        Actual type: IndexedBoard
    • In the second argument of ‘(:)’, namely
        ‘(step' (restrow : rest))’
      In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
Failed, modules loaded: none.
</code>```

答:
For the actual question see amalloy's answer. This is a too-long-for-comment...

The whole idea of adding indices and then random-accessing other cells (as numNeighbours does) is pretty unidiomatic in Haskells. Indices always forget a lot of structural information, are unsafe, and in particular for lists very inefficient. And pretty unnecessary: all you're ever accessing is direct neighbours.

A much nicer approach is to generalise this idea of mapping elements in their immediate environment.

```<code>mapInEnvi :: (a -> a -> a -> r) -> [a] -> [r]
mapInEnvi f (a:b:c:l) = f a b c : mapInEnvi
...  †
</code>```

The nice thing is how such a higher-order function composes: in your case you have a two-dimensional list, but you can basically just map in each direction independently:

```<code>step :: Board -> Board
step = mapInEnvi modRow
 where modRow above row below = mapInEnvi modCell $ zip3 above row below
       modCell (ne,e,se)
               (n ,m, s)
               (nw,w,sw) = case length $ filter (==On) [ne,e,se,n,s,nw,w,sw] of
          0 -> Off
          1 -> Off
          2 -> m
          3 -> On
          _ -> Off
</code>```

Unlike the solution you were aiming for, this doesn't need to perform any direct position lookups, therefore the complexity is just O (h · w) instead of O (h · w · (h + w)) where h and w are the height and width of the board.

†In case of a finite-sized board it's a bit trickier – you'll need to decide what to do on the boundaries.

Body:
To help me begin to understand Haskell, I'm implementing Conway's Game of Life and ran into a snag in my step function trying to build a 2D list. Relevant definitions below:

data Cell = On | Off deriving (Eq, Show)

type Board = [[Cell]]
type Coord = (Int, Int)
type IndexedBoard = [[(Coord, Cell)]]

testBoard =     [[On, On,  On]
                ,[On, Off, On]
                ,[On, On,  On]]

numNeighbors :: Board -> Coord -> Int
-- Returns the number of live neighbors given a Board and a Coord on that board
-- assume this is implemented correctly, because it's a bunch of code
-- that you don't otherwise need to read, and it passes tests.

addIndexes :: Board -> IndexedBoard
addIndexes xs = [[((x,y), el) | (x,el) <- zip [0..] row] | (y,row) <- zip [0..] xs]
removeIndexes :: IndexedBoard -> Board
removeIndexes = map (map snd)
-- addIndexes testBoard is
-- [ [((0, 0), On), ((1, 0), On),  ((2, 0), On)]
--   ,((0, 1), On), ((1, 1), Off), ((2, 1), On)]
--   ,((0, 2), On), ((1, 2), On),  ((2, 2), On)] ]
-- and removeIndexes . addIndexes = id

My step function is where I'm having trouble. I'm not sure how to build the 2D list I expect without mutual recursion (which I'm trying to avoid arbitrarily).

step :: Board -> Board
step board = removeIndexes . step' . addIndexes $ board where
    step' :: IndexedBoard -> IndexedBoard
    step' [] = []
    step' ([]:rest) = step' rest
    step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))
    newCell :: Int -> Cell -> Cell
    newCell 2 On = On
    newCell 3 _ = On
    newCell _ _ = Off

I expect the follow output from step testBoard:

[[On,  Off, On ]
,[Off, Off, Off]
,[On,  Off, On ]]

But am instead getting:

[[On],  [Off], [On]
,[Off], [Off], [Off]
,[On],  [Off], [On]]

I understand that's because my recursive case of step' gives [(coord, newCell (numNeighbors board coord) cell)] : ..., but if I pull that out of the list I get the following error:

[1 of 1] Compiling Main             ( gameoflife.hs, interpreted )

gameoflife.hs:51:44: error:
    • Couldn't match type ‘(Coord, Cell)’ with ‘[(Coord, Cell)]’
      Expected type: IndexedBoard
        Actual type: [(Coord, Cell)]
    • In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
      In an equation for ‘step’:
          step board
            = removeIndexes . step' . addIndexes $ board
            where
                step' :: IndexedBoard -> IndexedBoard
                step' [] = []
                step' ([] : rest) = step' rest
                step' (((coord, cell) : restrow) : rest)
                  = (coord, newCell (numNeighbors board coord) cell)
                    : (step' (restrow : rest))
                newCell :: Int -> Cell -> Cell
                newCell 2 On = On
                newCell 3 _ = On
                newCell _ _ = Off

gameoflife.hs:51:96: error:
    • Couldn't match type ‘[(Coord, Cell)]’ with ‘(Coord, Cell)’
      Expected type: [(Coord, Cell)]
        Actual type: IndexedBoard
    • In the second argument of ‘(:)’, namely
        ‘(step' (restrow : rest))’
      In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
Failed, modules loaded: none.

Body:
For the actual question see amalloy's answer. This is a too-long-for-comment...

The whole idea of adding indices and then random-accessing other cells (as numNeighbours does) is pretty unidiomatic in Haskells. Indices always forget a lot of structural information, are unsafe, and in particular for lists very inefficient. And pretty unnecessary: all you're ever accessing is direct neighbours.

A much nicer approach is to generalise this idea of mapping elements in their immediate environment.

mapInEnvi :: (a -> a -> a -> r) -> [a] -> [r]
mapInEnvi f (a:b:c:l) = f a b c : mapInEnvi
...  †

The nice thing is how such a higher-order function composes: in your case you have a two-dimensional list, but you can basically just map in each direction independently:

step :: Board -> Board
step = mapInEnvi modRow
 where modRow above row below = mapInEnvi modCell $ zip3 above row below
       modCell (ne,e,se)
               (n ,m, s)
               (nw,w,sw) = case length $ filter (==On) [ne,e,se,n,s,nw,w,sw] of
          0 -> Off
          1 -> Off
          2 -> m
          3 -> On
          _ -> Off

Unlike the solution you were aiming for, this doesn't need to perform any direct position lookups, therefore the complexity is just O (h · w) instead of O (h · w · (h + w)) where h and w are the height and width of the board.

†In case of a finite-sized board it's a bit trickier – you'll need to decide what to do on the boundaries.


问:
Using reshape from long to wide on multiple categorical and numerical variables in R
I have a dateset like this:

```<code>##current state of data
team= c("a","a","a","a","b","b","b","b")
situation=c("fives","fives","short","short","fives","fives","short","short")
year= c("2014","2015","2014","2015","2014","2015","2014","2015")
shots= runif(8, min = 2, max=10)
saves= runif(8, min = 1, max=6)
df = data.frame(team,year,situation, shots, saves)
</code>```

I want the dataset to look like this:

```<code>team = c("a","b")
fives2014shots = runif(2, min = 2, max=10)
fives2015shots = runif(2, min = 2, max=10)
short2014shots = runif(2, min = 2, max=10)
short2015shots = runif(2, min = 2, max=10)
fives2014saves = runif(2, min = 1, max=6)
fives2015saves = runif(2, min = 1, max=6)
short2014saves = runif(2, min = 1, max=6)
short2015saves = runif(2, min = 1, max=6)
data.frame(team, fives2014shots,fives2015shots,
fives2014saves,fives2015saves, short2014shots, short2015shots,
short2014saves, short2015saves)
</code>```

This code gives me the closest result but it only shows the 'saves' numeric variable and I need 'saves' and 'shots' to now show as part of the new column names:

```<code>library(reshape)
cast(df, team ~ year + situation)
</code>```

Thank you!

Body:
I have a dateset like this:

##current state of data
team= c("a","a","a","a","b","b","b","b")
situation=c("fives","fives","short","short","fives","fives","short","short")
year= c("2014","2015","2014","2015","2014","2015","2014","2015")
shots= runif(8, min = 2, max=10)
saves= runif(8, min = 1, max=6)
df = data.frame(team,year,situation, shots, saves)

I want the dataset to look like this:

team = c("a","b")
fives2014shots = runif(2, min = 2, max=10)
fives2015shots = runif(2, min = 2, max=10)
short2014shots = runif(2, min = 2, max=10)
short2015shots = runif(2, min = 2, max=10)
fives2014saves = runif(2, min = 1, max=6)
fives2015saves = runif(2, min = 1, max=6)
short2014saves = runif(2, min = 1, max=6)
short2015saves = runif(2, min = 1, max=6)
data.frame(team, fives2014shots,fives2015shots,
fives2014saves,fives2015saves, short2014shots, short2015shots,
short2014saves, short2015saves)

This code gives me the closest result but it only shows the 'saves' numeric variable and I need 'saves' and 'shots' to now show as part of the new column names:

library(reshape)
cast(df, team ~ year + situation)

Thank you!

Body:
You can do this easily with tidyr.

library(tidyr)

df %>%
  gather("var", "val", -team, -year, -situation) %>%
  unite(key, situation, year, var) %>%
  spread(key, val)

#>   team fives_2014_saves fives_2014_shots fives_2015_saves fives_2015_shots
#> 1    a         3.957574         5.148969         1.909761         6.492150
#> 2    b         4.301518         6.643775         2.923988         3.879531
#>   short_2014_saves short_2014_shots short_2015_saves short_2015_shots
#> 1         4.696710         9.267883         4.178224         9.285276
#> 2         5.886455         9.417314         4.179030         6.485290


问:
reactivex repeated skip between
Suppose I have the following stream of data:

```<code>1, 2, 3, a, 5, 6, b, 7, 8, a, 10, 11, b, 12, 13, ...
</code>```

I want to filter everything between 'a' and 'b' (inclusive) no matter how many times they appear.  So the result of the above would be:

```<code>1, 2, 3, 7, 8, 12, 13, ...
</code>```

How can I do this with ReactiveX?

Title: reactivex repeated skip between

Body:
Suppose I have the following stream of data:

1, 2, 3, a, 5, 6, b, 7, 8, a, 10, 11, b, 12, 13, ...

I want to filter everything between 'a' and 'b' (inclusive) no matter how many times they appear.  So the result of the above would be:

1, 2, 3, 7, 8, 12, 13, ...

How can I do this with ReactiveX?

Body:
Use scan with initial value b to turn

1, 2, 3, a, 5, 6, b, 7, 8, a, 10, 11, b, 12, 13, ...

into

b, 1, 2, 3, a, a, a, b, 7, 8, a, a, a, b, 12, 13, ...

and then filter out a and b to get

1, 2, 3, 7, 8, 12, 13, ...

In pseudo code

values.scan('b', (s, v) -> if (v == 'a' || v == 'b' || s != 'a') v else s).
    filter(v -> v != 'a' && v != 'b');


问:
How do I restrict user sign ups to only certain domains in Firebase?
I have an iOS app that I'd like to restrict access to, making it only available to users from a specific email domain.
The app requires the users to log in using their Google Account.
I've found various answers online that suggested adding

```<code>".read": "auth.token.email.endsWith('gmail.com')"
</code>```

But that doesn't seem to return an error in the sign in page, but only when the user in question tries to access the database. Any suggestions?

答:
You will have to enforce that. You have multiple tools to do so:

After signInWithCredential resolves, you can check the domain and that it is a google.com provider. If you are allowing email/password users, you need to verify those too. If the user doesn't meet your criteria, use the delete API on the user and issue an error to the user that they need to sign in with a certain account.

Enforce the check in your rules, as you can't always trust the client. Ensure that if a user signs up, and isn't deleted, he/she can't access the data.

Use Firebase functions which has a trigger for user creation. On user creation, check your criteria is met, if not, use the firebase-admin module to delete that user.

If you are using the Google sign-in library for iOS to get the Google credential, you can check the Google user email and Google ID token before you signInWithCredential in Firebase and block the sign in attempt.

Write your own clean up script: If you are hosting your own server and do not want to use Firebase Functions, you can run a daily script that downloads all your users using the Firebase CLI SDK and then deletes all users using firebase-admin SDK that do no match your criteria.

Body:
I have an iOS app that I'd like to restrict access to, making it only available to users from a specific email domain.
The app requires the users to log in using their Google Account.
I've found various answers online that suggested adding

".read": "auth.token.email.endsWith('gmail.com')"

But that doesn't seem to return an error in the sign in page, but only when the user in question tries to access the database. Any suggestions?


问:
Theme music - Trying to get duration & keys to work together
I am writing a MATLAB function playing a song (Game of Thrones theme). </p>

<p>I have the correct keystroke and duration. I am trying to have two (treble and bass) playing at once and for each keystroke to be the correct duration. For some reason, I cannot get the duration to work with the keystroke (they all are playing at duration=1) or for the two sets to play together. Any ideas? </p>

```<code>function xx = key2note(X, keynum, dur)
% KEY2NOTE Produce a sinusoidal waveform corresponding to a given piano key number
% usage: xx = key2note (X, keynum, dur)
% xx = the output sinusoidal waveform
% X = complex amplitude for the sinusoid, X = A*exp(j*phi).
% keynum = the piano keyboard number of the desired note
% dur = the duration (in seconds) of the output note

fs = 8000;
tt = (1/fs):(1/fs):dur;
freq = 440*(2^((keynum-49)/12));  %<=============== fill in this line
xx = real(X*exp(j*2*pi*freq*tt)); %<=============== fill in this line
end
</code>```

<p> </p>

```<code>t = 0.17;
%treble - 40 is middle C
throne.keys = [47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47, 40, 40 45 47, 40 43 45, 42 47 36 40];
throne.dur = [ 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 4, 4, 1 1 2 1, 2 1 1, 1 1 1 1];

%bass
throne.keys2 = [ 21, 21 25 28 31 28 25, 21 25 28 31 28 25];
throne.dur2 = [ 32, 1/3 1/3 1/3 1/3 1/3 1/3, 1/3 1/3 1/3 1/3 1/3 1/3];

throne.durations = 0.2 * ones(1,length(throne.dur));
fs = 8000; % 11025 Hz also works
f = 329.62;
xx = zeros(1, sum(throne.dur)*fs + length(throne.keys));
n1 = 1;
for kk = 1:length(throne.keys)
    keynum = throne.keys(kk);
    tone = key2note(1,keynum,0.25); %amplitude 1, keynum, 0.38s % <------- Fill in this line
    n2 = n1 + length(tone) - 1;
    xx(n1:n2) = tone; %<------- Insert the note
    n1 = n2 + 1;
end

fs = 8000;
%xt = zeros(1, sum(tdur)*fs + length(keyst));
%xb = zeros(1, sum(bdur)*fs + 1);
%xa = zeros(1, sum(adur)*fs+1);
%xd = zeros(1, sum(ddur)*fs+1);
%xx = xt + xb + xa + xd
xx = xt + xb;
soundsc(xx,fs)
</code>```

答:
I commented some never used lines out - you might want to uncomment them if they were used for something else later. Also I felt so free as to make t a global speed control.

```<code>t = 0.17; % this variable was never used.
%I assumed you wanted to control the overall speed with it and felt so free to adjust the durations with it.

%treble - 40 is middle C
throne.keys = [47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47, 40, 40 45 47, 40 43 45, 42 47 36 40];
throne.dur = t*[ 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 4, 4, 1 1 2 1, 2 1 1, 1 1 1 1];

%bass
throne.keys2 = [ 21, 21 25 28 31 28 25, 21 25 28 31 28 25];
throne.dur2 = t*[ 32, 1/3 1/3 1/3 1/3 1/3 1/3, 1/3 1/3 1/3 1/3 1/3 1/3];

%throne.durations = 0.2 * ones(1,length(throne.dur)); % this was never used - no clue what you intended to do with it
fs = 8000; % 11025 Hz also works
%f = 329.62; % is also never used

%treble loop
xt = zeros(1, ceil(sum(throne.dur)*fs + length(throne.keys)));
n1 = 1;
for kk = 1:length(throne.keys)
    tone = key2note(1,throne.keys(kk),throne.dur(kk)); % You used here the constant length of 0.25 instead of taking the duration value from throne.dur
    n2 = n1 + length(tone) - 1;
    xt(n1:n2) = tone; %<------- Insert the note
    n1 = n2 + 1;
end

%Bass loop
xb = zeros(1, ceil(sum(throne.dur2)*fs + length(throne.keys2)));
n1 = 1;
for kk = 1:length(throne.keys2)
    tone2 = key2note(1,throne.keys2(kk),throne.dur2(kk));
    n2 = n1 + length(tone2) - 1;
    xb(n1:n2) = tone2; %<------- Insert the note
    n1 = n2 + 1;
end
xb(length(xb)+1:length(xt)) = 0; %bass voice has a much shorter duration currently - padding to same size as xt with 0's at the end.
%If you add more voices, you have to pad them all to the length of the longest one.

%xt = zeros(1, sum(tdur)*fs + length(keyst));
%xb = zeros(1, sum(bdur)*fs + 1);
%xa = zeros(1, sum(adur)*fs+1);
%xd = zeros(1, sum(ddur)*fs+1);
%xx = xt + xb + xa + xd
xx = xt + xb;
soundsc(xx,fs)
</code>```

Of course you could just download the theme song somewhere and use [y,Fs] = audioread(filename) to convert it. But that wouldn't even remotely be as cool as what you are doing.

Body:
I am writing a MATLAB function playing a song (Game of Thrones theme).

I have the correct keystroke and duration. I am trying to have two (treble and bass) playing at once and for each keystroke to be the correct duration. For some reason, I cannot get the duration to work with the keystroke (they all are playing at duration=1) or for the two sets to play together. Any ideas?

function xx = key2note(X, keynum, dur)
% KEY2NOTE Produce a sinusoidal waveform corresponding to a given piano key number
% usage: xx = key2note (X, keynum, dur)
% xx = the output sinusoidal waveform
% X = complex amplitude for the sinusoid, X = A*exp(j*phi).
% keynum = the piano keyboard number of the desired note
% dur = the duration (in seconds) of the output note

fs = 8000;
tt = (1/fs):(1/fs):dur;
freq = 440*(2^((keynum-49)/12));  %<=============== fill in this line
xx = real(X*exp(j*2*pi*freq*tt)); %<=============== fill in this line
end

t = 0.17;
%treble - 40 is middle C
throne.keys = [47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47, 40, 40 45 47, 40 43 45, 42 47 36 40];
throne.dur = [ 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 4, 4, 1 1 2 1, 2 1 1, 1 1 1 1];

%bass
throne.keys2 = [ 21, 21 25 28 31 28 25, 21 25 28 31 28 25];
throne.dur2 = [ 32, 1/3 1/3 1/3 1/3 1/3 1/3, 1/3 1/3 1/3 1/3 1/3 1/3];

throne.durations = 0.2 * ones(1,length(throne.dur));
fs = 8000; % 11025 Hz also works
f = 329.62;
xx = zeros(1, sum(throne.dur)*fs + length(throne.keys));
n1 = 1;
for kk = 1:length(throne.keys)
    keynum = throne.keys(kk);
    tone = key2note(1,keynum,0.25); %amplitude 1, keynum, 0.38s % <------- Fill in this line
    n2 = n1 + length(tone) - 1;
    xx(n1:n2) = tone; %<------- Insert the note
    n1 = n2 + 1;
end

fs = 8000;
%xt = zeros(1, sum(tdur)*fs + length(keyst));
%xb = zeros(1, sum(bdur)*fs + 1);
%xa = zeros(1, sum(adur)*fs+1);
%xd = zeros(1, sum(ddur)*fs+1);
%xx = xt + xb + xa + xd
xx = xt + xb;
soundsc(xx,fs)

Body:
I commented some never used lines out - you might want to uncomment them if they were used for something else later. Also I felt so free as to make t a global speed control.

t = 0.17; % this variable was never used.
%I assumed you wanted to control the overall speed with it and felt so free to adjust the durations with it.

%treble - 40 is middle C
throne.keys = [47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 43 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47 40 44 45, 47, 40, 40 45 47, 40 43 45, 42 47 36 40];
throne.dur = t*[ 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 1 1 0.5 0.5, 4, 4, 1 1 2 1, 2 1 1, 1 1 1 1];

%bass
throne.keys2 = [ 21, 21 25 28 31 28 25, 21 25 28 31 28 25];
throne.dur2 = t*[ 32, 1/3 1/3 1/3 1/3 1/3 1/3, 1/3 1/3 1/3 1/3 1/3 1/3];

%throne.durations = 0.2 * ones(1,length(throne.dur)); % this was never used - no clue what you intended to do with it
fs = 8000; % 11025 Hz also works
%f = 329.62; % is also never used

%treble loop
xt = zeros(1, ceil(sum(throne.dur)*fs + length(throne.keys)));
n1 = 1;
for kk = 1:length(throne.keys)
    tone = key2note(1,throne.keys(kk),throne.dur(kk)); % You used here the constant length of 0.25 instead of taking the duration value from throne.dur
    n2 = n1 + length(tone) - 1;
    xt(n1:n2) = tone; %<------- Insert the note
    n1 = n2 + 1;
end

%Bass loop
xb = zeros(1, ceil(sum(throne.dur2)*fs + length(throne.keys2)));
n1 = 1;
for kk = 1:length(throne.keys2)
    tone2 = key2note(1,throne.keys2(kk),throne.dur2(kk));
    n2 = n1 + length(tone2) - 1;
    xb(n1:n2) = tone2; %<------- Insert the note
    n1 = n2 + 1;
end
xb(length(xb)+1:length(xt)) = 0; %bass voice has a much shorter duration currently - padding to same size as xt with 0's at the end.
%If you add more voices, you have to pad them all to the length of the longest one.

%xt = zeros(1, sum(tdur)*fs + length(keyst));
%xb = zeros(1, sum(bdur)*fs + 1);
%xa = zeros(1, sum(adur)*fs+1);
%xd = zeros(1, sum(ddur)*fs+1);
%xx = xt + xb + xa + xd
xx = xt + xb;
soundsc(xx,fs)

Of course you could just download the theme song somewhere and use [y,Fs] = audioread(filename) to convert it. But that wouldn't even remotely be as cool as what you are doing.


问:
Getting clicked element id and using it in html using angularjs
I am creating ionic app(ionic version v1) with angular js.
I want to get the data of clicked element from one html file and use it in other html file.

app.js

```<code>angular.module('placementApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

  // $ionicConfigProvider.views.transition('android'); //none, ios

  $stateProvider

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

    .state('students', {
      url: '/students',
      templateUrl: 'templates/userList.html'
    })

    .state('companies', {
      url: '/companies',
      templateUrl: 'templates/companyList.html'
    })

    .state('editStudent', {
      url: '/editStudent',
      templateUrl: 'templates/editUser.html'
    });
});
</code>```

userList.component.js

```<code>var app = angular.module('placementApp');

app.controller('userListCtrl', function($scope) {
    $scope.students = [
        {
            name: "Pearl Adam",
            Branch: "CE",
            id: "10562",
            cgpa: "5.9"

        },

        {
            name: "Avrill White",
            Branch: "CSE",
            id: "10821",
            cgpa: "8.3"
        }
    ]

    $scope.getClickedStudent = function(event) {
        $scope.v = event.currentTarget.attributes.data;
        console.log($scope.v);
    }

})
</code>```

userList.html

```<code><ion-view>
    <ion-header-bar class="bar-stable">
        <h1 class="title">Student List</h1>
    </ion-header-bar>
    <ion-content class="has-header">
        <div ng-controller='userListCtrl' ng-init='v = "undefined"'>
            <ul class="list" ng-repeat="x in students">
                <li class="item">
                    <a ng-click="getClickedStudent($event)" data='{{x}}' class="item" href='#/editStudent' >
                        <p>Name: {{x.name}}</p>
                        <p>Roll No.: {{x.id}}</p>
                    </a>
                </li>
            </ul>
            {{v.name}}

        </div>
    </ion-content>
</ion-view>
</code>```

I need to get the data of clicked element and use it in editUser.html for eg. {{v.name}}, {{v.cgpa}}.
but v is getting {} value.

I am using v in following file and it is showing empty value of {{v}} instead.
editUser.html

```<code><ion-view>
    <ion-header-bar class="bar-stable">
        <div ng-controller="userListCtrl">
            <h1 class="title">{{v.name}}</h1>
        </div>
    </ion-header-bar>
    <ion-content class="has-header">
        <div ng-controller='userListCtrl'>
            <div class="list">
                <label class="item item-input">
                    <span class="input-label">Name</span>
                    {{v.name}}
                </label>
                <label class="item item-input">
                    <span class="input-label">Branch</span>
                    {{v.branch}}
                </label>
                <label class="item item-input">
                    <span class="input-label">Roll No.</span>
                    {{v.id}}
                </label>
                <label class="item item-input">
                    <span class="input-label">CGPA</span>
                    {{v.cgpa}}
                </label>

            </div>
        </div>
    </ion-content>
</ion-view>
</code>```

答:
Do this to get the data and the id:</p>

```<code><a href="#" id="12345" data-ng-click="ShowId($event)">

$scope.ShowId = function(event)
{
   $scope.v = event.target.attributes['data'].value;
   $scope.yourWantedId = event.target.id;
};
</code>```

Body:
I am creating ionic app(ionic version v1) with angular js.
I want to get the data of clicked element from one html file and use it in other html file.

app.js

angular.module('placementApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

  // $ionicConfigProvider.views.transition('android'); //none, ios

  $stateProvider

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

    .state('students', {
      url: '/students',
      templateUrl: 'templates/userList.html'
    })

    .state('companies', {
      url: '/companies',
      templateUrl: 'templates/companyList.html'
    })

    .state('editStudent', {
      url: '/editStudent',
      templateUrl: 'templates/editUser.html'
    });
});

userList.component.js

var app = angular.module('placementApp');

app.controller('userListCtrl', function($scope) {
    $scope.students = [
        {
            name: "Pearl Adam",
            Branch: "CE",
            id: "10562",
            cgpa: "5.9"

        },

        {
            name: "Avrill White",
            Branch: "CSE",
            id: "10821",
            cgpa: "8.3"
        }
    ]

    $scope.getClickedStudent = function(event) {
        $scope.v = event.currentTarget.attributes.data;
        console.log($scope.v);
    }

})

userList.html

<ion-view>
    <ion-header-bar class="bar-stable">

Student List

    </ion-header-bar>
    <ion-content class="has-header">

Name: {{x.name}}

Roll No.: {{x.id}}

            {{v.name}}

    </ion-content>
</ion-view>

I need to get the data of clicked element and use it in editUser.html for eg. {{v.name}}, {{v.cgpa}}.
but v is getting {} value.

I am using v in following file and it is showing empty value of {{v}} instead.
editUser.html

<ion-view>
    <ion-header-bar class="bar-stable">

{{v.name}}

    </ion-header-bar>
    <ion-content class="has-header">

                    Name
                    {{v.name}}

                    Branch
                    {{v.branch}}

                    Roll No.
                    {{v.id}}

                    CGPA
                    {{v.cgpa}}

    </ion-content>
</ion-view>

Body:
Do this to get the data and the id:

<a href="#" id="12345" data-ng-click="ShowId($event)">

$scope.ShowId = function(event)
{
   $scope.v = event.target.attributes['data'].value;
   $scope.yourWantedId = event.target.id;
};


问:
Delayed Control Events
I have a weird delayed/off mapping event issue with a few controls within my UserControl.
The UserControl has 2 textboxes and 1 button. When I click on the button, nothing happens. When tab to the next control. The focus goes somewhere I can't see, but all the event for the button work there. I can hit the space bar and it fires with Button.click event. The same thing happens to the textboxes. I can type anything in the box I can see. Then hit tab, it goes to the box I can't see and all the events work. I went over all my code and I can't find anything that would suggest there are 2 controls on there..

Anyone have any suggestions on how to fix this??

答: make sure you are handling the click event of the button and not the LostFocus event. your description of the problem sounds like you're handling the lost focus event since the event fires when you hit tab to navigate away from the button</p>

Title: Delayed Control Events


问:
I do *not* want correct rounding for function exp
The GCC implementation of the C mathematical library on Debian systems has apparently an (IEEE 754-2008)-compliant implementation of the function exp, implying that rounding shall always be correct:

(from Wikipedia) The IEEE floating point standard guarantees that add, subtract, multiply, divide, fused multiply–add, square root, and floating point remainder will give the correctly rounded result of the infinite precision operation. No such guarantee was given in the 1985 standard for more complex functions and they are typically only accurate to within the last bit at best. However, the 2008 standard guarantees that conforming implementations will give correctly rounded results which respect the active rounding mode; implementation of the functions, however, is optional.

It turns out that I am encountering a case where this feature is actually hindering, because the exact result of the exp function is often nearly exactly at the middle between two consecutive double values (1), and then the program carries plenty of several further computations, losing up to a factor 400 (!) in speed: this was actually the explanation to my (ill-asked :-S) Question #43530011.

(1) More precisely, this happens when the argument of exp turns out to be of the form (2 k + 1) × 2-53 with k a rather small integer (like 242 for instance). In particular, the computations involved by pow (1. + x, 0.5) tend to call exp with such an argument when x is of the order of magnitude of 2-44.

Since implementations of correct rounding can be so much time-consuming in certain circumstances, I guess that the developers will also have devised a way to get a slightly less precise result (say, only up to 0.6 ULP or something like this) in a time which is (roughly) bounded for every value of the argument in a given range… (2)

… But how to do this??

(2) What I mean is that I just do not want that some exceptional values of the argument like (2 k + 1) × 2-53 would be much more time-consuming than most values of the same order of magnitude; but of course I do not mind if some exceptional values of the argument go much faster, or if large arguments (in absolute value) need a larger computation time.

Here is a minimal program showing the phenomenon:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
 {
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
   {
    a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
    c += exp (a); // Just to be sure that the compiler will actually perform the computation of exp (a).
   }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
 }
</code>```

Now after gcc -std=c99 program53.c -lm -o program53:

$ ./program53
1.000000e+06
Clock time spent: 13470008
$ ./program53
1.000000e+06
Clock time spent: 13292721
$ ./program53
1.000000e+06
Clock time spent: 13201616
```

<p>On the other hand, with <code>program52</code> and <code>program54</code> (got by replacing <code>0x20000000000000</code> by resp. <code>0x10000000000000</code> and <code>0x40000000000000</code>):</p>

<pre class="lang-none prettyprint-override"><code>$ ./program52
1.000000e+06
Clock time spent: 83594
$ ./program52
1.000000e+06
Clock time spent: 69095
$ ./program52
1.000000e+06
Clock time spent: 54694
$ ./program54
1.000000e+06
Clock time spent: 86151
$ ./program54
1.000000e+06
Clock time spent: 74209
$ ./program54
1.000000e+06
Clock time spent: 78612
</code>```

Beware, the phenomenon is implementation-dependent! Apparently, among the common implementations, only those of the Debian systems (including Ubuntu) show this phenomenon.

P.-S.: I hope that my question is not a duplicate: I searched for a similar question thoroughly without success, but maybe I did note use the relevant keywords… :-/

答:
To answer the general question on why the library functions are required to give correctly rounded results:

Floating-point is hard, and often times counterintuitive. Not every programmer has read what they should have. When libraries used to allow some slightly inaccurate rounding, people complained about the precision of the library function when their inaccurate computations inevitably went wrong and produced nonsense. In response, the library writers made their libraries exactly rounded, so now people cannot shift the blame to them.

In many cases, specific knowledge about floating point algorithms can produce considerable improvements to accuracy and/or performance, like in the testcase:

Taking the exp() of numbers very close to 0 in floating-point numbers is problematic, since the result is a number close to 1 while all the precision is in the difference to one, so most significant digits are lost. It is more precise (and significantly faster in this testcase) to compute exp(x) - 1 through the C math library function expm1(x). If the exp() itself is really needed, it is still much faster to do expm1(x) + 1.

A similar concern exists for computing log(1 + x), for which there is the function log1p(x).

A quick fix that speeds up the provided testcase:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
{
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
    {
      a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
      c += expm1 (a) + 1; // replace exp() with expm1() + 1
    }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
}
</code>```

For this case, the timings on my machine are thus:

Original code

1.000000e+06

Clock time spent: 21543338

Modified code

1.000000e+06

Clock time spent: 55076

Programmers with advanced knowledge about the accompanying trade-offs may sometimes consider using approximate results where the precision is not critical

For an experienced programmer it may be possible to write an approximative implementation of a slow function using methods like Newton-Raphson, Taylor or Maclaurin polynomials, specifically inexactly rounded specialty functions from libraries like Intel's MKL, AMD's AMCL, relaxing the floating-point standard compliance of the compiler, reducing precision to ieee754 binary32 (float), or a combination of these.

Note that a better description of the problem would enable a better answer.

Body:
The GCC implementation of the C mathematical library on Debian systems has apparently an (IEEE 754-2008)-compliant implementation of the function exp, implying that rounding shall always be correct:

(from Wikipedia) The IEEE floating point standard guarantees that add, subtract, multiply, divide, fused multiply–add, square root, and floating point remainder will give the correctly rounded result of the infinite precision operation. No such guarantee was given in the 1985 standard for more complex functions and they are typically only accurate to within the last bit at best. However, the 2008 standard guarantees that conforming implementations will give correctly rounded results which respect the active rounding mode; implementation of the functions, however, is optional.

It turns out that I am encountering a case where this feature is actually hindering, because the exact result of the exp function is often nearly exactly at the middle between two consecutive double values (1), and then the program carries plenty of several further computations, losing up to a factor 400 (!) in speed: this was actually the explanation to my (ill-asked :-S) Question #43530011.

(1) More precisely, this happens when the argument of exp turns out to be of the form (2 k + 1) × 2-53 with k a rather small integer (like 242 for instance). In particular, the computations involved by pow (1. + x, 0.5) tend to call exp with such an argument when x is of the order of magnitude of 2-44.

Since implementations of correct rounding can be so much time-consuming in certain circumstances, I guess that the developers will also have devised a way to get a slightly less precise result (say, only up to 0.6 ULP or something like this) in a time which is (roughly) bounded for every value of the argument in a given range… (2)

… But how to do this??

(2) What I mean is that I just do not want that some exceptional values of the argument like (2 k + 1) × 2-53 would be much more time-consuming than most values of the same order of magnitude; but of course I do not mind if some exceptional values of the argument go much faster, or if large arguments (in absolute value) need a larger computation time.

Here is a minimal program showing the phenomenon:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
 {
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
   {
    a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
    c += exp (a); // Just to be sure that the compiler will actually perform the computation of exp (a).
   }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
 }

Now after gcc -std=c99 program53.c -lm -o program53:

$ ./program53
1.000000e+06
Clock time spent: 13470008
$ ./program53
1.000000e+06
Clock time spent: 13292721
$ ./program53
1.000000e+06
Clock time spent: 13201616

On the other hand, with program52 and program54 (got by replacing 0x20000000000000 by resp. 0x10000000000000 and 0x40000000000000):

$ ./program52
1.000000e+06
Clock time spent: 83594
$ ./program52
1.000000e+06
Clock time spent: 69095
$ ./program52
1.000000e+06
Clock time spent: 54694
$ ./program54
1.000000e+06
Clock time spent: 86151
$ ./program54
1.000000e+06
Clock time spent: 74209
$ ./program54
1.000000e+06
Clock time spent: 78612

Beware, the phenomenon is implementation-dependent! Apparently, among the common implementations, only those of the Debian systems (including Ubuntu) show this phenomenon.

P.-S.: I hope that my question is not a duplicate: I searched for a similar question thoroughly without success, but maybe I did note use the relevant keywords… :-/

Body:
To answer the general question on why the library functions are required to give correctly rounded results:

Floating-point is hard, and often times counterintuitive. Not every programmer has read what they should have. When libraries used to allow some slightly inaccurate rounding, people complained about the precision of the library function when their inaccurate computations inevitably went wrong and produced nonsense. In response, the library writers made their libraries exactly rounded, so now people cannot shift the blame to them.

In many cases, specific knowledge about floating point algorithms can produce considerable improvements to accuracy and/or performance, like in the testcase:

Taking the exp() of numbers very close to 0 in floating-point numbers is problematic, since the result is a number close to 1 while all the precision is in the difference to one, so most significant digits are lost. It is more precise (and significantly faster in this testcase) to compute exp(x) - 1 through the C math library function expm1(x). If the exp() itself is really needed, it is still much faster to do expm1(x) + 1.

A similar concern exists for computing log(1 + x), for which there is the function log1p(x).

A quick fix that speeds up the provided testcase:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

int main (void)
{
  int i;
  double a, c;
  c = 0;
  clock_t start = clock ();
  for (i = 0; i < 1e6; ++i) // Doing a large number of times the same type of computation with different values, to smoothen random fluctuations.
    {
      a = (double) (1 + 2 * (rand () % 0x400)) / 0x20000000000000; // "a" has only a few significant digits, and its last non-zero digit is at (fixed-point) position 53.
      c += expm1 (a) + 1; // replace exp() with expm1() + 1
    }
  clock_t stop = clock ();
  printf ("%e\n", c); // Just to be sure that the compiler will actually perform the computation.
  printf ("Clock time spent: %d\n", stop - start);
  return 0;
}

For this case, the timings on my machine are thus:

Original code

1.000000e+06

Clock time spent: 21543338

Modified code

1.000000e+06

Clock time spent: 55076

Programmers with advanced knowledge about the accompanying trade-offs may sometimes consider using approximate results where the precision is not critical

For an experienced programmer it may be possible to write an approximative implementation of a slow function using methods like Newton-Raphson, Taylor or Maclaurin polynomials, specifically inexactly rounded specialty functions from libraries like Intel's MKL, AMD's AMCL, relaxing the floating-point standard compliance of the compiler, reducing precision to ieee754 binary32 (float), or a combination of these.

Note that a better description of the problem would enable a better answer.


问:
Global extension function in kotlin
Hey I want to make a class in kotlin that will hold all extension functions that I will use in a few places for example:

```<code>class DateUtils {
    //in this case I use jodatime
    fun Long.toDateTime() : DateTime = DateTime(this)
    fun String.toDateTime() : DateTime = DateTime.parse(this)
}

class SomeClassWithNoConnectionToDateUtils {
    fun handleDataFromServer(startDate: String) {
        someOtherFunction()
        //startDate knows about toDateTime function in DateUtils
        startDate.toDateTime().plusDays(4)
    }
}
</code>```

Is there a way to perform such operation

答:
Having your extensions inside a DateUtils class will make them available for use only inside the DateUtils class.

If you want the extensions to be global, you can just put them on the top level of a file, without putting them inside a class.

```<code>package com.something.extensions

fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)
</code>```

And then import them to use them elsewhere like so:

```<code>import com.something.extensions.toDateTime

val x = 123456L.toDateTime()
</code>```

Title: Global extension function in kotlin

Body:
Hey I want to make a class in kotlin that will hold all extension functions that I will use in a few places for example:

class DateUtils {
    //in this case I use jodatime
    fun Long.toDateTime() : DateTime = DateTime(this)
    fun String.toDateTime() : DateTime = DateTime.parse(this)
}

class SomeClassWithNoConnectionToDateUtils {
    fun handleDataFromServer(startDate: String) {
        someOtherFunction()
        //startDate knows about toDateTime function in DateUtils
        startDate.toDateTime().plusDays(4)
    }
}

Is there a way to perform such operation

Body:
Having your extensions inside a DateUtils class will make them available for use only inside the DateUtils class.

If you want the extensions to be global, you can just put them on the top level of a file, without putting them inside a class.

package com.something.extensions

fun Long.toDateTime() : DateTime = DateTime(this)
fun String.toDateTime() : DateTime = DateTime.parse(this)

And then import them to use them elsewhere like so:

import com.something.extensions.toDateTime

val x = 123456L.toDateTime()


问:
Logging User actions on Android
Is there a way to log a user's activity on an app. Basically, information like widget clicks, text inputs, swipes etc. I want these logs for my test case creation. </p>

答:
I would strongly recommend using Google Firebase in your Android projects for this.

Get started here on Firebase for Android.

In code, you can do crash reporting on exceptions as easy as:

```<code>catch (Exception e) {
    FirebaseCrash.report(e);
}
</code>```

And for general analytics, you can do something like this:

```<code>FirebaseAnalytics.getInstance(getApplicationContext())
    .logEvent("Something happened", someBundle);
</code>```

Title: Logging User actions on Android

Body:
I would strongly recommend using Google Firebase in your Android projects for this.

Get started here on Firebase for Android.

In code, you can do crash reporting on exceptions as easy as:

catch (Exception e) {
    FirebaseCrash.report(e);
}

And for general analytics, you can do something like this:

FirebaseAnalytics.getInstance(getApplicationContext())
    .logEvent("Something happened", someBundle);


问:
htacces - Redirect old url to new
I want to redirect old url to new with additional parameter

How can I prevent creating many youtube parameter ?

OLD: http://example.com/lady-gaga-monster

NEW: http://example.com/lady-gaga-monster-youtube

Currently htaccess

```<code>RewriteEngine on
RewriteRule ^(.*)-youtube?$ index.php?search=$1&source=youtube [L]
</code>```

I add this line

```<code>RewriteRule ^(.*)$ http://example.com//$1-youtube [R=301,L]
</code>```

And the result on browser
http://example.com/lady-gaga-monster-youtube-youtube-youtube-youtube-youtube

答:
You created an endless loop. You need to add a RewriteCOnd so that the rule gets only applied if the requested URL does not end in "-youtube":

```<code>RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# external rewrite
RewriteCond %{REQUEST_URI} !-youtube$
RewriteRule ^(.*)$ http://example.com/$1-youtube [R=301,L]
# internal rewrite
RewriteRule ^(.*)-youtube$ index.php?search=$1&source=youtube [L]
</code>```

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Title: htacces - Redirect old url to new

Body:
I want to redirect old url to new with additional parameter

How can I prevent creating many youtube parameter ?

OLD: http://example.com/lady-gaga-monster

NEW: http://example.com/lady-gaga-monster-youtube

Currently htaccess

RewriteEngine on
RewriteRule ^(.*)-youtube?$ index.php?search=$1&source=youtube [L]

I add this line

RewriteRule ^(.*)$ http://example.com//$1-youtube [R=301,L]

And the result on browser
http://example.com/lady-gaga-monster-youtube-youtube-youtube-youtube-youtube

Body:
You created an endless loop. You need to add a RewriteCOnd so that the rule gets only applied if the requested URL does not end in "-youtube":

RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# external rewrite
RewriteCond %{REQUEST_URI} !-youtube$
RewriteRule ^(.*)$ http://example.com/$1-youtube [R=301,L]
# internal rewrite
RewriteRule ^(.*)-youtube$ index.php?search=$1&source=youtube [L]

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


问:
PayPal API Returning code 10400: Order total is missing
I am trying to call the PayPal API command SetExpressCheckout.

The parameters that I am passing are the following (URL parameters):

```<code>METHOD=SetExpressCheckout
VERSION=2.7.1
PWD=PWD
USER=USER
SIGNATURE=SIG
PAYMENTREQUEST_0_AMT=1.36
PAYMENTREQUEST_0_PAYMENTACTION=Sale
RETURNURL=https://url/confirm/?id=ID
CANCELURL=https://url/cancel/?id=ID
PAYMENTREQUEST_0_CURRENCYCODE=EUR
REQCONFIRMSHIPPING=0
NOSHIPPING=1
L_PAYMENTREQUEST_0_NAME0=ITEM_NAME
L_PAYMENTREQUEST_0_AMT0=1.36
L_PAYMENTREQUEST_0_QTY0=1
L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital
BUTTONSOURCE=PP-ECWizard
</code>```

I have looked at numerous other posts that illustrate the same problem and from the answers it seems that I have added all the parameters that are required including the Order Total (PAYMENTREQUEST_0_AMT).

The API is returning the following (JSON):

```<code>{"TIMESTAMP":"2017-06-03T15:13:26Z","CORRELATIONID":"ID","ACK":"Failure","VERSION":"2.700000","BUILD":"34310309","L_ERRORCODE0":"10400","L_SHORTMESSAGE0":"Transaction refused because of an invalid argument. See additional error messages for details.","L_LONGMESSAGE0":"Order total is missing.","L_SEVERITYCODE0":"Error"}
</code>```

I appreciate any kind of help with the above.

Thank you!

答: The problem was that I was using a global variable for $version which was being overwritten. The API's error was due to the VERSION parameter passed. Correct version param was 98.</p>

Body:
I am trying to call the PayPal API command SetExpressCheckout.

The parameters that I am passing are the following (URL parameters):

METHOD=SetExpressCheckout
VERSION=2.7.1
PWD=PWD
USER=USER
SIGNATURE=SIG
PAYMENTREQUEST_0_AMT=1.36
PAYMENTREQUEST_0_PAYMENTACTION=Sale
RETURNURL=https://url/confirm/?id=ID
CANCELURL=https://url/cancel/?id=ID
PAYMENTREQUEST_0_CURRENCYCODE=EUR
REQCONFIRMSHIPPING=0
NOSHIPPING=1
L_PAYMENTREQUEST_0_NAME0=ITEM_NAME
L_PAYMENTREQUEST_0_AMT0=1.36
L_PAYMENTREQUEST_0_QTY0=1
L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital
BUTTONSOURCE=PP-ECWizard

I have looked at numerous other posts that illustrate the same problem and from the answers it seems that I have added all the parameters that are required including the Order Total (PAYMENTREQUEST_0_AMT).

The API is returning the following (JSON):

{"TIMESTAMP":"2017-06-03T15:13:26Z","CORRELATIONID":"ID","ACK":"Failure","VERSION":"2.700000","BUILD":"34310309","L_ERRORCODE0":"10400","L_SHORTMESSAGE0":"Transaction refused because of an invalid argument. See additional error messages for details.","L_LONGMESSAGE0":"Order total is missing.","L_SEVERITYCODE0":"Error"}

I appreciate any kind of help with the above.

Thank you!