问:
Record User Typing Exactly with time Difference in JavaScript?
I am trying to record user typing with an exact time difference letter by letter to replay it. I would like to do this in React with setTimeout function while replaying text is not one by one but this is an expected behaviour but I want one by one like a Queue System

Please don't suggest any plugins

Still not clear?

Code

```<code>import React,{Component} from 'react'

class Recorder extends Component{

    state = {
        text:"",
        viewText:[],
        typeInterval:0,
        typingText:[],
        oldTimestamp:0,

        textInput:"",
        delayedTime:0,

        replay:[]
    };

    globalTime = 0

    handleTextArea = e => {

        this.setState({
            textInput:e.target.value
        });
    };
    recordUserTyping = e => {
        this.setState({
            oldTimestamp:e.timeStamp
        });
        let timeDiff = e.timeStamp - this.state.oldTimestamp;
        let key = e.key
        let payload = {
            key,
            timeDiff
        };
        this.setState({
            typingText:[...this.state.typingText,payload],
        });

    };
    _startReplay = (i,data) => {

        let currentTimeDiff = data.timeDiff;

        return setTimeout(() => {
            this.setState({
                replay:[...this.state.replay,data.key]
            })
        },currentTimeDiff)

    };
    startReplay = e => {

        return this.state.typingText.map((data,i) => {
            return this._startReplay(i,data)
        })

    };
    playRecorded = () => {
      return this.state.replay.map(data => {
          return data
      })
    };
    render(){
        console.log(this.state.replay,"STate Changhe");
        return(
            <div>
                <textarea name="" id="" cols="30" rows="10" defaultValue={this.state.textInput} onKeyDown={this.recordUserTyping} onChange={this.handleTextArea} />
                <button onClick={this.startReplay}>Start</button>
                <p>{this.playRecorded()}</p>
            </div>
        )
    }
}

export default Recorder;
</code>```

Hope I will get some help?

答:
In startReplay you are executing a bunch of setTimeout calls all at once, whose delays are the various currentTimeDiff.

Now, currentTimeDiff is defined as e.timeStamp - this.state.oldTimestamp which is the time difference relative to the PREVIOUS keydown.

This means that you are actually replaying the "quickest" keydowns first.
To fix this, wait for the previous setTimeout to finish before executing the next one in the queue.

Finally, set 0 as the waiting time for the first keydown.

```<code>recordUserTyping = e => {
  this.setState({
    oldTimestamp: e.timeStamp
  });
  // NOTE HOW timeDiff === 0 FOR THE FIRST EVENT
  let timeDiff = this.state.oldTimestamp
   ? e.timeStamp - this.state.oldTimestamp
   : 0;
  let key = e.key
  let payload = {
    key,
    timeDiff
  };
  this.setState({
    typingText: [...this.state.typingText, payload],
  });

};

_startReplay = (i,data) => {

    let currentTimeDiff = data.timeDiff;

    return setTimeout(() => {
        this.setState({
            replay:[...this.state.replay,data.key]
        });
        if (i+1 < this.state.typingText.length) {
          this._startReplay(i+1, this.state.typingText[i+1]);
        }
    },currentTimeDiff)

};

startReplay = e => {
    if (this.state.typingText.length === 0) return;
    return this._startReplay(0,this.state.typingText[0]);
};
</code>```

See https://codesandbox.io/s/m752zrx9px for a fully working example

Body:
I am trying to record user typing with an exact time difference letter by letter to replay it. I would like to do this in React with setTimeout function while replaying text is not one by one but this is an expected behaviour but I want one by one like a Queue System

Please don't suggest any plugins

Still not clear?

Code

import React,{Component} from 'react'

class Recorder extends Component{

    state = {
        text:"",
        viewText:[],
        typeInterval:0,
        typingText:[],
        oldTimestamp:0,

        textInput:"",
        delayedTime:0,

        replay:[]
    };

    globalTime = 0

    handleTextArea = e => {

        this.setState({
            textInput:e.target.value
        });
    };
    recordUserTyping = e => {
        this.setState({
            oldTimestamp:e.timeStamp
        });
        let timeDiff = e.timeStamp - this.state.oldTimestamp;
        let key = e.key
        let payload = {
            key,
            timeDiff
        };
        this.setState({
            typingText:[...this.state.typingText,payload],
        });

    };
    _startReplay = (i,data) => {

        let currentTimeDiff = data.timeDiff;

        return setTimeout(() => {
            this.setState({
                replay:[...this.state.replay,data.key]
            })
        },currentTimeDiff)

    };
    startReplay = e => {

        return this.state.typingText.map((data,i) => {
            return this._startReplay(i,data)
        })

    };
    playRecorded = () => {
      return this.state.replay.map(data => {
          return data
      })
    };
    render(){
        console.log(this.state.replay,"STate Changhe");
        return(

                <textarea name="" id="" cols="30" rows="10" defaultValue={this.state.textInput} onKeyDown={this.recordUserTyping} onChange={this.handleTextArea} />
                <button onClick={this.startReplay}>Start</button>

{this.playRecorded()}

        )
    }
}

export default Recorder;

Hope I will get some help?

Body:
In startReplay you are executing a bunch of setTimeout calls all at once, whose delays are the various currentTimeDiff.

Now, currentTimeDiff is defined as e.timeStamp - this.state.oldTimestamp which is the time difference relative to the PREVIOUS keydown.

This means that you are actually replaying the "quickest" keydowns first.
To fix this, wait for the previous setTimeout to finish before executing the next one in the queue.

Finally, set 0 as the waiting time for the first keydown.

recordUserTyping = e => {
  this.setState({
    oldTimestamp: e.timeStamp
  });
  // NOTE HOW timeDiff === 0 FOR THE FIRST EVENT
  let timeDiff = this.state.oldTimestamp
   ? e.timeStamp - this.state.oldTimestamp
   : 0;
  let key = e.key
  let payload = {
    key,
    timeDiff
  };
  this.setState({
    typingText: [...this.state.typingText, payload],
  });

};

_startReplay = (i,data) => {

    let currentTimeDiff = data.timeDiff;

    return setTimeout(() => {
        this.setState({
            replay:[...this.state.replay,data.key]
        });
        if (i+1 < this.state.typingText.length) {
          this._startReplay(i+1, this.state.typingText[i+1]);
        }
    },currentTimeDiff)

};

startReplay = e => {
    if (this.state.typingText.length === 0) return;
    return this._startReplay(0,this.state.typingText[0]);
};

See https://codesandbox.io/s/m752zrx9px for a fully working example


来源: stackexchange

问:
How to implement lateinit properly with custom class objects for use in onCreate() in android avoiding 'Property getter or setter expected' error
I am trying to implement the integration of a Dialogflow (previously api.ai) agent with my Android app, using Kotlin. I checked other Q&A about kotlin lateinit and the onCreate() lifecycle in Android is ideal for late-init implementations, to avoid writing dirty code with null objects and corresponding !! and ? accesses in Kotlin. But I am running into the error of 'Property getter or setter expected' when trying to lateinint instances of self-defined class. Here is the code:

```<code>class AIApplication : Application() {

    private var activitiesCount: Int = 0

    var lateinit settingsManager: SettingsManager
        //private set

    private val isInForeground: Boolean
        get() = activitiesCount > 0

    override fun onCreate() {
        super.onCreate()

        settingsManager = SettingsManager(this)
    }
</code>```

Which gives me the error of 'Property getter or setter expected' on the lateinit settingsManager line. Here is the SettingsManager definition:

```<code>class SettingsManager(private val context: Context) {
    private val prefs: SharedPreferences

    private var useBluetooth: Boolean = false

    var isUseBluetooth: Boolean
        get() = useBluetooth
        set(useBluetooth) {
            this.useBluetooth = useBluetooth

            prefs.edit().putBoolean(PREF_USE_BLUETOOTH, useBluetooth).commit()
            val controller = (context.applicationContext as AIApplication).getBluetoothController()
            if (useBluetooth) {
                controller!!.start()
            } else {
                controller!!.stop()
            }
        }

    init {
        prefs = context.getSharedPreferences(SETTINGS_PREFS_NAME, Context.MODE_PRIVATE)

        useBluetooth = prefs.getBoolean(PREF_USE_BLUETOOTH, true)
    }

    companion object {

        private val SETTINGS_PREFS_NAME = "ai.api.APP_SETTINGS"
        private val PREF_USE_BLUETOOTH = "USE_BLUETOOTH"
    }

}
</code>```

So what is the proper way to do this? Do I need to make some changes to the SettingsManager class? Please explain the whole concept clearly.

答:
The lateinit declaration of the SettingsManager is wrong. Try this :

```<code>lateinit var settingsManager: SettingsManager
</code>```

instead of

