问:
Spark SQL fails with java.lang.NoClassDefFoundError: org/codehaus/commons/compiler/UncheckedCompileException
Running a Spark SQL (v2.1.0_2.11) program in Java immediately fails with the following exception, as soon as the first action is called on a dataframe:

```<code>java.lang.ClassNotFoundException: org.codehaus.commons.compiler.UncheckedCompileException
</code>```

I ran it in Eclipse, outside of the spark-submit environment. I use the following Spark SQL Maven dependency:

```<code><dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.0</version>
    <scope>provided</scope>
</dependency>
</code>```

答:
My implementation requirement is Spring-boot + Scala + Spark(2.4.5)

For this issue, solution is to exclude artifactID 'janino' and 'commons-compiler' which comes with 'spark-sql_2.12' version 2.4.5.

The reason being the updated version 3.1.2 for both artifactID 'janino' and 'commons-compiler' which comes with 'spark-sql_2.12' version 2.4.5.

After excluding, add version 3.0.8 for both artifactID 'janino' and 'commons-compiler' as separate dependency.

```<code><dependencies>
     <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.12</artifactId>
        <version>2.4.5</version>
        <exclusions>
            <exclusion>
                <artifactId>janino</artifactId>
                <groupId>org.codehaus.janino</groupId>
            </exclusion>
            <exclusion>
                <artifactId>commons-compiler</artifactId>
                <groupId>org.codehaus.janino</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <artifactId>janino</artifactId>
        <groupId>org.codehaus.janino</groupId>
        <version>3.0.8</version>
    </dependency>
    <dependency>
        <artifactId>commons-compiler</artifactId>
        <groupId>org.codehaus.janino</groupId>
        <version>3.0.8</version>
    </dependency>
    ...............
    ...............
    ...............
    ...............
    ...............
</dependencies>
</code>```

Body:
Running a Spark SQL (v2.1.0_2.11) program in Java immediately fails with the following exception, as soon as the first action is called on a dataframe:

java.lang.ClassNotFoundException: org.codehaus.commons.compiler.UncheckedCompileException

I ran it in Eclipse, outside of the spark-submit environment. I use the following Spark SQL Maven dependency:

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.0</version>
    <scope>provided</scope>
</dependency>

Body:
My implementation requirement is Spring-boot + Scala + Spark(2.4.5)

For this issue, solution is to exclude artifactID 'janino' and 'commons-compiler' which comes with 'spark-sql_2.12' version 2.4.5.

The reason being the updated version 3.1.2 for both artifactID 'janino' and 'commons-compiler' which comes with 'spark-sql_2.12' version 2.4.5.

After excluding, add version 3.0.8 for both artifactID 'janino' and 'commons-compiler' as separate dependency.

<dependencies>
     <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.12</artifactId>
        <version>2.4.5</version>
        <exclusions>
            <exclusion>
                <artifactId>janino</artifactId>
                <groupId>org.codehaus.janino</groupId>
            </exclusion>
            <exclusion>
                <artifactId>commons-compiler</artifactId>
                <groupId>org.codehaus.janino</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <artifactId>janino</artifactId>
        <groupId>org.codehaus.janino</groupId>
        <version>3.0.8</version>
    </dependency>
    <dependency>
        <artifactId>commons-compiler</artifactId>
        <groupId>org.codehaus.janino</groupId>
        <version>3.0.8</version>
    </dependency>
    ...............
    ...............
    ...............
    ...............
    ...............
</dependencies>


来源: stackexchange

问:
IIS Returning Old User Names to my application
Here's my scenario.  I created an application which uses Integrated Windows Authentication in order to work.  In Application_AuthenticateRequest(), I use HttpContext.Current.User.Identity to get the current WindowsPrincipal of the user of my website.

Now here's the funny part.  Some of our users have recently gotten married, and their names change.   (i.e. the user's NT Login changes from jsmith to jjones) and when my application authenticates them, IIS passes me their OLD LOGIN .  I continue to see jsmith passed to my application until I reboot my SERVER!  Logging off the client does not work.  Restarting the app pool does not work.  Only a full reboot.

Does anyone know what's going on here?  Is there some sort of command I can use to flush whatever cache is giving me this problem?  Is my server misconfigured?

Note: I definitely do NOT want to restart IIS, my application pools, or the machine.  As this is a production box, these are not really viable options.

AviD -

Yes, their UPN was changed along with their login name.  And Mark/Nick... This is a production enterprise server... It can't just be rebooted or have IIS restarted.

Follow up (for posterity):

Grhm's answer was spot-on.  This problem pops up in low-volume servers where you don't have a lot of people using your applications, but enough requests are made to keep the users' identity in the cache.  The key part of the KB which seems to describe why the cache item is not refreshed after the default of 10 minutes is:

The cache entries do time out, however chances are that recurring
  queries by applications keep the existing cache entry alive for the
  maximum lifetime of the cache entry.

I'm not exactly sure what in our code was causing this (the recurring queries), but the resolution which worked for us was to cut the LsaLookupCacheExpireTime value from the seemingly obscene default of 1 week to just a few hours.  This, for us, cut the probability that a user would be impacted in the real world to essentially zero, and yet at the same time doesn't cause an extreme number of SID-Name lookups against our directory servers.  An even better solution IMO would be if applications looked up user information by SID instead of mapping user data to textual login name.  (Take note, vendors!  If you're relying on AD authentication in your application, you'll want to put the SID in your authentication database!)

答: Just as an FYI we had the exact same issue.  What appeared to work for us is to go into Active Directory and do a "Refresh".  Immediately after this we had to recycle the application pool on the intranet sites that were having this issue.</p>

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Dave Markle


问:
string.split is not working for some reason
I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.

When I run this code, I get undefined. I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.

Can you please take a look and help figure me out what am I doing wrong?

Here is my code:

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = [names.split(" ")];
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] == "Michael") {
      var Michael = newN[i++];
    }
    return Michael;
  }
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```

答:
Your code has multiple issues:

Don't use newN[i++] because you're updating the i value. Use newN[i+1] instead;

You've got some scopes issues. You can learn more here: https://developer.mozilla.org/en-US/docs/Glossary/Scope

If the last word of the sentence was 'Michael', you'll get a overflow error (newN[i+1] does not exist).

The split function already returns an array.

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = names.split(" ");
  var michaelLastnames = []

  for (var i = 0; i<newN.length - 1; i++) {
    if(newN[i] == "Michael") {
      michaelLastnames.push(newN[i+1]);
    }
  }

  return michaelLastnames;
}

var michaelLastname = getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")

console.log(michaelLastname)```

ContentLicense: CC BY-SA 4.0


问:
The plugin generated 242 characters of unexpected output during activation. If you notice “headers already sent” messages
I'm a beginner in plugin development. I have created one plugin for the book. but it generates one error at an installation time_

The plugin generated 242 characters of unexpected output during
  activation. If you notice “headers already sent” messages

I searched for this type of error and the reason is ending PHP tag with space and etc but I don't think this type of issue here
this is my code for the create table and add menu

```<code><?php /*
* @package test plugin
*/
/*
 * Plugin Name: test
 * Description: This plugin is book plugin.
 * Plugin URI:
 * Author:
 * Author URI:
 * Version: 1.0.0
*/
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
    $table_name2 = $wpdb->prefix . 'question';
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE test3 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        category varchar(255) DEFAULT '0',
        question LONGTEXT DEFAULT NULL,
        qp1 LONGTEXT DEFAULT NULL,
        qp2 LONGTEXT DEFAULT NULL,
        qp3 LONGTEXT DEFAULT NULL,
        qp4 LONGTEXT DEFAULT NULL,
        qp5 LONGTEXT DEFAULT NULL,
        image varchar(255) DEFAULT '0',
        option1 varchar(255) DEFAULT '0',
        option2 varchar(255) DEFAULT '0',
        option3 varchar(255) DEFAULT '0',
        option4 varchar(255) DEFAULT '0',
        dd1option1 varchar(255) DEFAULT '0',
        dd1option2 varchar(255) DEFAULT '0',
        dd1option3 varchar(255) DEFAULT '0',
        dd1option4 varchar(255) DEFAULT '0',
        answer LONGTEXT DEFAULT NULL,
        PRIMARY KEY  (id)
        ) $charset_collate;";
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
    update_option( 'jal_db_version', $jal_db_version );
}
register_activation_hook( __FILE__, 'jal_install1' );
//adding in menu
add_action('admin_menu', 'at_try_menu');
    function enqueue(){
    wp_enqueue_style( 'bookstyle', plugins_url('/assets/style/style.css', __FILE__ ) );
}
    add_action('wp_enqueue_scripts', 'enqueue');
    function at_try_menu() {
    //adding plugin in menu
    add_menu_page('book_menu', //page title
    'Book',//menu title
    'manage_options',//capabilities
    'Book_Menu',//menu slug
    'book_menu'//function
);
    //adding submenu to a menu
    add_submenu_page('Book_Menu',//parent page slug
    'Book Question',//page title
    'Question',//menu titel
    'manage_options',//manage optios
    'Book_Question',//slug
    'book_question'//function
);
    add_submenu_page( 'Book_Menu',//parent page slug
    'book_question',//$page_title
    'Result',// $menu_title
    'manage_options',// $capability
    'Book_Result',// $menu_slug,
    'book_result'// $function
);
}
//returns the root directory path of particular plugin
define('ROOTDIR', plugin_dir_path(__FILE__));
</code>```