```<code>var lateinit settingsManager: SettingsManager
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement the integration of a Dialogflow (previously api.ai) agent with my Android app, using Kotlin. I checked other Q&A about kotlin lateinit and the onCreate() lifecycle in Android is ideal for late-init implementations, to avoid writing dirty code with null objects and corresponding !! and ? accesses in Kotlin. But I am running into the error of 'Property getter or setter expected' when trying to lateinint instances of self-defined class. Here is the code:

class AIApplication : Application() {

    private var activitiesCount: Int = 0

    var lateinit settingsManager: SettingsManager
        //private set

    private val isInForeground: Boolean
        get() = activitiesCount > 0

    override fun onCreate() {
        super.onCreate()

        settingsManager = SettingsManager(this)
    }

Which gives me the error of 'Property getter or setter expected' on the lateinit settingsManager line. Here is the SettingsManager definition:

class SettingsManager(private val context: Context) {
    private val prefs: SharedPreferences

    private var useBluetooth: Boolean = false

    var isUseBluetooth: Boolean
        get() = useBluetooth
        set(useBluetooth) {
            this.useBluetooth = useBluetooth

            prefs.edit().putBoolean(PREF_USE_BLUETOOTH, useBluetooth).commit()
            val controller = (context.applicationContext as AIApplication).getBluetoothController()
            if (useBluetooth) {
                controller!!.start()
            } else {
                controller!!.stop()
            }
        }

    init {
        prefs = context.getSharedPreferences(SETTINGS_PREFS_NAME, Context.MODE_PRIVATE)

        useBluetooth = prefs.getBoolean(PREF_USE_BLUETOOTH, true)
    }

    companion object {

        private val SETTINGS_PREFS_NAME = "ai.api.APP_SETTINGS"
        private val PREF_USE_BLUETOOTH = "USE_BLUETOOTH"
    }

}

So what is the proper way to do this? Do I need to make some changes to the SettingsManager class? Please explain the whole concept clearly.

Body:
The lateinit declaration of the SettingsManager is wrong. Try this :

lateinit var settingsManager: SettingsManager

instead of

var lateinit settingsManager: SettingsManager

Hope this helps.


问:
Redirect Logged in user to specific page in wprdpress
I want to redirect users after the login to specific page called 'activity'. I have tried the Peter’s Login Redirect plugin but it just worked to the subscriber users although I have added all the roles in the plugin setting.

I have tried to add function to function.php in my theme but I can not find the right one.

答:
I hope this will help you for your specific page redirect, you want to do this:

```<code>function login_redirect( $redirect_to, $request, $user ){
    return home_url('your-page.php');
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );
</code>```

As you used this code...

```<code>function my_loginredirect( $redirect_to, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if( in_array('administrator', $user->roles)) {
         return admin_url();
        }
        else {
            return site_url('avtivity');
        }
}
add_filter('login_redirect', 'my_loginredirect', 10, 3);
</code>```

Body:
I hope this will help you for your specific page redirect, you want to do this:

function login_redirect( $redirect_to, $request, $user ){
    return home_url('your-page.php');
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

As you used this code...

function my_loginredirect( $redirect_to, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if( in_array('administrator', $user->roles)) {
         return admin_url();
        }
        else {
            return site_url('avtivity');
        }
}
add_filter('login_redirect', 'my_loginredirect', 10, 3);


问:
Display SQLserv result as text in PHP array
I have a query where I'm already pulling back the results from a Sql query via an array as below.

```<code><?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "<table><tr id=\"header\"><td><center>Status</center></td><tr>";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "<tr><td><b><center> " . $row["STATUS"] . "</center></b></td></tr>";
}

echo "</table>";

sqlsrv_close( $conn );
?>
</code>```

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

答:
change your while loop as below. check status number is available in $status or not if available then display its value otherwise display blank

```<code>while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    $status_str = isset($status[$row["STATUS"]])?$status[$row["STATUS"]]:"";
    echo "<tr><td><b><center> " . $status_str . "</center></b></td></tr>";
}
</code>```

Also change your array to(You forgot array keyword)

```<code>$status=array(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);
</code>```

Body:
I have a query where I'm already pulling back the results from a Sql query via an array as below.

<?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "

Status
";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "
 " . $row["STATUS"] . "
";
}

echo "
";

sqlsrv_close( $conn );
?>

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

Body:
change your while loop as below. check status number is available in $status or not if available then display its value otherwise display blank

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    $status_str = isset($status[$row["STATUS"]])?$status[$row["STATUS"]]:"";
    echo "<tr><td><b><center> " . $status_str . "</center></b></td></tr>";
}

Also change your array to(You forgot array keyword)

$status=array(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);


问:
Why is the Parse error is occured in this code? PHP
I am working on Magento project.There I have a controller which is a php file.I want to write a JavaScript function inside that php file.
This is the function which results in the error,

```<code> public function verifyPinAction()
         {
           $data = $this->getRequest()->getPost();
             echo "<script type='text/javascript'>
           var datastring=<?php echo $data['pin'];?>;
           $.ajax({
type: 'POST',
url: 'http://xxxxx.com/xxxxxx/ErrorProcessing1.php',
data : datastring,
//dataType: 'json',

success: function(html) {

   //alert(html);

   if(html=='wrong text entered')
  {
    <?php Mage::getSingleton('core/session')->addError('Invalid Pin Number');
                  $this->_redirect('enterpintoverify'); ?>
  }
  else{
    <?php Mage::getSingleton('core/session')->addSuccess('Your Email is verified');
                $this->_redirect('enterpintoverify');?>
  }

}
});
           </script>
           ";

         }
</code>```

It gives the following error

```<code>Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/xxxxx/public_html/newtradesdev/app/code/local/Customer/Register/controllers/IndexController.php on line 65
</code>```

Line 65 refers to
var datastring=<?php echo $data['pin'];?>;
Can someone tell me where have I gone wrong?

I have used xxxx marks beacause I am working on hosted site.Please skip the urls.

答:
Try using concatenate php code in your echo</p>

```<code>echo "<script type='text/javascript'>
                        var datastring=".$data['pin'].";
                        $.ajax({....
</code>```

Body:
I am working on Magento project.There I have a controller which is a php file.I want to write a JavaScript function inside that php file.
This is the function which results in the error,

 public function verifyPinAction()
         {
           $data = $this->getRequest()->getPost();
             echo "
           ";

         }

It gives the following error

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/xxxxx/public_html/newtradesdev/app/code/local/Customer/Register/controllers/IndexController.php on line 65

Line 65 refers to
var datastring=<?php echo $data['pin'];?>;
Can someone tell me where have I gone wrong?

I have used xxxx marks beacause I am working on hosted site.Please skip the urls.

Body:
Try using concatenate php code in your echo

echo "<script type='text/javascript'>
                        var datastring=".$data['pin'].";
                        $.ajax({....


问:
IOS - FCM Push Notification not received from firebase console
I have a native ios application and it enabled FCM. I have uploaded certificate to firebase and added GoogleService-Info.plist to my project from appdelegate

```<code> -(void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [FIRMessaging messaging].APNSToken = deviceToken;

    NSLog(@"FCM deviceToken : %@", deviceToken);
}
</code>```

And I have received token "FCM deviceToken : <076bc1b2 31493038
  08da0351 8d272982 d04f7171 46f6e619 31e89403 1457fc19>"

I have tried with this token in console, but it's showing failed.

This is what i am getting from firebase console

答:
hi @Anju You need to use

```<code>-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken (NSData *)deviceToken{
[FIRMessaging messaging].APNSToken = deviceToken;NSString *fcmToken = [FIRMessaging messaging].FCMToken;
NSLog(@"FCM deviceToken : %@", deviceToken);
}
</code>```

FCMtoken

Body:
I have a native ios application and it enabled FCM. I have uploaded certificate to firebase and added GoogleService-Info.plist to my project from appdelegate

 -(void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [FIRMessaging messaging].APNSToken = deviceToken;

    NSLog(@"FCM deviceToken : %@", deviceToken);
}

And I have received token "FCM deviceToken : <076bc1b2 31493038
  08da0351 8d272982 d04f7171 46f6e619 31e89403 1457fc19>"

I have tried with this token in console, but it's showing failed.

This is what i am getting from firebase console

Body:
hi @Anju You need to use

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken (NSData *)deviceToken{
[FIRMessaging messaging].APNSToken = deviceToken;NSString *fcmToken = [FIRMessaging messaging].FCMToken;
NSLog(@"FCM deviceToken : %@", deviceToken);
}

FCMtoken


问:
Delta sync logic
Looking for some high-level logic when performing a delta sync.
We have a system A which reads data from a system B - both are SQL DBs. Transfer of data between A and B can take 10 hours. Objects in system B give a Change Date value which tells us when the object changed

We now need to come up with a logic for delta sync - i.e. only capture objects from B which have changed since the last sync finished.

The current logic we have is something like this:

1) Sync data based on last sync date (change date from System B > Last sync date)

2) Store the date after sync has finished into last sync date

I think this logic doesn't capture any changes which might have happened during the sync itself.

Say the last sync date is 17th November 08:00 and I start a sync based on that time. This finishes at 17th November 20:00 and I store that value. Now, during that 10 hour sync some objects in system B changed with a Changedate of 17th November 16:00. In the next cycle, we will miss those objects since the "new" last sync date will be 17th November 20:00

Any suggestions on a high level logic on how to perform delta syncs?

Thanks

UPDATE: I saw a useful article but not sure what "Capture" means
https://community.boomi.com/docs/DOC-2784#jive_content_id_2_GOOD_Extract_by_Last_Modified_Date

Method #2

答:
Ah, think I got it

1) Store the start date of the sync into a variable (say x)

2) Perform the sync (use the value from step 3 to compare)

3) Store the value of x into permanent storage

Title: Delta sync logic


答:
It may happen due to parse error. Try concatenation for PHP Code.</p>

```<code>var datastring=".$data['pin'].";
</code>```

Title: Why is the Parse error is occured in this code? PHP

Body:
It may happen due to parse error. Try concatenation for PHP Code.

var datastring=".$data['pin'].";


问:
Pass path with spaces as parameter to bat file
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

```<code>:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )
</code>```

If I simply call the script I get the following error:

```<code>C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>
</code>```

答:
```<code>@echo off
setlocal enableextensions enabledelayedexpansion

if %1=="" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
                IF ERRORLEVEL ==2 GOTO CANCEL
                IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
        @echo !PWA_PATH! vs. %1
        goto end
    )
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1
</code>```

As VardhanDotNet mentions, %1 is enough.

"%1%" would add quotes around quotes: ""c:\Program Files\xxx"" which means:

'empty string' (""),

followed by 'c:\Program',

followed by the "unexpected here" 'Files\xxx',

followed by an empty string ("")

Note however that if you need to use PWA_PATH within your IF clause, you need to refer if as !PWA_PATH! (hence the enabledelayedexpansion as the beginning of the script)

Body:
I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?

In my code i have the following

:READ_PWA_PATH
    if "%1" == "" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
            IF ERRORLEVEL ==2 GOTO CANCEL
            IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
    )

If I simply call the script I get the following error:

C:\Projects\Setup>install.cmd "C:\program files (x86)"

-----------------
SETUP SCRIPT
-----------------

files was unexpected at this time.
C:\Projects\Setup>

Body:
@echo off
setlocal enableextensions enabledelayedexpansion

if %1=="" (
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
                IF ERRORLEVEL ==2 GOTO CANCEL
                IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
        @echo !PWA_PATH! vs. %1
        goto end
    )
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1

As VardhanDotNet mentions, %1 is enough.

"%1%" would add quotes around quotes: ""c:\Program Files\xxx"" which means:

'empty string' (""),

followed by 'c:\Program',

followed by the "unexpected here" 'Files\xxx',

followed by an empty string ("")

Note however that if you need to use PWA_PATH within your IF clause, you need to refer if as !PWA_PATH! (hence the enabledelayedexpansion as the beginning of the script)

OwnerDisplayName: VonC

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: VonC


问:
How do I get more columns of xticklabels
me very new to programming I have problem with bar chart.
Here is my bar chart:

```<code>import numpy as np
import matplotlib.pyplot as plt

N = 3

Start_means = (100, 50, 50)

Start_std = (2, 3, 4)

ind = np.arange(N)  # the x locations for the groups

width = 0.35       # the width of the bars

fig, ax = plt.subplots()

rects1 = ax.bar(ind, Start_means, width, color='xkcd:cyan', yerr=Start_std)

End_means = (80, 30, 30)

End_std = (3, 5, 2)

rects2 = ax.bar(ind + width, End_means, width, color='xkcd:red', yerr=End_std)

# add some text for labels, title and axes ticks

ax.set_ylabel('Available')

ax.set_title('Travel availability, by tour')

ax.set_xticks(ind + width / 2)

ax.set_xticklabels(('Italy', 'China', 'France',))
</code>```

How do I get multiple columns here? For example Underneath Italy I want "ID: 12345" for china "ID: 13579" and for France "ID: 24680"

```<code>ax.legend((rects1[0], rects2[0]), ('Start', 'End'))

def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '%d' % int(height),
            ha='center', va='bottom')

autolabel(rects1)

autolabel(rects2)

plt.show()
</code>```

答:
Unless for some reason you really want a new x-axis, I think this can be better done by just making a set of x-labels with an '\n' in between.

```<code>import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

Start_means = (100, 50, 50)
Start_std = (2, 3, 4)

End_means = (80, 30, 30)
End_std = (3, 5, 2)

fig, ax = plt.subplots()

rects1 = ax.bar(ind, Start_means, width, color='xkcd:cyan', yerr=Start_std)
rects2 = ax.bar(ind+width, End_means, width, color='xkcd:red', yerr=End_std)

ax.set_ylabel('Available')
ax.set_title('Travel availability, by tour')
ax.set_xticks(ind + width/2)

countries = ['Italy', 'China', 'France']
ids = ['ID:12345', 'ID:48900', 'ID:56789']

xlabels = []
for i, j in zip(countries, ids):
    xlabels.append(i + '\n' + j)

ax.set_xticklabels(xlabels)

plt.show()
</code>```

If you want to have a separate xaxis, see this answer.

Body:
me very new to programming I have problem with bar chart.
Here is my bar chart:

import numpy as np
import matplotlib.pyplot as plt

N = 3

Start_means = (100, 50, 50)

Start_std = (2, 3, 4)

ind = np.arange(N)  # the x locations for the groups

width = 0.35       # the width of the bars

fig, ax = plt.subplots()

rects1 = ax.bar(ind, Start_means, width, color='xkcd:cyan', yerr=Start_std)

End_means = (80, 30, 30)

End_std = (3, 5, 2)

rects2 = ax.bar(ind + width, End_means, width, color='xkcd:red', yerr=End_std)

# add some text for labels, title and axes ticks

ax.set_ylabel('Available')

ax.set_title('Travel availability, by tour')

ax.set_xticks(ind + width / 2)

ax.set_xticklabels(('Italy', 'China', 'France',))

How do I get multiple columns here? For example Underneath Italy I want "ID: 12345" for china "ID: 13579" and for France "ID: 24680"

ax.legend((rects1[0], rects2[0]), ('Start', 'End'))

def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
            '%d' % int(height),
            ha='center', va='bottom')

autolabel(rects1)

autolabel(rects2)

plt.show()

Body:
Unless for some reason you really want a new x-axis, I think this can be better done by just making a set of x-labels with an '\n' in between.

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

Start_means = (100, 50, 50)
Start_std = (2, 3, 4)

End_means = (80, 30, 30)
End_std = (3, 5, 2)

fig, ax = plt.subplots()

rects1 = ax.bar(ind, Start_means, width, color='xkcd:cyan', yerr=Start_std)
rects2 = ax.bar(ind+width, End_means, width, color='xkcd:red', yerr=End_std)

ax.set_ylabel('Available')
ax.set_title('Travel availability, by tour')
ax.set_xticks(ind + width/2)

countries = ['Italy', 'China', 'France']
ids = ['ID:12345', 'ID:48900', 'ID:56789']

xlabels = []
for i, j in zip(countries, ids):
    xlabels.append(i + '\n' + j)

ax.set_xticklabels(xlabels)

plt.show()

If you want to have a separate xaxis, see this answer.


问:
Sort groups by specific values in two columns
I would like to sort the dataset in order of each coloured curve, based on the x-axis value where the y-axis is approximately 0.5. The legend now is based on sequential order. But if you sort the data right, the legend should look like, [item 5, item 1, item 3, item 2, item 4].

```<code>library(mirt)
dat <- expand.table(LSAT7)
mod <- mirt(dat, 1)
plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
print(plt) #plot the object
str(plt) #find the data
plt$panel.args
pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
pltdata$item <- rep(colnames(dat), each = 50)

library(ggplot2)
ggplot(pltdata, aes(x, y, colour = item)) +
  geom_line() +
  ggtitle('ggplot2 Tracelines') +
  xlab(expression(theta)) +
  ylab(expression(P(theta))) +
  geom_hline(aes(yintercept = 0.5))
</code>```

答:
First of all you have to obtain the "x" values associated to the "y" values nearest to 0.5 (using dplyr) and after that, reorder the levels of the "item" variable. </p>

```<code>library(mirt)
dat <- expand.table(LSAT7)
mod <- mirt(dat, 1)
plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
print(plt) #plot the object
str(plt) #find the data
plt$panel.args
pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
pltdata$item <- rep(colnames(dat), each = 50)

pltdata$item<-as.factor(pltdata$item)
library(dplyr)
aux<-pltdata %>%
  group_by(item) %>%
  slice(which.min(abs(y-0.5)))

aux<-aux[order(aux$x),]
ord<-as.integer(aux$item)
pltdata$item = factor(pltdata$item,levels(pltdata$item)[ord])

library(ggplot2)
ggplot(pltdata, aes(x, y, colour = item)) +
  geom_line() +
  ggtitle('ggplot2 Tracelines') +
  xlab(expression(theta)) +
  ylab(expression(P(theta))) +
  geom_hline(aes(yintercept = 0.5))
</code>```

Body:
I would like to sort the dataset in order of each coloured curve, based on the x-axis value where the y-axis is approximately 0.5. The legend now is based on sequential order. But if you sort the data right, the legend should look like, [item 5, item 1, item 3, item 2, item 4].

library(mirt)
dat <- expand.table(LSAT7)
mod <- mirt(dat, 1)
plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
print(plt) #plot the object
str(plt) #find the data
plt$panel.args
pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
pltdata$item <- rep(colnames(dat), each = 50)

library(ggplot2)
ggplot(pltdata, aes(x, y, colour = item)) +
  geom_line() +
  ggtitle('ggplot2 Tracelines') +
  xlab(expression(theta)) +
  ylab(expression(P(theta))) +
  geom_hline(aes(yintercept = 0.5))

Body:
First of all you have to obtain the "x" values associated to the "y" values nearest to 0.5 (using dplyr) and after that, reorder the levels of the "item" variable.

library(mirt)
dat <- expand.table(LSAT7)
mod <- mirt(dat, 1)
plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
print(plt) #plot the object
str(plt) #find the data
plt$panel.args
pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
pltdata$item <- rep(colnames(dat), each = 50)

pltdata$item<-as.factor(pltdata$item)
library(dplyr)
aux<-pltdata %>%
  group_by(item) %>%
  slice(which.min(abs(y-0.5)))

aux<-aux[order(aux$x),]
ord<-as.integer(aux$item)
pltdata$item = factor(pltdata$item,levels(pltdata$item)[ord])

library(ggplot2)
ggplot(pltdata, aes(x, y, colour = item)) +
  geom_line() +
  ggtitle('ggplot2 Tracelines') +
  xlab(expression(theta)) +
  ylab(expression(P(theta))) +
  geom_hline(aes(yintercept = 0.5))


问:
jQuery make surrounding href select radio on click
I am trying to make the surrounding url, when clicked, select the child radio button inside. The href is blocked so it makes the whole line clickable.

```<code><a href="#" class="radio-click">
  <input type="radio" /> Test