答:
The reason you are getting the error is that you have a typo in the following line:

```<code>register_activation_hook( __FILE__, 'jal_install1' );
</code>```

You have an extra 1 in the function name. Removing that character, removes the error.

Also, something that might help in the future. The errors shown on the UI side of a Wordpress website is generally put there for users and not developers. But the system does log errors if error logging is enabled. You can do this by doing the following:

Change the second param in the line define( 'WP_DEBUG', false ); in the wp-config.php to true and that should trigger "debug" mode in your WP installation.

Second, add one of the following below the WP_DEBUG line to trigger the logging of errors to a file.

```<code>    define( 'WP_DEBUG_LOG', true );
    -or-
    define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );
</code>```

if you want, you can even get the errors to show up on the screen by adding define('WP_DEBUG_DISPLAY',true) to the wp-config.php file to see errors in HTML.

You can read more about this here.

Hope this helps you.

Body:
I'm a beginner in plugin development. I have created one plugin for the book. but it generates one error at an installation time_

The plugin generated 242 characters of unexpected output during
  activation. If you notice “headers already sent” messages

I searched for this type of error and the reason is ending PHP tag with space and etc but I don't think this type of issue here
this is my code for the create table and add menu

<?php /*
* @package test plugin
*/
/*
 * Plugin Name: test
 * Description: This plugin is book plugin.
 * Plugin URI:
 * Author:
 * Author URI:
 * Version: 1.0.0
*/
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
    $table_name2 = $wpdb->prefix . 'question';
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE test3 (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        category varchar(255) DEFAULT '0',
        question LONGTEXT DEFAULT NULL,
        qp1 LONGTEXT DEFAULT NULL,
        qp2 LONGTEXT DEFAULT NULL,
        qp3 LONGTEXT DEFAULT NULL,
        qp4 LONGTEXT DEFAULT NULL,
        qp5 LONGTEXT DEFAULT NULL,
        image varchar(255) DEFAULT '0',
        option1 varchar(255) DEFAULT '0',
        option2 varchar(255) DEFAULT '0',
        option3 varchar(255) DEFAULT '0',
        option4 varchar(255) DEFAULT '0',
        dd1option1 varchar(255) DEFAULT '0',
        dd1option2 varchar(255) DEFAULT '0',
        dd1option3 varchar(255) DEFAULT '0',
        dd1option4 varchar(255) DEFAULT '0',
        answer LONGTEXT DEFAULT NULL,
        PRIMARY KEY  (id)
        ) $charset_collate;";
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
    update_option( 'jal_db_version', $jal_db_version );
}
register_activation_hook( __FILE__, 'jal_install1' );
//adding in menu
add_action('admin_menu', 'at_try_menu');
    function enqueue(){
    wp_enqueue_style( 'bookstyle', plugins_url('/assets/style/style.css', __FILE__ ) );
}
    add_action('wp_enqueue_scripts', 'enqueue');
    function at_try_menu() {
    //adding plugin in menu
    add_menu_page('book_menu', //page title
    'Book',//menu title
    'manage_options',//capabilities
    'Book_Menu',//menu slug
    'book_menu'//function
);
    //adding submenu to a menu
    add_submenu_page('Book_Menu',//parent page slug
    'Book Question',//page title
    'Question',//menu titel
    'manage_options',//manage optios
    'Book_Question',//slug
    'book_question'//function
);
    add_submenu_page( 'Book_Menu',//parent page slug
    'book_question',//$page_title
    'Result',// $menu_title
    'manage_options',// $capability
    'Book_Result',// $menu_slug,
    'book_result'// $function
);
}
//returns the root directory path of particular plugin
define('ROOTDIR', plugin_dir_path(__FILE__));

Body:
The reason you are getting the error is that you have a typo in the following line:

register_activation_hook( __FILE__, 'jal_install1' );

You have an extra 1 in the function name. Removing that character, removes the error.

Also, something that might help in the future. The errors shown on the UI side of a Wordpress website is generally put there for users and not developers. But the system does log errors if error logging is enabled. You can do this by doing the following:

Change the second param in the line define( 'WP_DEBUG', false ); in the wp-config.php to true and that should trigger "debug" mode in your WP installation.

Second, add one of the following below the WP_DEBUG line to trigger the logging of errors to a file.

    define( 'WP_DEBUG_LOG', true );
    -or-
    define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

if you want, you can even get the errors to show up on the screen by adding define('WP_DEBUG_DISPLAY',true) to the wp-config.php file to see errors in HTML.

You can read more about this here.

Hope this helps you.


问:
Flutter: use "children: <Widget>" or "children:"?
In this document https://flutter.dev/docs/development/ui/layout#nesting-rows-and-columns
they use

```children:
```

But in the Android Studio, and this doc https://api.flutter.dev/flutter/widgets/Row-class.html
they use

```
children: &ltWidget&gt
```

So, what are the differences?
Thank you

答:
both of them are true and worked but the difference is :

it`s like when you create a list, you can create lists like below

```<code>List<dynamic> list;
List<Widget> list;
</code>```

when you pass the <Widget>[] you tell to compiler the input list type is Widget and all list child must be Widget not anything else

and if you use  children: <Widget>[] your IDE can know the list type and if you add anything except Widget the IDE throw an error before you build the application and waste your time

Body:
In this document https://flutter.dev/docs/development/ui/layout#nesting-rows-and-columns
they use

children:

But in the Android Studio, and this doc https://api.flutter.dev/flutter/widgets/Row-class.html
they use

children: &ltWidget&gt

So, what are the differences?
Thank you

Body:
both of them are true and worked but the difference is :

it`s like when you create a list, you can create lists like below

List<dynamic> list;
List<Widget> list;

when you pass the <Widget>[] you tell to compiler the input list type is Widget and all list child must be Widget not anything else

and if you use  children: <Widget>[] your IDE can know the list type and if you add anything except Widget the IDE throw an error before you build the application and waste your time


问:
What is the different between encode and encription?
I am using windows form and mysql.

I am very confuse about different between encode and encription?.

encode also change the string value. and decode is give back the string.

In my program,...

userid - mcs
password - mcs

i want to store these strings in mysql database. but not a same string, for security purpose.

What is secure way to store these datas.

encode and encription which is best for this requirement.

thanks in advance.

i googled for the different but till i am not clear!. any one pls tell me  the different between encode and encription?. For my requrement what i use?.

Before leave this question just vist my downvote question in Click here

答:
Encoding and decoding (such as base64) are often associated with security procedures but encoding data is not at all a secure procedure on its own. Encoding simply turns an arbitrary set of byte data such as jpegs, gifs and encrypted bytes, into a string of text which easier and safer to store and transport across a variety of platforms and systems.

With encryption you actually secure data by processing it with a secret key into a different, encrypted block of data that is very hard to break without the key with which it was created. Decryption does the reverse, provided you have the key.

To secure your data you need to encrypt it. To help you store encrypted data you may want to encode but it is optional. If you store your encrypted data as a db blob, there's no need to encode.

To get the data back, you will need decode it (if you encoded) and then decrypt.


问:
How to set React Custom Port like 3129
My project is based on create-react-app. npm start or yarn start by default will run the application on port 3000 and there is no option of specifying a port in the package.json.</p>

答:
run this code</p>

```<code>yarn start --port 30022
</code>```

Title: How to set React Custom Port like 3129

Body:
run this code

yarn start --port 30022


问:
EF Core Full-text search: parameterized keySelector could not be translated into SQL
I'd like to create a generic extension method which allow me to use Full-text search.

● The code below works:

```<code>IQueryable<MyEntity> query = Repository.AsQueryable();

if (!string.IsNullOrEmpty(searchCondition.Name))
    query = query.Where(e => EF.Functions.Contains(e.Name, searchCondition.Name));

return query.ToList();
</code>```

● But I want a more-generic-way so I create the following extension method

```<code>public static IQueryable<T> FullTextContains<T>(this IQueryable<T> query, Func<T, string> keySelector, string value)
{
    return query.Where(e => EF.Functions.Contains(keySelector(e), value));
}
</code>```

When I call the exxtension method like below, I got an exception

```<code>IQueryable<MyEntity> query = Repository.AsQueryable();

if (!string.IsNullOrEmpty(searchCondition.Name))
    query = query.FullTextContains(e => e.Name, searchCondition.Name);

return query.ToList();
</code>```

```
> System.InvalidOperationException: 'The LINQ expression 'DbSet
>     .Where(c => __Functions_0
>         .Contains(
>           _: Invoke(__keySelector_1, c[MyEntity])
>           ,
> propertyReference: __value_2))' could not be translated. Either rewrite the query in a form that
> can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(),
> AsAsyncEnumerable(), ToList(), or ToListAsync().
> See https://go.microsoft.com/fwlink/?linkid=2101038 for more information
>
```

How do I "rewrite the query in a form that can be translated" as the Exception suggested?

答:
Your are falling into the typical IQueryable<> trap by using delegates (Func<>) instead of expressions (Expression<Func<>). You can see that difference in the lambda arguments of every  Queryable extension method vs corresponding Enumerable method. The difference is that the delegates cannot be translated (they are like unknown methods), while the expressions can.

So in order to do what you want, you have to change the signature of the custom method to use expression(s):