</a>
</code>```

I'm not sure where to start.

Thanks

答:
The problem you have is moot as having an input inside an a element is not valid HTML. Imagine the input is clicked. Does that mean the user wants to set focus in the input to type, or does it mean they want to go to the link in the a element?

From the description of what you're trying to achieve it sounds like you want ot use a label element instead:

  <input type="radio" />
  Test
```
</div>
</div>
</p>

<p>Or alternatively:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="foo" />
<label for="foo">Test</label></code>```

Body:
I am trying to make the surrounding url, when clicked, select the child radio button inside. The href is blocked so it makes the whole line clickable.

  <input type="radio" /> Test

I'm not sure where to start.

Thanks

Body:
The problem you have is moot as having an input inside an a element is not valid HTML. Imagine the input is clicked. Does that mean the user wants to set focus in the input to type, or does it mean they want to go to the link in the a element?

From the description of what you're trying to achieve it sounds like you want ot use a label element instead:

<label>
  <input type="radio" />
  Test
</label>

Or alternatively:

<input type="radio" id="foo" />
<label for="foo">Test</label>


问:
Hover dosnt fit in my navigation because every icon has a different size
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

```<code>  <nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  <a class="icontitle" href="./fotowand.html">HOME</a>
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   <a class="icontitle" href="">STUDIEN-<br>INTERESSIERTE</a>
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   <a class="icontitle" href="">STUDIERENDE</a>
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   <a class="icontitle" href="">UNTERNEHMEN</a>
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   <a class="icontitle" href="">KONTAKT</a>
   <div class="after"></div>
 </div>
</nav>
</code>```

This is my CSS

```<code>  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}
</code>```

Navigation Screenshot

Navigation Screenshot

答:
```<code><div class="navItem" id="studierendeicon">
   <a class="icontitle" href="" >STUDIERENDE</a>
   <div class="after"></div>
 </div>

#studierendeicon{
background-image: url('./img/studierende.png')
background-position: center center; //change on needs
}
.navItem{
width: 80px;
}
</code>```

Let me know if it works

Body:
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

  HOME

   STUDIEN-
INTERESSIERTE

   STUDIERENDE

   UNTERNEHMEN

   KONTAKT

This is my CSS

  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}

Navigation Screenshot

Navigation Screenshot

Body:
<div class="navItem" id="studierendeicon">
   <a class="icontitle" href="" >STUDIERENDE</a>
   <div class="after"></div>
 </div>

#studierendeicon{
background-image: url('./img/studierende.png')
background-position: center center; //change on needs
}
.navItem{
width: 80px;
}

Let me know if it works


问:
SFSafariViewController blank in iOS 11/Xcode 9.0
I have a SFSafariViewController opening at the click of a button inside a UIActionSheet. It has been working fine and is still working fine on all the versions of iOS except iOS 11. Is there something they have changed regarding the SFSafariViewController in iOS 11 or in Xcode 9.0 that might have caused this issue?

UPDATE - So it seems like its Xcode 9.0 that is causing this issue. I have tried running it on different iOS versions and all of them seem to be giving this issue. It used to work fine when I ran it using Xcode 8.3.3, something I don't have anymore :(

Here's the code -

```<code>- (void)presentWebView:(NSString *)url {
url = [url stringByReplacingOccurrencesOfString:@" " withString:@"+"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:url];

if (URL) {
    if ([SFSafariViewController class] != nil) {
        SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:URL];
        sfvc.delegate = self;
        [self.tabBarController presentViewController:sfvc animated:YES completion:nil];
    } else {
        if (![[UIApplication sharedApplication] openURL:URL]) {
            NSLog(@"%@%@",@"Failed to open url:",[url description]);
        }
    }
} else {
    // will have a nice alert displaying soon.
}
</code>```

}

答:
I've managed to fix this in my code. I hope this helps anyone else with a similar problem.

I had the exact same problem as described here. I tried everything above and unfortunately nothing worked.

In my app there were different windows. The fix was to ensure the window that would show SFSafariViewController was 'key' before presenting it. For example:

```<code>class MyViewController: UIViewcontroller {
    func showSafariViewController() {
        // imagine we have 2 windows, one for 'normal' content (key window) and one for 'other' content. lets say we're showing the 'other' content window, and have hidden the 'normal' window. you can see the 'other' content window in the app, but it won't be the key window!
        let window = // get the 'other' content window

        // make sure we make it the key window before presenting safari
        window.makeKey()

        // now present safari and celebrate victory by triumphantly slurping on your hot black coffee
        let mySafariViewController = SFSafariViewController(...)
        self.present(mySafariViewController ...)
    }
}
</code>```

I suspect Apple are searching for a SFSafariViewController instance in the window UIApplication.shared.keyWindow. Perhaps they're adding a child view from somewhere else. In the documentation it states The user's activity and interaction with SFSafariViewController are not visible to your app, so perhaps it's the bug is something related to an added level of security https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller

Body:
I have a SFSafariViewController opening at the click of a button inside a UIActionSheet. It has been working fine and is still working fine on all the versions of iOS except iOS 11. Is there something they have changed regarding the SFSafariViewController in iOS 11 or in Xcode 9.0 that might have caused this issue?

UPDATE - So it seems like its Xcode 9.0 that is causing this issue. I have tried running it on different iOS versions and all of them seem to be giving this issue. It used to work fine when I ran it using Xcode 8.3.3, something I don't have anymore :(

Here's the code -

- (void)presentWebView:(NSString *)url {
url = [url stringByReplacingOccurrencesOfString:@" " withString:@"+"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:url];

if (URL) {
    if ([SFSafariViewController class] != nil) {
        SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:URL];
        sfvc.delegate = self;
        [self.tabBarController presentViewController:sfvc animated:YES completion:nil];
    } else {
        if (![[UIApplication sharedApplication] openURL:URL]) {
            NSLog(@"%@%@",@"Failed to open url:",[url description]);
        }
    }
} else {
    // will have a nice alert displaying soon.
}

}

Body:
I've managed to fix this in my code. I hope this helps anyone else with a similar problem.

I had the exact same problem as described here. I tried everything above and unfortunately nothing worked.

In my app there were different windows. The fix was to ensure the window that would show SFSafariViewController was 'key' before presenting it. For example:

class MyViewController: UIViewcontroller {
    func showSafariViewController() {
        // imagine we have 2 windows, one for 'normal' content (key window) and one for 'other' content. lets say we're showing the 'other' content window, and have hidden the 'normal' window. you can see the 'other' content window in the app, but it won't be the key window!
        let window = // get the 'other' content window

        // make sure we make it the key window before presenting safari
        window.makeKey()

        // now present safari and celebrate victory by triumphantly slurping on your hot black coffee
        let mySafariViewController = SFSafariViewController(...)
        self.present(mySafariViewController ...)
    }
}

I suspect Apple are searching for a SFSafariViewController instance in the window UIApplication.shared.keyWindow. Perhaps they're adding a child view from somewhere else. In the documentation it states The user's activity and interaction with SFSafariViewController are not visible to your app, so perhaps it's the bug is something related to an added level of security https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller


问:
How to fix 'Microsoft.NETCore.App', version '1.1.2' was not found?
I am seeing this error when I try to run unit tests:

Testhost process exited with error: It was not possible to find any
  compatible framework version The specified framework
  'Microsoft.NETCore.App', version '1.1.2' was not found.
    - Check application dependencies and target a framework version installed at:
        \
    - Alternatively, install the framework version '1.1.2'.

How to fix it?

答: Installing DotNetCore.1.0.5_1.1.2-WindowsHosting solved the problem for me and my collegues.</p>


问:
Union two select statements with NOT IN - Oracle
I have two select statements and i need to output 1st select records and the other should receive the records that not output by select 1. 2nd select should not contain the data of select 1. here is my code

```<code>select b.tcl_tcserno, b.tcl_clmcode, b.tcl_clname, c.prd_desc, e.eqt_desc,
         b.tcl_conamount, b.tcl_intrate, f.numirp_minrate, f.dblirp_intrate,
         b.tcl_prdcode, e.eqt_type
    FROM leaseinfo.trn_ira_intreductapproval a,
         leaseinfo.tbltrialcalculation b,
         corpinfo.tblproduct c,
         leaseinfo.tbltrialequipment d,
         leaseinfo.tblequipmenttype e,
         leaseinfo.ref_irp_inerestratepara f
   WHERE a.numira_tcserno = b.tcl_tcserno
     AND b.tcl_prdcode = c.prd_code
     AND b.tcl_tcserno = d.teq_tcserno
     AND b.tcl_prdcode = e.eqt_prdcode
     AND d.teq_eqttype = e.eqt_type
     AND b.tcl_prdcode = f.strirp_productcode
     AND d.teq_eqttype = f.strirp_eqpttype
     AND a.strira_status = 'E'
     AND (f.numirp_minrate - b.tcl_intrate)<
              (SELECT g.intds_uplim
                       FROM glinfo.ref_tblintratefordesignation g
                      WHERE g.intds_designation IN (
                                        SELECT s.str_off_type
                                        FROM dpg.inf_responsible_maildetails s
                                        WHERE s.str_user_code = '10020336'))
     and  (b.tcl_prdcode='LE' OR b.tcl_prdcode='UV' OR b.tcl_prdcode='HP')
      and (e.EQT_TYPE='2' OR e.EQT_TYPE='9' OR e.EQT_TYPE='15' OR e.EQT_TYPE='17' OR e.EQT_TYPE='21' OR e.EQT_TYPE='23' OR e.EQT_TYPE='25' OR e.EQT_TYPE='28' OR e.EQT_TYPE='30')