```<code>public static IQueryable<T> FullTextContains<T>(
    this IQueryable<T> query,
    Expression<Func<T, string>> keySelector, // <--
    string value)
</code>```

But now you have implementation problem because C# does not support syntax for "invoking" expressions similar to delegates, so the following

```<code>keySelector(e)
</code>```

does not compile.

In order to do that you need at minimum a small utility for composing expressions like this:

```<code>public static partial class ExpressionUtils
{
    public static Expression<Func<TOuter, TResult>> Apply<TOuter, TInner, TResult>(this Expression<Func<TOuter, TInner>> outer, Expression<Func<TInner, TResult>> inner)
        => Expression.Lambda<Func<TOuter, TResult>>(inner.Body.ReplaceParameter(inner.Parameters[0], outer.Body), outer.Parameters);

    public static Expression<Func<TOuter, TResult>> ApplyTo<TInner, TResult, TOuter>(this Expression<Func<TInner, TResult>> inner, Expression<Func<TOuter, TInner>> outer)
        => outer.Apply(inner);

    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
        => new ParameterReplacer { source = source, target = target }.Visit(expression);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression source;
        public Expression target;
        protected override Expression VisitParameter(ParameterExpression node)
            => node == source ? target : node;
    }
}
</code>```

Use Apply or ApplyTo depending of what type of expression you have. Other than that they do the same.

In your case, the implementation of the method with Expression<Func<T, string>> keySelector would be

```<code>return query.Where(keySelector.Apply(key => EF.Functions.Contains(key, value)));
</code>```

Body:
I'd like to create a generic extension method which allow me to use Full-text search.

● The code below works:

IQueryable<MyEntity> query = Repository.AsQueryable();

if (!string.IsNullOrEmpty(searchCondition.Name))
    query = query.Where(e => EF.Functions.Contains(e.Name, searchCondition.Name));

return query.ToList();

● But I want a more-generic-way so I create the following extension method

public static IQueryable<T> FullTextContains<T>(this IQueryable<T> query, Func<T, string> keySelector, string value)
{
    return query.Where(e => EF.Functions.Contains(keySelector(e), value));
}

When I call the exxtension method like below, I got an exception

IQueryable<MyEntity> query = Repository.AsQueryable();

if (!string.IsNullOrEmpty(searchCondition.Name))
    query = query.FullTextContains(e => e.Name, searchCondition.Name);

return query.ToList();

> System.InvalidOperationException: 'The LINQ expression 'DbSet
>     .Where(c => __Functions_0
>         .Contains(
>           _: Invoke(__keySelector_1, c[MyEntity])
>           ,
> propertyReference: __value_2))' could not be translated. Either rewrite the query in a form that
> can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(),
> AsAsyncEnumerable(), ToList(), or ToListAsync().
> See https://go.microsoft.com/fwlink/?linkid=2101038 for more information
>

How do I "rewrite the query in a form that can be translated" as the Exception suggested?

Body:
Your are falling into the typical IQueryable<> trap by using delegates (Func<>) instead of expressions (Expression<Func<>). You can see that difference in the lambda arguments of every  Queryable extension method vs corresponding Enumerable method. The difference is that the delegates cannot be translated (they are like unknown methods), while the expressions can.

So in order to do what you want, you have to change the signature of the custom method to use expression(s):

public static IQueryable<T> FullTextContains<T>(
    this IQueryable<T> query,
    Expression<Func<T, string>> keySelector, // <--
    string value)

But now you have implementation problem because C# does not support syntax for "invoking" expressions similar to delegates, so the following

keySelector(e)

does not compile.

In order to do that you need at minimum a small utility for composing expressions like this:

public static partial class ExpressionUtils
{
    public static Expression<Func<TOuter, TResult>> Apply<TOuter, TInner, TResult>(this Expression<Func<TOuter, TInner>> outer, Expression<Func<TInner, TResult>> inner)
        => Expression.Lambda<Func<TOuter, TResult>>(inner.Body.ReplaceParameter(inner.Parameters[0], outer.Body), outer.Parameters);

    public static Expression<Func<TOuter, TResult>> ApplyTo<TInner, TResult, TOuter>(this Expression<Func<TInner, TResult>> inner, Expression<Func<TOuter, TInner>> outer)
        => outer.Apply(inner);

    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
        => new ParameterReplacer { source = source, target = target }.Visit(expression);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression source;
        public Expression target;
        protected override Expression VisitParameter(ParameterExpression node)
            => node == source ? target : node;
    }
}

Use Apply or ApplyTo depending of what type of expression you have. Other than that they do the same.

In your case, the implementation of the method with Expression<Func<T, string>> keySelector would be

return query.Where(keySelector.Apply(key => EF.Functions.Contains(key, value)));


问:
How do i load my sample data to Azure data lake and visualize in Power Bi?
I have a sample data (.CSV)  and I'm able to visualize the same in my Power Bi desktop by using get data->text file. I want to load the same data into Azure data lakes so that i can access it from  get data-> Azure data lake storage in my Power BI.

My azure data factory and my Power Bi accounts are trial ones. How do i load data into my azure data lake? When i try to do it it is asking for my git repository which is not necessary i suppose.

答:
To get your sample data into the Data Lake, you can go into the Azure Portal, find the data lake object and find the 'Storage Explorer' option. That will open up a file manager like interface to allow folder creation and upload files.

You can also use Azure Storage Explorer to load the file.

To load the data in a continuing process, you can use Azure Data Factory. You haven't mentioned if your Data Lake is Gen 1 or Gen 2, but the MS Docs website give a good start on how to use a copy activity to push files to the data lake

Gen 1 - https://learn.microsoft.com/en-us/azure/data-factory/load-azure-data-lake-store

Gen 2 - https://learn.microsoft.com/en-us/azure/data-factory/load-azure-data-lake-storage-gen2


问:
Dynamically swapping out or toggling visibility of controls
I have a TreeView in a form, that is dock-filled to a groupbox. The problem to solve is, that there is an operation that is run on a Task, which loads data from a server application. When this is running, there should be a progress indicator displayed in the location of the TreeView. That is, it should be shown instead of the TreeView, and take its place fully. The following is what the code for this looks like:

```<code>private async void preload_data(object sender, System.EventArgs args)
{
    try
    {
        // the treeView should be disabled/invisible at this point
        // make the CircularProgressBar enabled/visible

        // get the information from the server
        await Configuration.network.fetch_stuff();
    }
    catch (Exception ex)
    {
        // something bad happened
    }
    finally
    {
        // whatever happened, the treeView should be back
    }
}
</code>```

The CircularProgressBar (a third-party control) should appear as in the code above, and should replace the TreeView. It should fill the exact same space as the TreeView would, which is dock-filled. Below is a screenshot of this:

This form and all its controls have been designed in the designer, and I don't want to do it there, I want to do it programmatically. What is the best way to go about this? I have looked at examples of Controls.Remove() and Controls.Add(), but it's not clear if that fits this purpose.

答: Solved using Visible properties of controls.

Body:
I have a TreeView in a form, that is dock-filled to a groupbox. The problem to solve is, that there is an operation that is run on a Task, which loads data from a server application. When this is running, there should be a progress indicator displayed in the location of the TreeView. That is, it should be shown instead of the TreeView, and take its place fully. The following is what the code for this looks like:

private async void preload_data(object sender, System.EventArgs args)
{
    try
    {
        // the treeView should be disabled/invisible at this point
        // make the CircularProgressBar enabled/visible

        // get the information from the server
        await Configuration.network.fetch_stuff();
    }
    catch (Exception ex)
    {
        // something bad happened
    }
    finally
    {
        // whatever happened, the treeView should be back
    }
}

The CircularProgressBar (a third-party control) should appear as in the code above, and should replace the TreeView. It should fill the exact same space as the TreeView would, which is dock-filled. Below is a screenshot of this:

This form and all its controls have been designed in the designer, and I don't want to do it there, I want to do it programmatically. What is the best way to go about this? I have looked at examples of Controls.Remove() and Controls.Add(), but it's not clear if that fits this purpose.


问:
Problem with printing - Inheritance, Polymorphism and toString
I am practicing how to use toString(), polymorphism and inheritance. Right now I have the code below and it has all the information that I want to print and it does print but I have some unwanted lines.

I just need the 1st and 3rd line but I'm not so sure why it's printing out the other 3 lines.

```<code>public class Test_toString{
    public static void main(String[] args){
        Car c = new Car();
        System.out.println(c.toString());

        NamedCar c2 = new NamedCar(160, 8, "green", "Pony");
        System.out.println(c2.toString());
    }
}

class Car{
    int speed;
    int gear;
    public String color;

    public Car(){
        speed = 100;
        gear = 5;
        color = "silver";
    }

    public Car(int speed, int gear, String color){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + "\n" + super.toString();
    }
}

class NamedCar extends Car{
    public String name;

    public NamedCar(String name){
        super();
        this.name = name;
    }

    public NamedCar(int speed, int gear, String color, String name){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
        this.name = name;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + " " +  name + "\n" + super.toString();
    }
}
</code>```

答:
In Java, all classes by default extend Object, thus they can use the methods defined there, such as hashCode() or toString(), where toString() by default returns a hash representation of the object.

Now to get back to your example.
You have an inheritance setup such as this

-- Object
-- Car extends Object
-- NamedCar extends Car

when you create a Car and print it, it will call the toString() method defined in Object and it returns you the hashCode of this particular object (the instance of Car in this case). When you write your own public String toString() method (as you have done) and you try to print the Car again, it will call the toString() of the Car Class and therefore print you your

```<code>"Car: " + speed + "km/h " + gear + " gears " + color + "\n"
</code>```

however you are also calling super.toString();  which will go to the parent class and get the value of its toString(), thus the hashCode representation of the object.

Now - fast-forward to the NamedCar. As you may have guessed it follows the same principle.

when calling the toString() method here, it prints your correct details

```<code>"Car: " + speed + "km/h " + gear + " gears " + color + " " +  name
</code>```

but then you include the toString() of the parent class by super.toString()
therefore it will then call the respective method of the Class Car.

However, since NamedCar is also a Car, it also uses the fields defined in Car,
namely:

```<code>int speed;
int gear;
public String color;
</code>```

so when the super.toString() is called and it uses them, you get them in your 4th line.

Body:
I am practicing how to use toString(), polymorphism and inheritance. Right now I have the code below and it has all the information that I want to print and it does print but I have some unwanted lines.

I just need the 1st and 3rd line but I'm not so sure why it's printing out the other 3 lines.

public class Test_toString{
    public static void main(String[] args){
        Car c = new Car();
        System.out.println(c.toString());

        NamedCar c2 = new NamedCar(160, 8, "green", "Pony");
        System.out.println(c2.toString());
    }
}

class Car{
    int speed;
    int gear;
    public String color;

    public Car(){
        speed = 100;
        gear = 5;
        color = "silver";
    }

    public Car(int speed, int gear, String color){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + "\n" + super.toString();
    }
}

class NamedCar extends Car{
    public String name;

    public NamedCar(String name){
        super();
        this.name = name;
    }

    public NamedCar(int speed, int gear, String color, String name){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
        this.name = name;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + " " +  name + "\n" + super.toString();
    }
}

Body:
In Java, all classes by default extend Object, thus they can use the methods defined there, such as hashCode() or toString(), where toString() by default returns a hash representation of the object.

Now to get back to your example.
You have an inheritance setup such as this

-- Object
-- Car extends Object
-- NamedCar extends Car

when you create a Car and print it, it will call the toString() method defined in Object and it returns you the hashCode of this particular object (the instance of Car in this case). When you write your own public String toString() method (as you have done) and you try to print the Car again, it will call the toString() of the Car Class and therefore print you your

"Car: " + speed + "km/h " + gear + " gears " + color + "\n"

however you are also calling super.toString();  which will go to the parent class and get the value of its toString(), thus the hashCode representation of the object.

Now - fast-forward to the NamedCar. As you may have guessed it follows the same principle.

when calling the toString() method here, it prints your correct details

"Car: " + speed + "km/h " + gear + " gears " + color + " " +  name

but then you include the toString() of the parent class by super.toString()
therefore it will then call the respective method of the Class Car.

However, since NamedCar is also a Car, it also uses the fields defined in Car,
namely:

int speed;
int gear;
public String color;

so when the super.toString() is called and it uses them, you get them in your 4th line.


问:
Python how to parse output of Amazon RDS Data Service
I'm struggling to parse output of ExecuteStatement action using Amazon RDS Data service https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_ExecuteStatement.html

Documentation is very poor and I can't find any meaningful examples.

I'm using Aurora MySql DB

Output is returned like this. This example is 2 rows of data returned by SELECT statement, I've replaced actual data with word "data"

```<code> {'ResponseMetadata': {'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'content-type': 'application/json', 'content-length': '809', 'date': 'Tue, 02 Jun 2020 05:39:22 GMT'}, 'RetryAttempts': 0}, 'numberOfRecordsUpdated': 0, 'records': [[{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}], [{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}]]}
</code>```

I need to extract actually only this data fields, so I can use them for INSERT statement in another table.

As per documentation original response is dictionary data type, so I get 3 keys here 'ResponseMetadata', 'numberOfRecordsUpdated' and 'records'.
As per documentation 'records' is Type: Array of arrays of Field objects and here is where I stuck. How I can extract Field objects from array of arrays inside dictionary?

答:
You are getting this

```<code>response =
{'ResponseMetadata': {'HTTPHeaders': {'content-length': '809',
                                      'content-type': 'application/json',
                                      'date': 'Tue, 02 Jun 2020 05:39:22 GMT',
                                      'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b'},
                      'HTTPStatusCode': 200,
                      'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b',
                      'RetryAttempts': 0},
 'numberOfRecordsUpdated': 0,
 'records': [[{'stringValue': 'data'},
              {'longValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': ''},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'}],
             [{'stringValue': 'data'},
              {'longValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': ''},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'}]]}
</code>```

You can read yuor rows by iterating response['records']

```<code>data_fields = []
for row in response['records']:
    for field in row:
        if field['stringValue']:
           print(field)
           data_fields.append(field)
        elif field['longValue']:
           print(field)
           data_fields.append(field)
</code>```

Consider to use dictionary cursor by directly accessing database by mysql connection configuration like so you will not see aws request metadata.

```<code>import mysql.connector

cnx = mysql.connector.connect(user='username', password='password',
                              host='aws rds mysql host',
                              database='database_name')
cnx.close()
</code>```

You can see mysql connection details from AWS console.

https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

Body:
I'm struggling to parse output of ExecuteStatement action using Amazon RDS Data service https://docs.aws.amazon.com/rdsdataservice/latest/APIReference/API_ExecuteStatement.html

Documentation is very poor and I can't find any meaningful examples.

I'm using Aurora MySql DB