ORDER BY b.tcl_tcserno

union all

SELECT   b.tcl_tcserno, b.tcl_clmcode, b.tcl_clname, c.prd_desc, e.eqt_desc,
         b.tcl_conamount, b.tcl_intrate, f.numirp_minrate, f.dblirp_intrate,
         b.tcl_prdcode, e.eqt_type
    FROM leaseinfo.trn_ira_intreductapproval a,
         leaseinfo.tbltrialcalculation b,
         corpinfo.tblproduct c,
         leaseinfo.tbltrialequipment d,
         leaseinfo.tblequipmenttype e,
         leaseinfo.ref_irp_inerestratepara f
   WHERE a.numira_tcserno = b.tcl_tcserno
     AND b.tcl_prdcode = c.prd_code
     AND b.tcl_tcserno = d.teq_tcserno
     AND b.tcl_prdcode = e.eqt_prdcode
     AND d.teq_eqttype = e.eqt_type
     AND b.tcl_prdcode = f.strirp_productcode
     AND d.teq_eqttype = f.strirp_eqpttype
     AND a.strira_status = 'E'
ORDER BY b.tcl_tcserno
</code>```

i think not in will work with this. but i don't have an idea to do with it. any help would be appreciated

答:
This will do job using set notation.  Assumes same columns in both queries to work </p>

```<code>With dat1 as (....),
     Dat2 as (....)
Select * from dat1 Union all
 (
  Select * from dat2 except select * from dat1
 )
</code>```

Body:
I have two select statements and i need to output 1st select records and the other should receive the records that not output by select 1. 2nd select should not contain the data of select 1. here is my code

select b.tcl_tcserno, b.tcl_clmcode, b.tcl_clname, c.prd_desc, e.eqt_desc,
         b.tcl_conamount, b.tcl_intrate, f.numirp_minrate, f.dblirp_intrate,
         b.tcl_prdcode, e.eqt_type
    FROM leaseinfo.trn_ira_intreductapproval a,
         leaseinfo.tbltrialcalculation b,
         corpinfo.tblproduct c,
         leaseinfo.tbltrialequipment d,
         leaseinfo.tblequipmenttype e,
         leaseinfo.ref_irp_inerestratepara f
   WHERE a.numira_tcserno = b.tcl_tcserno
     AND b.tcl_prdcode = c.prd_code
     AND b.tcl_tcserno = d.teq_tcserno
     AND b.tcl_prdcode = e.eqt_prdcode
     AND d.teq_eqttype = e.eqt_type
     AND b.tcl_prdcode = f.strirp_productcode
     AND d.teq_eqttype = f.strirp_eqpttype
     AND a.strira_status = 'E'
     AND (f.numirp_minrate - b.tcl_intrate)<
              (SELECT g.intds_uplim
                       FROM glinfo.ref_tblintratefordesignation g
                      WHERE g.intds_designation IN (
                                        SELECT s.str_off_type
                                        FROM dpg.inf_responsible_maildetails s
                                        WHERE s.str_user_code = '10020336'))
     and  (b.tcl_prdcode='LE' OR b.tcl_prdcode='UV' OR b.tcl_prdcode='HP')
      and (e.EQT_TYPE='2' OR e.EQT_TYPE='9' OR e.EQT_TYPE='15' OR e.EQT_TYPE='17' OR e.EQT_TYPE='21' OR e.EQT_TYPE='23' OR e.EQT_TYPE='25' OR e.EQT_TYPE='28' OR e.EQT_TYPE='30')
ORDER BY b.tcl_tcserno

union all

SELECT   b.tcl_tcserno, b.tcl_clmcode, b.tcl_clname, c.prd_desc, e.eqt_desc,
         b.tcl_conamount, b.tcl_intrate, f.numirp_minrate, f.dblirp_intrate,
         b.tcl_prdcode, e.eqt_type
    FROM leaseinfo.trn_ira_intreductapproval a,
         leaseinfo.tbltrialcalculation b,
         corpinfo.tblproduct c,
         leaseinfo.tbltrialequipment d,
         leaseinfo.tblequipmenttype e,
         leaseinfo.ref_irp_inerestratepara f
   WHERE a.numira_tcserno = b.tcl_tcserno
     AND b.tcl_prdcode = c.prd_code
     AND b.tcl_tcserno = d.teq_tcserno
     AND b.tcl_prdcode = e.eqt_prdcode
     AND d.teq_eqttype = e.eqt_type
     AND b.tcl_prdcode = f.strirp_productcode
     AND d.teq_eqttype = f.strirp_eqpttype
     AND a.strira_status = 'E'
ORDER BY b.tcl_tcserno

i think not in will work with this. but i don't have an idea to do with it. any help would be appreciated

Body:
This will do job using set notation.  Assumes same columns in both queries to work

With dat1 as (....),
     Dat2 as (....)
Select * from dat1 Union all
 (
  Select * from dat2 except select * from dat1
 )


问:
Why we have to do a regular commit immediately after conflicts resolved in Git?
Why we have to do a regular commit immediately after conflicts resolved in Git?

What if I modify some other files after conflicts resolved, then commit them together?

What is the difference?

答:
There is no "difference".

If a merge ends up with one or more conflicts it merges as much as possible and then halts, informing you about these conflicts.

It is then your task to commit the final merge commit once you've resolved those conflicts.

The reason for this is that the merge conflict resolution step is manually performed by invoking other git commands, external conflict resolution tools, inspecting the files manually and visually, etc. It's not an interactive process and as such git doesn't hang around waiting for you to complete resolving the conflicts before it commits as normal. It simply says "I stop here, commit when you're done".

If, in addition to resolving these conflicts, you change the files on disk further and adds those changes and then commit, it will just commit everything together. There's nothing special about this.

A merge commit is like any other regular commit except that it has (usually) two parents instead of one, other than that it is an entirely regular commit with all the bells and whistles. The fact that it was a merge operation performed by git that prepared all the changes the commit introduced is just a detail, you can construct a merge commit yourself 100% manually by staging the right changes and telling git to commit with two parents.

As such, the difference between you modifying the files further vs. you don't do this is that the merge will contain more changes vs. only what git + the conflict resolution added.

Nothing more, nothing less.


问:
Windows service with NHibernate is increasing used memory
I'm debugging an existing windows service (written in C#) that needs to be manually restarted every few months because it keeps eating memory.

The service is not very complicated. It requests a json file from an external server, which holds products.
Next it parses this json file into a list of products.
For each of these products it is checking if this product already exists in the database. If not it will be added if it does exists the properties will be updated.

The database is a PostgreSQL database and we use NHibernate v3.2.0 as ORM.

I've been using JetBrains DotMemory to profile the service when it runs:

The service starts and after 30s it starts doing its work. SnapShot #1 is made before the first run.
Snapshot #6 was made after the 5th run.
The other snapshots are also made after a run.
As you can see after each run the number of objects increases with approx. 60k and the memory used increases with a few MBs after every run.

Looking closer at Snapshot #6, shows the retained size is mostly used by NHibernate session objects:

Here's my OnStart code:

```<code>try
{
    // Trying to fix certificate errors:
    ServicePointManager.ServerCertificateValidationCallback += delegate
    {
        _logger.Debug("Cert validation work around");
        return true;
    };

    _timer = new Timer(_interval)
    {
        AutoReset = false // makes it fire only once, restart when work is done to prevent multiple runs
    };
    _timer.Elapsed += DoServiceWork;
    _timer.Start();
}
catch (Exception ex)
{
    _logger.Error("Exception in OnStart: " + ex.Message, ex);
}
</code>```

And my DoServiceWork:

```<code>try
{
    // Call execute
    var processor = new SAPProductProcessor();
    processor.Execute();
}
catch (Exception ex)
{
    _logger.Error("Error in DoServiceWork", ex);
}
finally
{
    // Next round:
    _timer.Start();
}
</code>```

In SAPProductProcessor I use two db calls. Both in a loop.
I loop through all products from the JSON file and check if the product is already in the table using the product code:

```<code>ProductDto dto;
using (var session = SessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        var criteria = session.CreateCriteria<ProductDto>();
        criteria.Add(Restrictions.Eq("Code", code));
        dto = criteria.UniqueResult<ProductDto>();
        transaction.Commit();
    }
}
return dto;
</code>```

And when the productDto is updated I save it using:

```<code>using (var session = SessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        session.SaveOrUpdate(item);
        transaction.Commit();
    }
}
</code>```

I'm not sure how to change the code above to stop increasing the memory and the number of object.

I already tried using var session = SessionFactory.GetCurrentSession(); instead of using (var session = SessionFactory.OpenSession()) but that didn't stop the increase of memory.

Update

In the constructor of my data access class MultiSessionFactoryProvider sessionFactoryProvider is injected. And the base class is called with : base(sessionFactoryProvider.GetFactory("data")). This base class has a method BeginSession:

```<code>ISession session = _sessionFactory.GetCurrentSession();
if (session == null)
{
  session = _sessionFactory.OpenSession();
  ThreadLocalSessionContext.Bind(session);
}
</code>```

And a EndSession:

```<code>ISession session = ThreadLocalSessionContext.Unbind(_sessionFactory);
if (session != null)
{
    session.Close();
}
</code>```

In my data access class I call base.BeginSession at the start and base.EndSession at then end.

答:
The suggestion about the Singleton made me have a closer look at my data access class.

I thought when creating this class with every run would free the NHibernate memory when it runs out of scope. I even added some dispose call in the class' destructor. But that didn't work, or more likely I'm not doing it correctly.
I now save my data access class in a static field and re-use it. Now my memory doesn't increase anymore and more important the number of open objects stay the same. I just run the service using DotMemory again for over an hour calling the run around 150 times and the memory of the last snapshot is still around 105MB and the number of object is still 117k and my SessionFactory dictionary is now just 4MB instead of 150*4MB.

Body:
I'm debugging an existing windows service (written in C#) that needs to be manually restarted every few months because it keeps eating memory.

The service is not very complicated. It requests a json file from an external server, which holds products.
Next it parses this json file into a list of products.
For each of these products it is checking if this product already exists in the database. If not it will be added if it does exists the properties will be updated.

The database is a PostgreSQL database and we use NHibernate v3.2.0 as ORM.

I've been using JetBrains DotMemory to profile the service when it runs:

The service starts and after 30s it starts doing its work. SnapShot #1 is made before the first run.
Snapshot #6 was made after the 5th run.
The other snapshots are also made after a run.
As you can see after each run the number of objects increases with approx. 60k and the memory used increases with a few MBs after every run.

Looking closer at Snapshot #6, shows the retained size is mostly used by NHibernate session objects:

Here's my OnStart code:

try
{
    // Trying to fix certificate errors:
    ServicePointManager.ServerCertificateValidationCallback += delegate
    {
        _logger.Debug("Cert validation work around");
        return true;
    };

    _timer = new Timer(_interval)
    {
        AutoReset = false // makes it fire only once, restart when work is done to prevent multiple runs
    };
    _timer.Elapsed += DoServiceWork;
    _timer.Start();
}
catch (Exception ex)
{
    _logger.Error("Exception in OnStart: " + ex.Message, ex);
}

And my DoServiceWork:

try
{
    // Call execute
    var processor = new SAPProductProcessor();
    processor.Execute();
}
catch (Exception ex)
{
    _logger.Error("Error in DoServiceWork", ex);
}
finally
{
    // Next round:
    _timer.Start();
}

In SAPProductProcessor I use two db calls. Both in a loop.
I loop through all products from the JSON file and check if the product is already in the table using the product code:

ProductDto dto;
using (var session = SessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        var criteria = session.CreateCriteria<ProductDto>();
        criteria.Add(Restrictions.Eq("Code", code));
        dto = criteria.UniqueResult<ProductDto>();
        transaction.Commit();
    }
}
return dto;

And when the productDto is updated I save it using:

using (var session = SessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        session.SaveOrUpdate(item);
        transaction.Commit();
    }
}

I'm not sure how to change the code above to stop increasing the memory and the number of object.

I already tried using var session = SessionFactory.GetCurrentSession(); instead of using (var session = SessionFactory.OpenSession()) but that didn't stop the increase of memory.

Update

In the constructor of my data access class MultiSessionFactoryProvider sessionFactoryProvider is injected. And the base class is called with : base(sessionFactoryProvider.GetFactory("data")). This base class has a method BeginSession:

ISession session = _sessionFactory.GetCurrentSession();
if (session == null)
{
  session = _sessionFactory.OpenSession();
  ThreadLocalSessionContext.Bind(session);
}

And a EndSession:

ISession session = ThreadLocalSessionContext.Unbind(_sessionFactory);
if (session != null)
{
    session.Close();
}

In my data access class I call base.BeginSession at the start and base.EndSession at then end.


问:
Inserting Signature into Outlook email from Excel VBA
I am trying to automate some emails using VBA for Excel. Everything so far is fine, except trying to keep my signature in the email.

Once you tell VBA to create a new email, it will already contain your default signature. This can be seen if you try Outmail.Display. However if you overwrite the .HTMLBody property, it will be deleted.

My simple attempt was to save the contents of .HTMLBody to a signature (string), and then reassign it to .HTMLBody just to test it out. However the resulting email will be void of any signature.

Code to copy and re-insert the signature:

```<code>Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem

Dim signature As String

Set myOlApp = CreateObject("Outlook.Application")
Set Outmail = myOlApp.CreateItem(0)

signature = Outmail.HTMLBody
Outmail.HTMLBody = signature

Outmail.Display
</code>```

Code to show that signature is automatically inserted:

```<code>Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem
Set myOlApp = CreateObject("Outlook.Application")
Set Outmail = myOlApp.CreateItem(0)
Outmail.Display
</code>```

Edit: I tried replacing .HTMLBody with .Body. That works, but obviously takes out the HTML formatting of the signature

Edit 2: The code works on my friend's computer but not on mine

答:
I solved that issue with this trick:

```<code>Set myOutlook = CreateObject("Outlook.Application")
Set tempMail = myOutlook.CreateItem(olMailItem)

With tempMail
  ' Trick to preserve Outlook default signature
  ' MailItem need to be displayed to be "fully created" as object (maybe VBA bug)

  .Display
  HTMLBody = .HTMLBody
  .Close olDiscard

  ' --- Trick to split HTMLBody into Head and Signature ---
  ' Search for the position of the tag before signature
  bodyTag = "<body"
  PosBody = InStr(HTMLBody, bodyTag)
  pTag = "<o:p>"
  PosSignature = InStr(PosBody, HTMLBody, pTag)

  Head = Left(HTMLBody, PosSignature - 1)
  Signature = Right(HTMLBody, Len(HTMLBody) - PosSignature + 1)

End With
</code>```

Then you can simply put your HTML text between Head and Signature:

```<code>Set myOutlook = CreateObject("Outlook.Application")
Set myMail = myOutlook.CreateItem(olMailItem)

With myMail
  .To = Recipients
  .Subject = Subject
  .CC = CC
  .HTMLBody = Head & "Here the HTML text of your mail" & Signature
End With
</code>```

I think it's a sort of VBA bug: if you don't use the .Display method, the MailItem object is not "fully" created.

Try to place a brakepoint and look at ?mymail.HTMLbody values on Immediate Window (Ctrl + G) before and after the .Display method line....

You can also obtain the same simply expanding mymail object in the Locals Window!

Body:
I am trying to automate some emails using VBA for Excel. Everything so far is fine, except trying to keep my signature in the email.

Once you tell VBA to create a new email, it will already contain your default signature. This can be seen if you try Outmail.Display. However if you overwrite the .HTMLBody property, it will be deleted.

My simple attempt was to save the contents of .HTMLBody to a signature (string), and then reassign it to .HTMLBody just to test it out. However the resulting email will be void of any signature.

Code to copy and re-insert the signature:

Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem

Dim signature As String

Set myOlApp = CreateObject("Outlook.Application")
Set Outmail = myOlApp.CreateItem(0)

signature = Outmail.HTMLBody
Outmail.HTMLBody = signature

Outmail.Display

Code to show that signature is automatically inserted:

Dim myOlApp As Outlook.Application
Dim MyItem As Outlook.MailItem
Set myOlApp = CreateObject("Outlook.Application")
Set Outmail = myOlApp.CreateItem(0)
Outmail.Display

Edit: I tried replacing .HTMLBody with .Body. That works, but obviously takes out the HTML formatting of the signature

Edit 2: The code works on my friend's computer but not on mine

Body:
I solved that issue with this trick:

Set myOutlook = CreateObject("Outlook.Application")
Set tempMail = myOutlook.CreateItem(olMailItem)

With tempMail
  ' Trick to preserve Outlook default signature
  ' MailItem need to be displayed to be "fully created" as object (maybe VBA bug)

  .Display
  HTMLBody = .HTMLBody
  .Close olDiscard

  ' --- Trick to split HTMLBody into Head and Signature ---
  ' Search for the position of the tag before signature
  bodyTag = "<body"
  PosBody = InStr(HTMLBody, bodyTag)
  pTag = "<o:p>"
  PosSignature = InStr(PosBody, HTMLBody, pTag)

  Head = Left(HTMLBody, PosSignature - 1)
  Signature = Right(HTMLBody, Len(HTMLBody) - PosSignature + 1)

End With

Then you can simply put your HTML text between Head and Signature:

Set myOutlook = CreateObject("Outlook.Application")
Set myMail = myOutlook.CreateItem(olMailItem)

With myMail
  .To = Recipients
  .Subject = Subject
  .CC = CC
  .HTMLBody = Head & "Here the HTML text of your mail" & Signature
End With

I think it's a sort of VBA bug: if you don't use the .Display method, the MailItem object is not "fully" created.

Try to place a brakepoint and look at ?mymail.HTMLbody values on Immediate Window (Ctrl + G) before and after the .Display method line....

You can also obtain the same simply expanding mymail object in the Locals Window!


问:
How can I modify this code?
```<code>from itertools import product
for d in product(range(10), repeat=4):
   if 7 in d :
      print(d)
</code>```

This is supposed to print all numbers that have number 7, but what if I want the number that contains exactly one 7?

答:
Here is one approach:

for each d count the number of 7s, and select the ones that contain exactly one. (thanks @MrXcoder for the assist in the comments)

```<code>from itertools import product
for d in product(range(10), repeat=4):
    if d.count(7) == 1:
        print(d)