Output is returned like this. This example is 2 rows of data returned by SELECT statement, I've replaced actual data with word "data"

 {'ResponseMetadata': {'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b', 'content-type': 'application/json', 'content-length': '809', 'date': 'Tue, 02 Jun 2020 05:39:22 GMT'}, 'RetryAttempts': 0}, 'numberOfRecordsUpdated': 0, 'records': [[{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}], [{'stringValue': 'data'}, {'longValue': data}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': ''}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}, {'stringValue': 'data'}]]}

I need to extract actually only this data fields, so I can use them for INSERT statement in another table.

As per documentation original response is dictionary data type, so I get 3 keys here 'ResponseMetadata', 'numberOfRecordsUpdated' and 'records'.
As per documentation 'records' is Type: Array of arrays of Field objects and here is where I stuck. How I can extract Field objects from array of arrays inside dictionary?

Body:
You are getting this

response =
{'ResponseMetadata': {'HTTPHeaders': {'content-length': '809',
                                      'content-type': 'application/json',
                                      'date': 'Tue, 02 Jun 2020 05:39:22 GMT',
                                      'x-amzn-requestid': '955a6aee-5bad-4f87-a455-b83a10a8a31b'},
                      'HTTPStatusCode': 200,
                      'RequestId': '955a6aee-5bad-4f87-a455-b83a10a8a31b',
                      'RetryAttempts': 0},
 'numberOfRecordsUpdated': 0,
 'records': [[{'stringValue': 'data'},
              {'longValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': ''},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'}],
             [{'stringValue': 'data'},
              {'longValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': ''},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'},
              {'stringValue': 'data'}]]}

You can read yuor rows by iterating response['records']

data_fields = []
for row in response['records']:
    for field in row:
        if field['stringValue']:
           print(field)
           data_fields.append(field)
        elif field['longValue']:
           print(field)
           data_fields.append(field)

Consider to use dictionary cursor by directly accessing database by mysql connection configuration like so you will not see aws request metadata.

import mysql.connector

cnx = mysql.connector.connect(user='username', password='password',
                              host='aws rds mysql host',
                              database='database_name')
cnx.close()

You can see mysql connection details from AWS console.

https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html


问:
IntelliJ idea stucked on "loading project" screen
This is a Monday morning nightmare on top of existing bugs I have!!

I have couple of projects which i open simultaneously using intellj. One of the project was not showing all directory structures inside it so i took some advice and deleted the .idea folder. Now all hell broke loose on me.

I am stucked here from the dawn of mankind now

Intellij logs

```<code>2017-12-04 09:46:59,444 [   9036]   INFO -                git4idea.GitVcs - Git version: 2.14.3.0
2017-12-04 09:46:59,533 [   9125]   INFO - pl.projectlevelman.NewMappings - VCS Root: [Git] - [/codebase/plutus]
2017-12-04 09:47:01,309 [  10901]   INFO - tor.impl.FileEditorManagerImpl - Project opening took 6353 ms
2017-12-04 09:47:02,913 [  12505]   INFO - .diagnostic.PerformanceWatcher - Indexable file iteration took 4772ms; general responsiveness: ok; EDT responsiveness: 2/5 sluggish, 1/5 very slow
2017-12-04 09:47:05,252 [  14844]   INFO - ellij.project.impl.ProjectImpl - 18 project components initialized in 52 ms

# ----- ^^ all good till here, below is when i start open new project

2017-12-04 09:47:26,455 [  36047]   INFO - og4jmonitor.Log4JWindowManager - creating new LoggingReceiver on port:=4454
2017-12-04 09:47:26,496 [  36088]   INFO - ellij.project.impl.ProjectImpl - 153 project components initialized in 165 ms
2017-12-04 09:47:26,497 [  36089]   INFO - le.impl.ModuleManagerComponent - 0 module(s) loaded in 0 ms
2017-12-04 09:47:26,645 [  36237]   INFO - CompilerBackwardReferenceIndex - backward reference index version differ due to: class java.io.FileNotFoundException
</code>```

Two errors i see on my screen are :

Intellij version

Any help would draw your chances of not having monday morning blues and nightmare like me! :)

Thank you!

答: When the "loading..." appears. Try to save a file. That seems to trigger a event to the file-system, and the directory is loaded.</p>

Body:
This is a Monday morning nightmare on top of existing bugs I have!!

I have couple of projects which i open simultaneously using intellj. One of the project was not showing all directory structures inside it so i took some advice and deleted the .idea folder. Now all hell broke loose on me.

I am stucked here from the dawn of mankind now

Intellij logs

2017-12-04 09:46:59,444 [   9036]   INFO -                git4idea.GitVcs - Git version: 2.14.3.0
2017-12-04 09:46:59,533 [   9125]   INFO - pl.projectlevelman.NewMappings - VCS Root: [Git] - [/codebase/plutus]
2017-12-04 09:47:01,309 [  10901]   INFO - tor.impl.FileEditorManagerImpl - Project opening took 6353 ms
2017-12-04 09:47:02,913 [  12505]   INFO - .diagnostic.PerformanceWatcher - Indexable file iteration took 4772ms; general responsiveness: ok; EDT responsiveness: 2/5 sluggish, 1/5 very slow
2017-12-04 09:47:05,252 [  14844]   INFO - ellij.project.impl.ProjectImpl - 18 project components initialized in 52 ms

# ----- ^^ all good till here, below is when i start open new project

2017-12-04 09:47:26,455 [  36047]   INFO - og4jmonitor.Log4JWindowManager - creating new LoggingReceiver on port:=4454
2017-12-04 09:47:26,496 [  36088]   INFO - ellij.project.impl.ProjectImpl - 153 project components initialized in 165 ms
2017-12-04 09:47:26,497 [  36089]   INFO - le.impl.ModuleManagerComponent - 0 module(s) loaded in 0 ms
2017-12-04 09:47:26,645 [  36237]   INFO - CompilerBackwardReferenceIndex - backward reference index version differ due to: class java.io.FileNotFoundException

Two errors i see on my screen are :

Intellij version

Any help would draw your chances of not having monday morning blues and nightmare like me! :)

Thank you!


问:
C: I don't know what this mean "while(temp->next->next)"
I've a struct linkedList like that

typedef struct linkedList l_List;

struct linkedList{
  hash_It* item;     /*this is hashItem structure include key and value*/
  l_List* next;     /*next list                                       */
};
```
<p>and my question is: what <code>temp->next->next </code>mean?<br />
I've suspected that temp datatype is <code>l_List*</code> instead of <code>l_List**</code> <br />
Why it's can use as level 2 pointer by that way?<br /></p>
<p>cre:I found this code on another source</p>
<pre class="lang-c prettyprint-override"><code>l_List* temp = list;
    while (temp->next->next) {
        temp = temp->next;
    }
</code>```

答:
It is an equivalent to

l_List* find(l_list *temp)
{
    while (temp->next)
    {
        l_list *temp1 = temp -> next;
        if(temp1 -> next == NULL)
            break;
        temp = temp->next;
    }
    return  temp;
}
```
<p>It should help you to understand what it means.</p>
<pre class="lang-c prettyprint-override"><code>l_list *temp1 = temp -> next -> next;
</code>```

is the same as

l_list *temp1 = temp -> next;
temp1 = temp1 -> next;
```

Body:
I've a struct linkedList like that

typedef struct linkedList l_List;

struct linkedList{
  hash_It* item;     /*this is hashItem structure include key and value*/
  l_List* next;     /*next list                                       */
};

and my question is: what temp->next->next mean?

I've suspected that temp datatype is l_List* instead of l_List**

Why it's can use as level 2 pointer by that way?

cre:I found this code on another source

l_List* temp = list;
    while (temp->next->next) {
        temp = temp->next;
    }

Body:
It is an equivalent to

l_List* find(l_list *temp)
{
    while (temp->next)
    {
        l_list *temp1 = temp -> next;
        if(temp1 -> next == NULL)
            break;
        temp = temp->next;
    }
    return  temp;
}

It should help you to understand what it means.

l_list *temp1 = temp -> next -> next;

is the same as

l_list *temp1 = temp -> next;
temp1 = temp1 -> next;


问:
I integrated leakcanary with version 2.0-beta-3, app flickered out
Error message -

java.lang.RuntimeException: Unable to get provider
  leakcanary.internal.LeakCanaryFileProvider:
  java.lang.ClassNotFoundException: Didn't find class
  "leakcanary.internal.LeakCanaryFileProvider" on path: DexPathList[[zip
  file "/system/framework/org.apache.http.legacy.boot.jar", zip file
  "/data/app/com.cango.financetob-lH9-QFZ7DnUT7CUjD0oFVQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.cango.financetob-lH9-QFZ7DnUT7CUjD0oFVQ==/lib/arm,
  /data/app/com.cango.financetob-lH9-QFZ7DnUT7CUjD0oFVQ==/base.apk!/lib/armeabi-v7a,
  /system/lib, /vendor/lib]]

I only integrated this version in the form of documentation.  And this is the complete code snippet.

// debugImplementation because LeakCanary should only run in debug builds. debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-3'

答:
This happens when version is not supported by your app. Try lowering LeakCanary version (2.0_beta) to lower versions. Ideally this should fix.

-This worked for me.


问:
Getting Null Value joining 3 tables
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

```<code>SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
</code>```

The output is like this:

答:
You're using a FULL join for the Fact_AccountPayables table. This way, all records from Fact_AccountPayables are included even if there are no matches with the other two tables. If you don't want that, use LEFT join instead of FULL join.</p>

```<code>SELECT
  ISNULL(dbo.Supplier.supplier_key, dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
  dbo.Supplier.Supplier,
  dbo.Supplier.Name,
  dbo.Supplier.Status,
  dbo.Supplier.AddressCode,
  dbo.Supplier.Address,
  dbo.Supplier.HouseNo,
  dbo.Supplier.Street,
  dbo.Supplier.City,
  dbo.Supplier.Country,
  dbo.Supplier.ZipCode,
  dbo.Supplier.StartDate,
  dbo.Supplier.CreditLimit,
  dbo.Supplier.FinancialGroup,
  dbo.Supplier.LastTransactionDate,
  dbo.Fact_PurchaseOrder.Company,
  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order], dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
  ISNULL(dbo.Fact_PurchaseOrder.Sequence, dbo.Fact_AccountPayables.Line) AS POSequence,
  dbo.Fact_PurchaseOrder.[Order Quantity],
  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
  dbo.Fact_PurchaseOrder.[Per Quantity Price],
  dbo.Fact_PurchaseOrder.[Purchase price unit],
  dbo.Fact_PurchaseOrder.[Total Order Amount],
  dbo.Fact_PurchaseOrder.Currency,
  dbo.Fact_PurchaseOrder.[Rate Date],
  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
  dbo.Fact_PurchaseOrder.[Receipt No],
  dbo.Fact_PurchaseOrder.[Receipt Sequence],
  dbo.Fact_PurchaseOrder.[Received Quantity],
  dbo.Fact_PurchaseOrder.[Approved Quantity],
  dbo.Fact_PurchaseOrder.[Purchase Office],
  dbo.Fact_PurchaseOrder.[Invoice Number],
  dbo.Fact_PurchaseOrder.[Invoice Date],
  dbo.Fact_PurchaseOrder.[Invoice Quantity],
  dbo.Fact_PurchaseOrder.[Invoice Amount],
  dbo.Fact_AccountPayables.InvoiceNumber,
  dbo.Fact_AccountPayables.Type AS InvoiceType,
  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
  dbo.Fact_AccountPayables.AP_Balance_EUR,
  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
  dbo.Fact_AccountPayables.InvoiceNumber,
  dbo.Fact_AccountPayables.DueDate,
  dbo.Fact_AccountPayables.DocDate,
  dbo.Fact_PurchaseOrder.[Order Date],
  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
  CASE
    WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
    WHEN dbo.Fact_AccountPayables.InvoiceNumber IS NULL THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
  END AS ORDERBALANCE,
  dbo.Supplier.CreditLimit - (ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR]) AS Availablecredit
FROM
  dbo.Supplier
  LEFT JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
  LEFT JOIN dbo.Fact_AccountPayables ON
    dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
    dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