</code>```

Title: How can I modify this code?

Body:
from itertools import product
for d in product(range(10), repeat=4):
   if 7 in d :
      print(d)

This is supposed to print all numbers that have number 7, but what if I want the number that contains exactly one 7?

Body:
Here is one approach:

for each d count the number of 7s, and select the ones that contain exactly one. (thanks @MrXcoder for the assist in the comments)

from itertools import product
for d in product(range(10), repeat=4):
    if d.count(7) == 1:
        print(d)


问:
Issues with session in Codeigniter3 framework
My website works properly in localhost, however, it sometimes give this error when I open it in live https://wtf.az/test . Where can be the problem?

答:
I have the same problem too so do the following. In the config.php file you MUST set sess_save_path to a valid path. It was initially set to NULL.

Now the sessions are being saved in this folder and can be unlinked when needed to

change application > config > config.php

```<code>$config['sess_save_path'] =  BASEPATH . 'cache/';
</code>```

Please give the permission to 777 on cache folder, so when cache write on that folder it will accessible.

Body:
I have the same problem too so do the following. In the config.php file you MUST set sess_save_path to a valid path. It was initially set to NULL.

Now the sessions are being saved in this folder and can be unlinked when needed to

change application > config > config.php

$config['sess_save_path'] =  BASEPATH . 'cache/';

Please give the permission to 777 on cache folder, so when cache write on that folder it will accessible.


问:
How to verify a signature in .net generated in Android
The problem is the following:

I generate the key in Android (Xamarin.Droid):

```<code> public IPublicKey CreateKey(string keyID)
 {
    /*KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
             KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(
                    "key1",
                    KeyProperties.PURPOSE_SIGN)
                    .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
                    .build());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Signature signature = Signature.getInstance("SHA256withRSA/PSS");
    signature.initSign(keyPair.getPrivate());

     // The key pair can also be obtained from the Android Keystore any time as follows:
     KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
                keyStore.load(null);
                PrivateKey privateKey = (PrivateKey)keyStore.getKey("key1", null);
                PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();*/

    //App.Current.MainPage.DisplayAlert("Info", "Creating a new key pair", "Ok");
    // UTILIZANDO RSA
    KeyPairGenerator kpg =
    KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);
    kpg.Initialize(
        new KeyGenParameterSpec.Builder(keyID,
        KeyStorePurpose.Sign)
        .SetSignaturePaddings(KeyProperties.SignaturePaddingRsaPss)
        .SetDigests(KeyProperties.DigestSha1)
        .Build()
        );

    KeyPair keyPair = kpg.GenerateKeyPair();

    Log.Debug(TAG, "New key created for fingerprint authentication");

    return keyPair.Public;
}
</code>```

Then i generate a signature:

```<code>    KeyStore.PrivateKeyEntry PKentry =
    (KeyStore.PrivateKeyEntry)_keystore.GetEntry(keyID, null);
    IPublicKey pk = (IPublicKey)PKentry.Certificate.PublicKey;
    //this.pk = pk;
    privKey = PKentry.PrivateKey;

    //cipher.Init(Cipher.EncryptMode, privKey);
    //byte[] output = cipher.DoFinal(Encoding.UTF8.GetBytes(input));
    //String s = new string(cipher.DoFinal(input));

    // signature
    Signature sig = Signature.GetInstance("SHA1withRSA/PSS");
    sig.InitSign(privKey);
    byte[] inputDataToSign = Encoding.UTF8.GetBytes(input);
    sig.Update(inputDataToSign);
    byte[] signatureBytes = sig.Sign();
</code>```

And i send the key and the signature to a ASP.net wep API 2 server.
Client side response generation:

```<code> RegistrationResponse registrationResponse = new RegistrationResponse();
 string fcparams = Utils.Base64Encode(JsonConvert.SerializeObject(finalChallengeParams));
  registrationResponse.fcParams = fcparams;
  byte[] signedData = sign(fcparams, registrationRequest.username, facetID);
 registrationResponse.signedData = signedData;
 registrationResponse.Base64key = convertPublicKeyToString(publicKey);
 ...
 ...
private string convertPublicKeyToString(IPublicKey publicKey)
{
    string publicKeyString = Base64.EncodeToString(publicKey.GetEncoded(), 0);

 return publicKeyString;
  }
</code>```

I send it using Refit Nugget.
And this is the code i use when i receive the HTTPRequest on server side:

```<code>[Route("regResponse/")]
    [HttpPost]
    public IHttpActionResult ProcessClientRegistrationResponse([FromBody] RegistrationResponse registrationResponse)
    {

        //byte[] publicKeyBytes = Convert.FromBase64String(registrationResponse.Base64key);
        byte[] publicKeyBytes = registrationResponse.Base64key;
        AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);

        RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;

        RSAParameters rsaParameters = new RSAParameters();
        rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
        rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters(rsaParameters);

        /*****/

        string alg = rsa.SignatureAlgorithm;
        byte[] signedData = registrationResponse.signedData;
        byte[] fcParamsBytes = Encoding.UTF8.GetBytes(registrationResponse.fcParams);

        RSACng rsaCng = new RSACng();
        rsaCng.ImportParameters(rsaParameters);

        SHA1Managed hash = new SHA1Managed();
        byte[] hashedData;
        hashedData = hash.ComputeHash(signedData);

        /*********/

        bool rsaCngDataOk1 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk2 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk3 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk4 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool rsaCngHashOk1 = rsaCng.VerifyHash(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool dataOK1 = rsa.VerifyData(fcParamsBytes, new SHA1CryptoServiceProvider(), signedData);
        bool dataOk2 = rsa.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

        bool hashOk = rsa.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signedData);

        return Ok(true);

    }
</code>```

EVERY bool is wrong. I think the problem is clearly on the public key.
The questions are,

does the method publickey.encode() do what i think? I think it converts my public key to a byte[] representation (source: Android developer Key Info)

do i convert the received byte[] representation of the key to a correct RSA key?

Is there any problem on algorithms? I don't think so but we never know...

I don't find the solution. I searched for ways to import public keys from strings in .net or c# and for ways to export Android Public key to string or byte[] but there's no much help for this concrete questions...

答:
@James K Polk gave me the solution.
Apparently C# doesn't work well with PSS padding. I just had to change it to PKCS1. And i changed to digest algorithm too to SHA512.</p>

Body:
The problem is the following:

I generate the key in Android (Xamarin.Droid):

 public IPublicKey CreateKey(string keyID)
 {
    /*KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
             KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(
                    "key1",
                    KeyProperties.PURPOSE_SIGN)
                    .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
                    .build());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Signature signature = Signature.getInstance("SHA256withRSA/PSS");
    signature.initSign(keyPair.getPrivate());

     // The key pair can also be obtained from the Android Keystore any time as follows:
     KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
                keyStore.load(null);
                PrivateKey privateKey = (PrivateKey)keyStore.getKey("key1", null);
                PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();*/

    //App.Current.MainPage.DisplayAlert("Info", "Creating a new key pair", "Ok");
    // UTILIZANDO RSA
    KeyPairGenerator kpg =
    KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME);
    kpg.Initialize(
        new KeyGenParameterSpec.Builder(keyID,
        KeyStorePurpose.Sign)
        .SetSignaturePaddings(KeyProperties.SignaturePaddingRsaPss)
        .SetDigests(KeyProperties.DigestSha1)
        .Build()
        );

    KeyPair keyPair = kpg.GenerateKeyPair();

    Log.Debug(TAG, "New key created for fingerprint authentication");

    return keyPair.Public;
}

Then i generate a signature:

    KeyStore.PrivateKeyEntry PKentry =
    (KeyStore.PrivateKeyEntry)_keystore.GetEntry(keyID, null);
    IPublicKey pk = (IPublicKey)PKentry.Certificate.PublicKey;
    //this.pk = pk;
    privKey = PKentry.PrivateKey;

    //cipher.Init(Cipher.EncryptMode, privKey);
    //byte[] output = cipher.DoFinal(Encoding.UTF8.GetBytes(input));
    //String s = new string(cipher.DoFinal(input));

    // signature
    Signature sig = Signature.GetInstance("SHA1withRSA/PSS");
    sig.InitSign(privKey);
    byte[] inputDataToSign = Encoding.UTF8.GetBytes(input);
    sig.Update(inputDataToSign);
    byte[] signatureBytes = sig.Sign();

And i send the key and the signature to a ASP.net wep API 2 server.
Client side response generation:

 RegistrationResponse registrationResponse = new RegistrationResponse();
 string fcparams = Utils.Base64Encode(JsonConvert.SerializeObject(finalChallengeParams));
  registrationResponse.fcParams = fcparams;
  byte[] signedData = sign(fcparams, registrationRequest.username, facetID);
 registrationResponse.signedData = signedData;
 registrationResponse.Base64key = convertPublicKeyToString(publicKey);
 ...
 ...
private string convertPublicKeyToString(IPublicKey publicKey)
{
    string publicKeyString = Base64.EncodeToString(publicKey.GetEncoded(), 0);

 return publicKeyString;
  }

I send it using Refit Nugget.
And this is the code i use when i receive the HTTPRequest on server side:

[Route("regResponse/")]
    [HttpPost]
    public IHttpActionResult ProcessClientRegistrationResponse([FromBody] RegistrationResponse registrationResponse)
    {

        //byte[] publicKeyBytes = Convert.FromBase64String(registrationResponse.Base64key);
        byte[] publicKeyBytes = registrationResponse.Base64key;
        AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);

        RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;

        RSAParameters rsaParameters = new RSAParameters();
        rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
        rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters(rsaParameters);

        /*****/

        string alg = rsa.SignatureAlgorithm;
        byte[] signedData = registrationResponse.signedData;
        byte[] fcParamsBytes = Encoding.UTF8.GetBytes(registrationResponse.fcParams);

        RSACng rsaCng = new RSACng();
        rsaCng.ImportParameters(rsaParameters);

        SHA1Managed hash = new SHA1Managed();
        byte[] hashedData;
        hashedData = hash.ComputeHash(signedData);

        /*********/

        bool rsaCngDataOk1 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk2 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk3 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk4 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool rsaCngHashOk1 = rsaCng.VerifyHash(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool dataOK1 = rsa.VerifyData(fcParamsBytes, new SHA1CryptoServiceProvider(), signedData);
        bool dataOk2 = rsa.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

        bool hashOk = rsa.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signedData);

        return Ok(true);

    }

EVERY bool is wrong. I think the problem is clearly on the public key.
The questions are,

does the method publickey.encode() do what i think? I think it converts my public key to a byte[] representation (source: Android developer Key Info)

do i convert the received byte[] representation of the key to a correct RSA key?

Is there any problem on algorithms? I don't think so but we never know...

I don't find the solution. I searched for ways to import public keys from strings in .net or c# and for ways to export Android Public key to string or byte[] but there's no much help for this concrete questions...


问:
Chrome not opening new window correctly
I'm attempting to open a new window from a local html file but Chrome doesn't appear to be opening it correctly. I've got the following...

```<code>    function open()
{
    window.open ("open.html","open","resizable=no,scrollbars=no,status=no,toolbar=no width=500,height=300");
}
</code>```

As you can see, it explains itself. I want a new window of that height with those options. However, right now it opens with scrollbars, is resizeable and doesn't open my html file. What am I doing wrong?

答: Add the missing comma and change your function name from open to something else (say openLink).

Title: Chrome not opening new window correctly

Body:
I'm attempting to open a new window from a local html file but Chrome doesn't appear to be opening it correctly. I've got the following...

    function open()
{
    window.open ("open.html","open","resizable=no,scrollbars=no,status=no,toolbar=no width=500,height=300");
}

As you can see, it explains itself. I want a new window of that height with those options. However, right now it opens with scrollbars, is resizeable and doesn't open my html file. What am I doing wrong?


问:
How to validate input using javascript
```<code><script type="text/javascript">
function validate() {
    if (document.form.price.value.trim() === "") {
        alert("Please enter a price");
        document.form.price.focus();
        return false;
    }
    if (document.form.price.value !== "") {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.form.price.value))) {
            alert("Please enter a valid price");
            document.form.price.focus();
            return false;
        }
    }
    return true;
}
</script>

<form action="" method="post" name="form" id="form" onsubmit="return validate(this);">

<input name="price"  type="text" class="r2" />
<input name="price2" type="text" class="r2" />
<input name="price3" type="text" class="r2" />
<input name="price4" type="text" class="r2" />
<input name="price5" type="text" class="r2" />
...more....
<input name="price50" type="text" class="r2" />
</code>```

This javascript code is working fine to validate the field "price".

Question :

How to make the code to work as global validation? Example: would validate the price, price2, price3, price4, price5 etc.. with a single function. Please let me know :)

答:
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.

Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.

```<code>    <form action="/registration" method="POST">
      <p>
        User name (4 characters minimum, only alphanumeric characters):
        <input data-validation="length alphanumeric" data-validation-length="min4">
      </p>
      <p>
        Year (yyyy-mm-dd):
        <input data-validation="date" data-validation-format="yyyy-mm-dd">
      </p>
      <p>
        Website:
        <input data-validation="url">
      </p>
      <p>
        <input type="submit">
      </p>
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
    <script>
      $.validate({
        lang: 'es'
      });
    </script>
</code>```

Title: How to validate input using javascript

Body:
<form action="" method="post" name="form" id="form" onsubmit="return validate(this);">

<input name="price"  type="text" class="r2" />
<input name="price2" type="text" class="r2" />
<input name="price3" type="text" class="r2" />
<input name="price4" type="text" class="r2" />
<input name="price5" type="text" class="r2" />
...more....
<input name="price50" type="text" class="r2" />

This javascript code is working fine to validate the field "price".

Question :

How to make the code to work as global validation? Example: would validate the price, price2, price3, price4, price5 etc.. with a single function. Please let me know :)

Body:
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.

Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.

    <form action="/registration" method="POST">
      <p>
        User name (4 characters minimum, only alphanumeric characters):
        <input data-validation="length alphanumeric" data-validation-length="min4">
      </p>
      <p>
        Year (yyyy-mm-dd):
        <input data-validation="date" data-validation-format="yyyy-mm-dd">
      </p>
      <p>
        Website:
        <input data-validation="url">
      </p>
      <p>
        <input type="submit">
      </p>
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
    <script>
      $.validate({
        lang: 'es'
      });
    </script>

ContentLicense: CC BY-SA 4.0


问:
How to display 2 labels dynamically with different color?

See in Image, in that message "I still look back on that expe...." and after that one count value is there i.e (7) .

Here, message color is blue and count value i.e (7) is in green color.

My question is that, how to adjust both labels dynamically with different length and different color like example shown in image.

答:
Doing it with two labels is not the way you want to do it. A much better solution would be to use NSAttributedString.

```<code>struct MyMsg {
        var text: String
        var count: Int
    }

    let msg = MyMsg(text: "I still look back on that expe....", count: 7)

    let contentString = NSMutableAttributedString(string: msg.text)
    let countString = NSAttributedString(string: " \(msg.count)", attributes: [NSForegroundColorAttributeName: UIColor.green])
    contentString.append(countString)
    myLabel.attributedText = contentString
</code>```

Body:
Doing it with two labels is not the way you want to do it. A much better solution would be to use NSAttributedString.

struct MyMsg {
        var text: String
        var count: Int
    }

    let msg = MyMsg(text: "I still look back on that expe....", count: 7)

    let contentString = NSMutableAttributedString(string: msg.text)
    let countString = NSAttributedString(string: " \(msg.count)", attributes: [NSForegroundColorAttributeName: UIColor.green])
    contentString.append(countString)
    myLabel.attributedText = contentString


问:
Display SQLserv result as text in PHP array
I have a query where I'm already pulling back the results from a Sql query via an array as below.

```<code><?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "<table><tr id=\"header\"><td><center>Status</center></td><tr>";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "<tr><td><b><center> " . $row["STATUS"] . "</center></b></td></tr>";
}

echo "</table>";

sqlsrv_close( $conn );
?>
</code>```

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

答:
Read also about this: http://php.net/manual/en/function.strtr.php</p>

```<code>strtr($row["STATUS"], $status);
</code>```

Body:
I have a query where I'm already pulling back the results from a Sql query via an array as below.

<?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "

Status
";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "
 " . $row["STATUS"] . "
";
}

echo "
";

sqlsrv_close( $conn );
?>

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

Body:
Read also about this: http://php.net/manual/en/function.strtr.php

strtr($row["STATUS"], $status);


问:
Angular: Component X is not included in a module and will not be available inside a template
In my Angular application, I have few components which are used while testing and not included in any module.

In WebStorm, it shows me a lint error saying Component is not included in any module, while I know that this is not included and that is the purpose.

Is there a way to disable only this lint error while keeping all others enabled?

Angular: Component 'ComponentName' is not included in a module and
  will not be available inside a template. Consider adding it to a
  NgModule declaration.

I saw this threat, where it was suggested to disable all Angular lint errors. However, i think it is not a good idea to do that just for one issue. I am looking for a way to only disable this one error.

答: Angular language service doesn't provide a possibility to suppress particular rules/checks. Please follow https://github.com/angular/angular/issues/13726 for updates</p>


问:
php5 pagination current page
I am trying to highlight the current page in my website using the class active so that users can know which page the users can know which page they are currently in. Below is the php5 code I am trying to get to work.

```<code><!-- Pagination -->
<ul class="pagination pagination-lg">
  <?php for ($page=1; $page<=$number_of_pages; $page++) { ?>
  <li><a href="page.php?page=<?php echo $page?>" class= "active" ><?php echo $page ?></a></li>
  <?php } ?>
</ul>
</code>```

This is what I am trying to obtain

But, this is what my code currently generates

This is the best I could come up with

```<code>  <?php for ($page=1; $page<=$number_of_pages; $page++) { ?>
      <li><a href="page.php?page=<?php echo $page?>"  <?php if ($_GET['page'] == $page) { echo 'class= "active"'; } ?> >
  <?php echo $page ?></a></li> <?php } ?>
</code>```

答:
Try This ,where set $current_page to your current page.

```<code><ul class="pagination pagination-lg">
    <?php
    $current_page = 1;
    for ($page = 1; $page <= $number_of_pages; $page++) {
        ?>
        <li><a href="page.php?page=<?php echo $page ?>" class= "<?php if ($page == $current_page) echo 'active'; ?>"><?php echo $page ?></a></li>
        <?php
    }
    ?>
</ul>
</code>```

Title: php5 pagination current page

Body:
I am trying to highlight the current page in my website using the class active so that users can know which page the users can know which page they are currently in. Below is the php5 code I am trying to get to work.

  <?php for ($page=1; $page<=$number_of_pages; $page++) { ?>

<a href="page.php?page=<?php echo $page?>" class= "active" ><?php echo $page ?>

  <?php } ?>

This is what I am trying to obtain

But, this is what my code currently generates

This is the best I could come up with

  <?php for ($page=1; $page<=$number_of_pages; $page++) { ?>

<a href="page.php?page=<?php echo $page?>"  <?php if ($_GET['page'] == $page) { echo 'class= "active"'; } ?> >
  <?php echo $page ?>
 <?php } ?>

Body:
Try This ,where set $current_page to your current page.

<ul class="pagination pagination-lg">
    <?php
    $current_page = 1;
    for ($page = 1; $page <= $number_of_pages; $page++) {
        ?>
        <li><a href="page.php?page=<?php echo $page ?>" class= "<?php if ($page == $current_page) echo 'active'; ?>"><?php echo $page ?></a></li>
        <?php
    }
    ?>
</ul>