</code>```

Title: Getting Null Value joining 3 tables

Body:
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence

The output is like this:

Body:
You're using a FULL join for the Fact_AccountPayables table. This way, all records from Fact_AccountPayables are included even if there are no matches with the other two tables. If you don't want that, use LEFT join instead of FULL join.

SELECT
  ISNULL(dbo.Supplier.supplier_key, dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
  dbo.Supplier.Supplier,
  dbo.Supplier.Name,
  dbo.Supplier.Status,
  dbo.Supplier.AddressCode,
  dbo.Supplier.Address,
  dbo.Supplier.HouseNo,
  dbo.Supplier.Street,
  dbo.Supplier.City,
  dbo.Supplier.Country,
  dbo.Supplier.ZipCode,
  dbo.Supplier.StartDate,
  dbo.Supplier.CreditLimit,
  dbo.Supplier.FinancialGroup,
  dbo.Supplier.LastTransactionDate,
  dbo.Fact_PurchaseOrder.Company,
  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order], dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
  ISNULL(dbo.Fact_PurchaseOrder.Sequence, dbo.Fact_AccountPayables.Line) AS POSequence,
  dbo.Fact_PurchaseOrder.[Order Quantity],
  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
  dbo.Fact_PurchaseOrder.[Per Quantity Price],
  dbo.Fact_PurchaseOrder.[Purchase price unit],
  dbo.Fact_PurchaseOrder.[Total Order Amount],
  dbo.Fact_PurchaseOrder.Currency,
  dbo.Fact_PurchaseOrder.[Rate Date],
  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
  dbo.Fact_PurchaseOrder.[Receipt No],
  dbo.Fact_PurchaseOrder.[Receipt Sequence],
  dbo.Fact_PurchaseOrder.[Received Quantity],
  dbo.Fact_PurchaseOrder.[Approved Quantity],
  dbo.Fact_PurchaseOrder.[Purchase Office],
  dbo.Fact_PurchaseOrder.[Invoice Number],
  dbo.Fact_PurchaseOrder.[Invoice Date],
  dbo.Fact_PurchaseOrder.[Invoice Quantity],
  dbo.Fact_PurchaseOrder.[Invoice Amount],
  dbo.Fact_AccountPayables.InvoiceNumber,
  dbo.Fact_AccountPayables.Type AS InvoiceType,
  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
  dbo.Fact_AccountPayables.AP_Balance_EUR,
  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
  dbo.Fact_AccountPayables.InvoiceNumber,
  dbo.Fact_AccountPayables.DueDate,
  dbo.Fact_AccountPayables.DocDate,
  dbo.Fact_PurchaseOrder.[Order Date],
  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
  CASE
    WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
    WHEN dbo.Fact_AccountPayables.InvoiceNumber IS NULL THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
  END AS ORDERBALANCE,
  dbo.Supplier.CreditLimit - (ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR]) AS Availablecredit
FROM
  dbo.Supplier
  LEFT JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
  LEFT JOIN dbo.Fact_AccountPayables ON
    dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
    dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence


问:
Where should I call a method to use data from it?
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          hello
        </div>
      </>
    );
  }
}

export default Albums;

</code>```

I wanna do something like this inside the div.

```<code>this.state.albums.map((album) => (<AlbumCard img={album.img}/>))
</code>```

答:
The reason you get an infinite loop is because you're calling setState in render. Here is what's happening behind the scenes:

1.getAlbums is called in the render method.

2.The function triggers setState.

3.setState causes re-render.

4.In the render method, getAlbums is called again.

Repeat 1-4 infinitely!

Here's is what you could do:

Create a button and bind getAlbums as a method to the onClick event handler.

2.Run getAlbums on ComponentDidMount like so:

```<code>  componentDidMount() {
      this.getAlbums();
    }
</code>```

Body:
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>

          hello

      </>
    );
  }
}

export default Albums;

I wanna do something like this inside the div.

this.state.albums.map((album) => (<AlbumCard img={album.img}/>))

Body:
The reason you get an infinite loop is because you're calling setState in render. Here is what's happening behind the scenes:

1.getAlbums is called in the render method.

2.The function triggers setState.

3.setState causes re-render.

4.In the render method, getAlbums is called again.

Repeat 1-4 infinitely!

Here's is what you could do:

Create a button and bind getAlbums as a method to the onClick event handler.

2.Run getAlbums on ComponentDidMount like so:

  componentDidMount() {
      this.getAlbums();
    }


问:
Combinatorica`PlanarQ doesn't work
```<code> g1=Graph[{UndirectedEdge[a,b]}];
 GraphQ[g1]
 (*
   OUT: True
 *)
   (*Needs["Combinatorica`"]*)
 PlanarQ[g1]
 (*
    OUT: PlanarQ[.-.]
 *)
 Combinatorica`PlanarQ[g1]
 (*
   OUT: Combinatorica`PlanarQ[.-.]
 *)
</code>```

Why doesn't PlanarQ give back "True" or "False" ?

答:
Your graph is not a Combinatorica graph, rather it is a System graph.  You'll need to specify the contexts explicitly.

```<code>Needs["GraphUtilities`"];
g1 = System`Graph[{UndirectedEdge[a, b]}];
Combinatorica`PlanarQ[
  GraphUtilities`ToCombinatoricaGraph[g1]]
</code>```

This returns True but, in general, this process is a pain and rather buggy.  I believe that Combinatorica is on the way out and I'd recommend trying to get by without.

Title: Combinatorica`PlanarQ doesn't work

Body:
 g1=Graph[{UndirectedEdge[a,b]}];
 GraphQ[g1]
 (*
   OUT: True
 *)
   (*Needs["Combinatorica`"]*)
 PlanarQ[g1]
 (*
    OUT: PlanarQ[.-.]
 *)
 Combinatorica`PlanarQ[g1]
 (*
   OUT: Combinatorica`PlanarQ[.-.]
 *)

Why doesn't PlanarQ give back "True" or "False" ?

Body:
Your graph is not a Combinatorica graph, rather it is a System graph.  You'll need to specify the contexts explicitly.

Needs["GraphUtilities`"];
g1 = System`Graph[{UndirectedEdge[a, b]}];
Combinatorica`PlanarQ[
  GraphUtilities`ToCombinatoricaGraph[g1]]

This returns True but, in general, this process is a pain and rather buggy.  I believe that Combinatorica is on the way out and I'd recommend trying to get by without.


问:
is there a way to define a new (instead of aliasing) type in typescript?
If I define the following types:

```<code>type seconds = number;
type milliseconds = number;
</code>```

The types are only aliases and the following syntax will not raise any error :

```<code>var x:seconds = 1;
var y:milliseconds = x;
</code>```

While I expect typescript to prevent doing such assignment without a casting. Is there a way to create new nominal types ?

NB: I've found this proposal, not sure if there is anything new released since.

答:
Since 2016, there is still no native support for this however a package uom-ts tries to simulate this behaviour. https://github.com/mindbrave/uom-ts here is their example:

```<code>import { Unit } from "uom-ts";

type Kg = Unit<{kg: 1}>;
type Pounds = Unit<{lb: 1}>;

const mass: Kg = 1.0 as Kg; // ok

const mass2: Kg = 1.0 as Pounds; // error
const mass3: Kg = 1.0; // error
</code>```

Body:
If I define the following types:

type seconds = number;
type milliseconds = number;

The types are only aliases and the following syntax will not raise any error :

var x:seconds = 1;
var y:milliseconds = x;

While I expect typescript to prevent doing such assignment without a casting. Is there a way to create new nominal types ?

NB: I've found this proposal, not sure if there is anything new released since.

Body:
Since 2016, there is still no native support for this however a package uom-ts tries to simulate this behaviour. https://github.com/mindbrave/uom-ts here is their example:

import { Unit } from "uom-ts";

type Kg = Unit<{kg: 1}>;
type Pounds = Unit<{lb: 1}>;

const mass: Kg = 1.0 as Kg; // ok

const mass2: Kg = 1.0 as Pounds; // error
const mass3: Kg = 1.0; // error


问:
Decoding audio data using OPUS library but not getting clear voice and split arraybytes then convert to shortbyte in Objective-c iOS
Iam trying to decoding audio data using OPUS library..
iam able to decode data but voice is not clear..Actually iam getting encoded audio data from voice translating device just i need to decode audio data and data length iam getting from device is 160..
Now i need convert to Bytearray and then need to divide into 4 part with 40 length.then each 40bytes then convert to shortArray then i need to decoded.. then need to send to websocket.
Can you some one help me to how to write this logic below is android logic which is decoding properly in android..

```<code>- (void)viewDidLoad{
    [super viewDidLoad];
    _decoder = opus_decoder_create(16000, 1, &error);
}
-(void)onGetData:(NSData *)getData{
    if(self.isSocketOpen){
        NSData *opus = [OpusConverter.shared decodeOpusData:getData];

        [self.fileHandler writeData:opus];
        self.filePath = [self getVoiceData];

        NSInteger len = [opus length];
        NSLog(@"123Data length===%ld",(long)len);
        Byte *byteData = (Byte*)malloc(len);
        memcpy(byteData, [opus bytes], len);
        NSData * audioData = [NSData dataWithBytes:byteData length:len ];
 ///////////SENDING START FRAME
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"type": @"START",
                                        @"data": @{
                                            @"appid": @13432495,
                                            @"appkey": @"sdfgdfgsdfgsdfsg",
                                            @"dev_pid": @15372,
                                            @"lm_id": @1235,
                                            @"cuid": @"cuid-1",
                                            @"format": @"pcm",
                                            @"sample": @16000
                                        }
                } options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [[WebSocketManager shared] sendDataToServer:jsonString];

        ////////SENDING AUDIO FRAME
        [[WebSocketManager shared] sendDataToServer:audioData];

        /////////SENDING FINISH FRAME
        NSData *finishjsonData = [NSJSONSerialization dataWithJSONObject:@{@"type": @"FINISH"
        } options:NSJSONWritingPrettyPrinted error:&error];
        NSString *finishJsonString = [[NSString alloc] initWithData:finishjsonData encoding:NSUTF8StringEncoding];
        [[WebSocketManager shared] sendDataToServer:finishJsonString];
    }
-(NSData*)decodeOpusData:(NSData*)data
{
    int audioLength = (int)[data length];
    Byte *byteData = (Byte*)malloc(sizeof(Byte)*audioLength);
    memcpy(byteData, [data bytes], audioLength);
    short decodedBuffer[960];
    int nDecodedByte = sizeof(short) * [self decode:byteData length:audioLength output:decodedBuffer];
    NSData* PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte];
    return PCMData;
}
-(void)playbutton{
    self.filePath = [self getVoiceData];
    NSURL *url = [NSURL fileURLWithPath:self.filePath];
    NSData *wavDATA = [NSData dataWithContentsOfURL:url];
    [AudioManager.shared playAudioData:wavDATA completionHandler:^(BOOL successfully) {
           NSLog(@"Playing");
   }];
</code>```

}

Below logic is working fine in android..
Can you someone help to fix this issue
Below is Android code.

```<code>    BUFFER_LENGTH = 40
    public fun opusDataDecoder(data:ByteArray){
                  val tntOpusUtils = OpusUtils.getInstant()
                  val decoderHandler = tntOpusUtils.createDecoder(16000, 1)
                  for (i in 0..3){
                      val byteArray = ByteArray(BUFFER_LENGTH)
                      System.arraycopy(data,i * BUFFER_LENGTH,byteArray,0, BUFFER_LENGTH)
                      val decodeBufferArray = ShortArray(byteArray.size * 8)
                      val size = tntOpusUtils.decode(decoderHandler, byteArray, decodeBufferArray)
                      if (size > 0) {
                          val decodeArray = ShortArray(size)
                          System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size)
                          opusDecode(decodeArray)//输出数据到接口
                      } else {
                          Log.e(TAG, "opusDecode error : $size")
                      }
                  }
              }
</code>```

答:
Finally i got solution for Decoding Audio data using OPUS library and converting PCM to WAV then play..

Below is updated working code..

import "OpusAudioDecode.h"

```<code>@interface OpusAudioDecode : NSObject
+ (instancetype)shared;

-(void)opusInit;
-(NSMutableData*)decodeOpusData:(NSData*)data;
@end
</code>```

import "OpusAudioDecode.m"

```<code>#import "OpusAudioDecode.h"
#import "opus.h"

#define SAMPLE_RATE 16000
#define CHANNELS        1
#define WB_FRAME_SIZE 320

@implementation OpusAudioDecode
{
    OpusDecoder *decoder;
    int opus_num;
    int pcm_num;
}
+ (instancetype)shared {
    static id _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone: NULL] init];
    });
    return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self shared];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [[self class] shared];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self opusInit];
    }
    return self;
}
-(void)opusInit
{
    int error;
    decoder = opus_decoder_create(SAMPLE_RATE, CHANNELS, &error);
    opus_decoder_ctl(decoder, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
}

////int decode(unsigned char* in_data, int len, short* out_data, int* out_len) {
-(int)decode:(unsigned char *)encodedBytes length:(int)lengthOfBytes output:(short*)decoded {
     int frame_size = WB_FRAME_SIZE;
    unsigned char cbits[frame_size + 1];
     memcpy(cbits, encodedBytes, lengthOfBytes);
    pcm_num = opus_decode(decoder,cbits,lengthOfBytes,decoded,frame_size,0);
    return frame_size;
}

-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        }
    }
    return audioData;
}
@end
</code>```

import"RecordingViewController.m"

```<code> #pragma mark - Reciving Audio Data from Deivce and DECODING with OPUS Library

-(void)recivedEncodedDatafromDevice:(NSData *)getData{
        NSMutableData *opus = [OpusAudioDecode.shared decodeOpusData:getData];
        [self.fileHandler writeData:opus];
}

#pragma mark - Save and Convert WAV From PCM

- (NSString *)getVoiceData{
    if (![CommonUtils isEmptyString:self.pcmPath]) {
        self.wavPath = [self createWavFromPcm:self.pcmPath];
    }
    return self.wavPath;
}

- (NSString *)createWavFromPcm:(NSString *)filePath {
    NSString *wavFilePath = [NSString stringWithFormat:@"%@.wav", [filePath stringByDeletingPathExtension]];
    long totalAudioLen = 0;
    long totalDataLen = 0;
    long longSampleRate = 16000;
    int channels = 1;
    long byteRate = 16 * 16000 * channels/8;
    int numOfSamples = (int)[[NSData dataWithContentsOfFile:filePath] length];
    NSData * wavData = [NSData dataWithContentsOfFile:filePath];
    if(numOfSamples>0){
    int wav1DataSize = (int)[[NSData dataWithContentsOfFile:filePath] length] - 44;
    NSData *Wave= [NSMutableData dataWithData:[wavData subdataWithRange:NSMakeRange(44, wav1DataSize)]];
    totalAudioLen=[Wave length];
    totalDataLen = totalAudioLen + 44;
    Byte *header = (Byte*)malloc(44);
    header[0] = 'R';  // RIFF/WAVE header
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';
    header[4] = (Byte) (totalDataLen & 0xff);
    header[5] = (Byte) ((totalDataLen >> 8) & 0xff);
    header[6] = (Byte) ((totalDataLen >> 16) & 0xff);
    header[7] = (Byte) ((totalDataLen >> 24) & 0xff);
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    header[12] = 'f';  // 'fmt ' chunk
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    header[16] = 16;  // 4 bytes: size of 'fmt ' chunk
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1;  // format = 1
    header[21] = 0;
    header[22] = (Byte) channels;
    header[23] = 0;
    header[24] = (Byte) (longSampleRate & 0xff);
    header[25] = (Byte) ((longSampleRate >> 8) & 0xff);
    header[26] = (Byte) ((longSampleRate >> 16) & 0xff);
    header[27] = (Byte) ((longSampleRate >> 24) & 0xff);
    header[28] = (Byte) (byteRate & 0xff);
    header[29] = (Byte) ((byteRate >> 8) & 0xff);
    header[30] = (Byte) ((byteRate >> 16) & 0xff);
    header[31] = (Byte) ((byteRate >> 24) & 0xff);
    header[32] = (Byte) (2 * 8 / 8);  // block align
    header[33] = 0;
    header[34] = 16;  // bits per sample
    header[35] = 0;
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (Byte) (totalAudioLen & 0xff);
    header[41] = (Byte) ((totalAudioLen >> 8) & 0xff);
    header[42] = (Byte) ((totalAudioLen >> 16) & 0xff);
    header[43] = (Byte) ((totalAudioLen >> 24) & 0xff);

    NSData *headerData = [NSData dataWithBytes:header length:44];
    NSMutableData * soundFileData = [NSMutableData alloc];
    [soundFileData appendData:[headerData subdataWithRange:NSMakeRange(0, 44)]];
    [soundFileData appendData:Wave];
    [[NSFileManager defaultManager] createFileAtPath:wavFilePath contents:soundFileData attributes:nil];
    }
    return wavFilePath;
}

#pragma mark - PLAYING DECODED DATA

-(void)playbutton{
    self.filePath = [self getVoiceData];
    NSURL *url = [NSURL fileURLWithPath:self.filePath];
    NSData *wavDATA = [NSData dataWithContentsOfURL:url];
    [AudioPlayerManager.shared playAudioData:wavDATA completionHandler:^(BOOL successfully) {
        NSLog(@"Playing");
    }];
}
</code>```

Body:
Iam trying to decoding audio data using OPUS library..
iam able to decode data but voice is not clear..Actually iam getting encoded audio data from voice translating device just i need to decode audio data and data length iam getting from device is 160..
Now i need convert to Bytearray and then need to divide into 4 part with 40 length.then each 40bytes then convert to shortArray then i need to decoded.. then need to send to websocket.
Can you some one help me to how to write this logic below is android logic which is decoding properly in android..

- (void)viewDidLoad{
    [super viewDidLoad];
    _decoder = opus_decoder_create(16000, 1, &error);
}
-(void)onGetData:(NSData *)getData{
    if(self.isSocketOpen){
        NSData *opus = [OpusConverter.shared decodeOpusData:getData];

        [self.fileHandler writeData:opus];
        self.filePath = [self getVoiceData];

        NSInteger len = [opus length];
        NSLog(@"123Data length===%ld",(long)len);
        Byte *byteData = (Byte*)malloc(len);
        memcpy(byteData, [opus bytes], len);
        NSData * audioData = [NSData dataWithBytes:byteData length:len ];
 ///////////SENDING START FRAME
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"type": @"START",
                                        @"data": @{
                                            @"appid": @13432495,
                                            @"appkey": @"sdfgdfgsdfgsdfsg",
                                            @"dev_pid": @15372,
                                            @"lm_id": @1235,
                                            @"cuid": @"cuid-1",
                                            @"format": @"pcm",
                                            @"sample": @16000
                                        }
                } options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [[WebSocketManager shared] sendDataToServer:jsonString];

        ////////SENDING AUDIO FRAME
        [[WebSocketManager shared] sendDataToServer:audioData];

        /////////SENDING FINISH FRAME
        NSData *finishjsonData = [NSJSONSerialization dataWithJSONObject:@{@"type": @"FINISH"
        } options:NSJSONWritingPrettyPrinted error:&error];
        NSString *finishJsonString = [[NSString alloc] initWithData:finishjsonData encoding:NSUTF8StringEncoding];
        [[WebSocketManager shared] sendDataToServer:finishJsonString];
    }
-(NSData*)decodeOpusData:(NSData*)data
{
    int audioLength = (int)[data length];
    Byte *byteData = (Byte*)malloc(sizeof(Byte)*audioLength);
    memcpy(byteData, [data bytes], audioLength);
    short decodedBuffer[960];
    int nDecodedByte = sizeof(short) * [self decode:byteData length:audioLength output:decodedBuffer];
    NSData* PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte];
    return PCMData;
}
-(void)playbutton{
    self.filePath = [self getVoiceData];
    NSURL *url = [NSURL fileURLWithPath:self.filePath];
    NSData *wavDATA = [NSData dataWithContentsOfURL:url];
    [AudioManager.shared playAudioData:wavDATA completionHandler:^(BOOL successfully) {
           NSLog(@"Playing");
   }];

}

Below logic is working fine in android..
Can you someone help to fix this issue
Below is Android code.

    BUFFER_LENGTH = 40
    public fun opusDataDecoder(data:ByteArray){
                  val tntOpusUtils = OpusUtils.getInstant()
                  val decoderHandler = tntOpusUtils.createDecoder(16000, 1)
                  for (i in 0..3){
                      val byteArray = ByteArray(BUFFER_LENGTH)
                      System.arraycopy(data,i * BUFFER_LENGTH,byteArray,0, BUFFER_LENGTH)
                      val decodeBufferArray = ShortArray(byteArray.size * 8)
                      val size = tntOpusUtils.decode(decoderHandler, byteArray, decodeBufferArray)
                      if (size > 0) {
                          val decodeArray = ShortArray(size)
                          System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size)
                          opusDecode(decodeArray)//输出数据到接口
                      } else {
                          Log.e(TAG, "opusDecode error : $size")
                      }
                  }
              }

Body:
Finally i got solution for Decoding Audio data using OPUS library and converting PCM to WAV then play..

Below is updated working code..

import "OpusAudioDecode.h"

@interface OpusAudioDecode : NSObject
+ (instancetype)shared;

-(void)opusInit;
-(NSMutableData*)decodeOpusData:(NSData*)data;
@end

import "OpusAudioDecode.m"

#import "OpusAudioDecode.h"
#import "opus.h"

#define SAMPLE_RATE 16000
#define CHANNELS        1
#define WB_FRAME_SIZE 320

@implementation OpusAudioDecode
{
    OpusDecoder *decoder;
    int opus_num;
    int pcm_num;
}
+ (instancetype)shared {
    static id _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone: NULL] init];
    });
    return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self shared];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [[self class] shared];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self opusInit];
    }
    return self;
}
-(void)opusInit
{
    int error;
    decoder = opus_decoder_create(SAMPLE_RATE, CHANNELS, &error);
    opus_decoder_ctl(decoder, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
}

////int decode(unsigned char* in_data, int len, short* out_data, int* out_len) {
-(int)decode:(unsigned char *)encodedBytes length:(int)lengthOfBytes output:(short*)decoded {
     int frame_size = WB_FRAME_SIZE;
    unsigned char cbits[frame_size + 1];
     memcpy(cbits, encodedBytes, lengthOfBytes);
    pcm_num = opus_decode(decoder,cbits,lengthOfBytes,decoded,frame_size,0);
    return frame_size;
}

-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        }
    }
    return audioData;
}
@end

import"RecordingViewController.m"

 #pragma mark - Reciving Audio Data from Deivce and DECODING with OPUS Library

-(void)recivedEncodedDatafromDevice:(NSData *)getData{
        NSMutableData *opus = [OpusAudioDecode.shared decodeOpusData:getData];
        [self.fileHandler writeData:opus];
}

#pragma mark - Save and Convert WAV From PCM

- (NSString *)getVoiceData{
    if (![CommonUtils isEmptyString:self.pcmPath]) {
        self.wavPath = [self createWavFromPcm:self.pcmPath];
    }
    return self.wavPath;
}

- (NSString *)createWavFromPcm:(NSString *)filePath {
    NSString *wavFilePath = [NSString stringWithFormat:@"%@.wav", [filePath stringByDeletingPathExtension]];
    long totalAudioLen = 0;
    long totalDataLen = 0;
    long longSampleRate = 16000;
    int channels = 1;
    long byteRate = 16 * 16000 * channels/8;
    int numOfSamples = (int)[[NSData dataWithContentsOfFile:filePath] length];
    NSData * wavData = [NSData dataWithContentsOfFile:filePath];
    if(numOfSamples>0){
    int wav1DataSize = (int)[[NSData dataWithContentsOfFile:filePath] length] - 44;
    NSData *Wave= [NSMutableData dataWithData:[wavData subdataWithRange:NSMakeRange(44, wav1DataSize)]];
    totalAudioLen=[Wave length];
    totalDataLen = totalAudioLen + 44;
    Byte *header = (Byte*)malloc(44);
    header[0] = 'R';  // RIFF/WAVE header
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';
    header[4] = (Byte) (totalDataLen & 0xff);
    header[5] = (Byte) ((totalDataLen >> 8) & 0xff);
    header[6] = (Byte) ((totalDataLen >> 16) & 0xff);
    header[7] = (Byte) ((totalDataLen >> 24) & 0xff);
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    header[12] = 'f';  // 'fmt ' chunk
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    header[16] = 16;  // 4 bytes: size of 'fmt ' chunk
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1;  // format = 1
    header[21] = 0;
    header[22] = (Byte) channels;
    header[23] = 0;
    header[24] = (Byte) (longSampleRate & 0xff);
    header[25] = (Byte) ((longSampleRate >> 8) & 0xff);
    header[26] = (Byte) ((longSampleRate >> 16) & 0xff);
    header[27] = (Byte) ((longSampleRate >> 24) & 0xff);
    header[28] = (Byte) (byteRate & 0xff);
    header[29] = (Byte) ((byteRate >> 8) & 0xff);
    header[30] = (Byte) ((byteRate >> 16) & 0xff);
    header[31] = (Byte) ((byteRate >> 24) & 0xff);
    header[32] = (Byte) (2 * 8 / 8);  // block align
    header[33] = 0;
    header[34] = 16;  // bits per sample
    header[35] = 0;
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (Byte) (totalAudioLen & 0xff);
    header[41] = (Byte) ((totalAudioLen >> 8) & 0xff);
    header[42] = (Byte) ((totalAudioLen >> 16) & 0xff);
    header[43] = (Byte) ((totalAudioLen >> 24) & 0xff);

    NSData *headerData = [NSData dataWithBytes:header length:44];
    NSMutableData * soundFileData = [NSMutableData alloc];
    [soundFileData appendData:[headerData subdataWithRange:NSMakeRange(0, 44)]];
    [soundFileData appendData:Wave];
    [[NSFileManager defaultManager] createFileAtPath:wavFilePath contents:soundFileData attributes:nil];
    }
    return wavFilePath;
}

#pragma mark - PLAYING DECODED DATA

-(void)playbutton{
    self.filePath = [self getVoiceData];
    NSURL *url = [NSURL fileURLWithPath:self.filePath];
    NSData *wavDATA = [NSData dataWithContentsOfURL:url];
    [AudioPlayerManager.shared playAudioData:wavDATA completionHandler:^(BOOL successfully) {
        NSLog(@"Playing");
    }];
}


问:
How to calculate a monthly car payment for a form I'm creating in JavaScript
I am trying to put this JavaScript in Adobe as a calculation field. The point of this is to use Term, Amount Financed and APR (Interest Rate) to calculate a monthly car payment for a form I'm creating. All I want to know is what JavaScript code will work?  PS. I have limited knowledge in JavaScript.

This code calculates $208.80 a month when the correct calculation in fact is $100 More...

APR Is .21, Term is 60, Amount to Finance is 10,000.00.

My current code below:

```<code>var R = Number(this.getField("APR").valueAsString);
var N = Number(this.getField("Term").valueAsString);
var P = Number(this.getField("AmountFinanced").valueAsString);
event.value = P * (R / 12), Math.pow(N, (1 + R)) / Math.pow(N, (1 + (R / 12) - 1));
</code>```

答:
Looks like you're trying to implement this:

That would look something like

```<code>P * (R/12) * (Math.pow((1 + (R/12)), N))/ ((Math.pow((1 + (R/12)), N)) - 1)
</code>```

Body:
I am trying to put this JavaScript in Adobe as a calculation field. The point of this is to use Term, Amount Financed and APR (Interest Rate) to calculate a monthly car payment for a form I'm creating. All I want to know is what JavaScript code will work?  PS. I have limited knowledge in JavaScript.

This code calculates $208.80 a month when the correct calculation in fact is $100 More...

APR Is .21, Term is 60, Amount to Finance is 10,000.00.

My current code below:

var R = Number(this.getField("APR").valueAsString);
var N = Number(this.getField("Term").valueAsString);
var P = Number(this.getField("AmountFinanced").valueAsString);
event.value = P * (R / 12), Math.pow(N, (1 + R)) / Math.pow(N, (1 + (R / 12) - 1));

Body:
Looks like you're trying to implement this:

That would look something like

P * (R/12) * (Math.pow((1 + (R/12)), N))/ ((Math.pow((1 + (R/12)), N)) - 1)