问:
Input data to database using rest api (Login)
I have an API that is trying to check a if a user is on the database. However, I'm not sure how to post the data from the input to my API to allow a user to login.

HTML Login page

```<code>  <ion-item class='ion-padding'>
    <ion-label position="floating">Username (Email)</ion-label>
    <ion-input type='text'name="email" #email [(ngModel)]="email"></ion-input>
  </ion-item>

  <ion-item class='ion-padding'>
    <ion-label position="floating">Password</ion-label>
    <ion-input type='password'  name="password" #password [(ngModel)]="password"></ion-input>
  </ion-item>
   <router-outlet></router-outlet>
</ion-content>
</ion-app>
</code>```

Login.ts

```<code>import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController } from '@ionic/angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: 'login.page.html',

})
export class HomePage {
  username = '';
  password = '';

  constructor(
    public navCtrl: NavController, public alertCtrl: AlertController,
    private http: HttpClient,
    private httpH: HttpHeaders,
    public loading: LoadingController) { }

  }
</code>```

答:
The clean way would be to create an authentication service and add all authentication related methods to it:

```<code>@Injectable()
export class AuthService {
  constructor(private http: HttpClient) {
  }

  login(username, password) {
    return this.http.post<any>('localhost:2800/login', {username, password});
  }
}
</code>```

Use the service and subscribe to the result in your Login.ts, and call the method when user click submit/ login. You will get the result, failed or successful, in both case you have to handle it. If fails, show the error to the user, if successful, probably redirecting user to home/ dashboard.

```<code>this.authService.login(this.username, this.password).subscribe(res => {
  if (res) {
    // if you are using JWT store the token
  } else {// depends how you handle}
}), error => {
  if (error.status === 401) {
    // Failed to login if you are returning 401
  }
});;
</code>```

Make sure you instantiate the service in the constructor:

```<code>constructor(private authService: AuthService)
</code>```

Body:
I have an API that is trying to check a if a user is on the database. However, I'm not sure how to post the data from the input to my API to allow a user to login.

HTML Login page

  <ion-item class='ion-padding'>
    <ion-label position="floating">Username (Email)</ion-label>
    <ion-input type='text'name="email" #email [(ngModel)]="email"></ion-input>
  </ion-item>

  <ion-item class='ion-padding'>
    <ion-label position="floating">Password</ion-label>
    <ion-input type='password'  name="password" #password [(ngModel)]="password"></ion-input>
  </ion-item>
   <router-outlet></router-outlet>
</ion-content>
</ion-app>

Login.ts

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController } from '@ionic/angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: 'login.page.html',

})
export class HomePage {
  username = '';
  password = '';

  constructor(
    public navCtrl: NavController, public alertCtrl: AlertController,
    private http: HttpClient,
    private httpH: HttpHeaders,
    public loading: LoadingController) { }

  }

Body:
The clean way would be to create an authentication service and add all authentication related methods to it:

@Injectable()
export class AuthService {
  constructor(private http: HttpClient) {
  }

  login(username, password) {
    return this.http.post<any>('localhost:2800/login', {username, password});
  }
}

Use the service and subscribe to the result in your Login.ts, and call the method when user click submit/ login. You will get the result, failed or successful, in both case you have to handle it. If fails, show the error to the user, if successful, probably redirecting user to home/ dashboard.

this.authService.login(this.username, this.password).subscribe(res => {
  if (res) {
    // if you are using JWT store the token
  } else {// depends how you handle}
}), error => {
  if (error.status === 401) {
    // Failed to login if you are returning 401
  }
});;

Make sure you instantiate the service in the constructor:

constructor(private authService: AuthService)


来源: stackexchange

问:
Requesting Sensor.TYPE_HEART_BEAT returns null in Android 9 Ticwatch c2
I would like to use Sensor.TYPE_HEART_BEAT from Androids Sensor API to measure heart rate variability, however when requested from my application it returns null.

I've checked my manifest permissions for BODY_SENSORS which has no effect. Sensor.TYPE_HEART_RATE also seems to be working fine.

```<code>    Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_BEAT);

    if (sensor == null) {
        Log.d(TAG,"Sensor is null");
    }
</code>```

I would expect this to return a valid sensor but it returns null.  I am using the Ticwatch c2 which does have a heart rate sensor.  I'm not sure why heart beat is not working.

答:
Don't forget, from SDK 23 and onward  you have to ask for permissions separately on the wear device and the phone. The Wear app no longer inherits permissions from the phone app.

https://developer.android.com/training/articles/wear-permissions.html

ContentLicense: CC BY-SA 4.0

Body:
I would like to use Sensor.TYPE_HEART_BEAT from Androids Sensor API to measure heart rate variability, however when requested from my application it returns null.

I've checked my manifest permissions for BODY_SENSORS which has no effect. Sensor.TYPE_HEART_RATE also seems to be working fine.

    Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_BEAT);

    if (sensor == null) {
        Log.d(TAG,"Sensor is null");
    }

I would expect this to return a valid sensor but it returns null.  I am using the Ticwatch c2 which does have a heart rate sensor.  I'm not sure why heart beat is not working.


问:
Google places search box disappear in my android app, is it my code?
I have the following code in a map activity :

```<code>PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            destination = place.getName().toString();
        }
        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
        }
    });
}
</code>```

This is the XML fragment:

```<code>        <fragment android:id="@+id/autocomplete_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"/>
</code>```

Here is my app build.gradle file :

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.site.test"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.firebase:firebase-storage:16.1.0'
implementation 'com.github.bumptech.glide:glide:4.0.0'
//implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.firebase:geofire-android:2.1.1'
implementation 'com.android.support:cardview-v7:21.0.+'
implementation 'com.google.android.gms:play-services-places:16.0.0'
//below added for testing
//implementation 'com.google.android.libraries.places:1.0.0'
`enter code here`}

apply plugin: 'com.google.gms.google-services'
</code>```

Once the map activity is activated, I see the fragment search box in it's correct placement. Once I click it, the search box pop-up briefly appears then disappears, effectively stopping me from entering a location.

I have enabled the Google Places API, and it is correctly placed in my android manifest file.

This is what the logcat shows :

```<code>2019-03-04 00:58:55.090 6506-6506/com.site.test E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted
</code>```

答:
Seems to be an issue in Places, try this
https://stackoverflow.com/a/55073542/11551260</p>

Body:
I have the following code in a map activity :

PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            destination = place.getName().toString();
        }
        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
        }
    });
}

This is the XML fragment:

        <fragment android:id="@+id/autocomplete_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"/>

Here is my app build.gradle file :

apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.site.test"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.firebase:firebase-storage:16.1.0'
implementation 'com.github.bumptech.glide:glide:4.0.0'
//implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.firebase:geofire-android:2.1.1'
implementation 'com.android.support:cardview-v7:21.0.+'
implementation 'com.google.android.gms:play-services-places:16.0.0'
//below added for testing
//implementation 'com.google.android.libraries.places:1.0.0'
`enter code here`}

apply plugin: 'com.google.gms.google-services'

Once the map activity is activated, I see the fragment search box in it's correct placement. Once I click it, the search box pop-up briefly appears then disappears, effectively stopping me from entering a location.

I have enabled the Google Places API, and it is correctly placed in my android manifest file.

This is what the logcat shows :

2019-03-04 00:58:55.090 6506-6506/com.site.test E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted


问:
Counting the max of elements based on stack operations c++
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

```<code>#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}
</code>```

Input :

```<code>6 4
1 2 4 3 3 5
</code>```

Expected Output :

```<code>4
</code>```

Error:

```<code>Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.
</code>```

答:
There are several bugs in your code: three indexation bugs and one memory deallocation bug. First of all, In C++ array indexation always starts from 0. So first valid index of n-element array is 0 and the last valid index is n-1.

1) Due to these reasons first loop should be like this:

```<code>for (int i = n-1; i >= 0; i--) { ... }
</code>```

2) Bottom element, which you call 'max', should be initialized like this:

```<code>max = arr[n-1];
</code>```

3) Same observation about the second loop:

```<code>for (int i = n-2; i >= x; i--) { ... }
</code>```

4) Deallocation of array should be performed with operator delete[] instead of delete. Otherwise you will have a memory leak and undefined behavior. Here you can find some additional information about these operators:

```<code>delete[] arr;
</code>```

Body:
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}

Input :

6 4
1 2 4 3 3 5

Expected Output :

4

Error:

Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.

Body:
There are several bugs in your code: three indexation bugs and one memory deallocation bug. First of all, In C++ array indexation always starts from 0. So first valid index of n-element array is 0 and the last valid index is n-1.

1) Due to these reasons first loop should be like this:

for (int i = n-1; i >= 0; i--) { ... }

2) Bottom element, which you call 'max', should be initialized like this:

max = arr[n-1];

3) Same observation about the second loop:

for (int i = n-2; i >= x; i--) { ... }

4) Deallocation of array should be performed with operator delete[] instead of delete. Otherwise you will have a memory leak and undefined behavior. Here you can find some additional information about these operators:

delete[] arr;


问:
How to have img same size as div
I want to make a nav bar in the footer with images. The footer needs to be 10% of the total screen and the images need to be within those 10% as well. Only I don't get the images scale according to the screen size and are way bigger. What am I doing wrong?

I am using Bootstrap 4 and I intent to make a mobile version of my website but it is not displaying good.

```<code><div class="footer navbar row">
 <div class="col-sm-2 menu_item">
<a href="#home" class="active">
    <img src="<source>" class="menu_img" alt="Logo"/>
</a>
 </div>
 <div class="col-sm-2 menu_item">
<a href="#news">
<img src="<source>" class="menu_img" alt="Logo"/>
    </a>
  </div>
  <div class="col-sm-2 menu_item">
    <a href="#contact">
        <img src="<source>" class="menu_img" alt="Logo"/>
    </a>
  </div>
  <div class="col-sm-2 menu_item">
  <a href="#contact">
    <img src="<source>" class="menu_img" alt="Logo"/>
   </a>
   </div>
   <div class="col-sm-2 menu_item">
   <a href="#contact">
    <img src="<source>" class="menu_img" alt="Logo"/>
   </a>
   </div>
</code>```

```<code>/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
        background-color: var(--primary-color-1);
        overflow: hidden;
        position: fixed;
        bottom: 0;
        width: 100%;
        margin: 0px;
        height: 10vh;
    }
    /* Style the menu blocks */
    .menu_item {
        position: relative;
        padding: 2px 10px;
        margin: 0px;
    }
    /* Style the links inside the navigation bar */
    .navbar a {
        float: left;
        display: block;
        text-align: center;
        text-decoration: none;

    }
   /* Style the images/icons of the links */
    .menu_img {
        height:100%;
        width: 100%;
        object-fit: cover;
      }
</code>```

答:
I found the solution. My structure is like

```<code><div class="footer">
  <div>
     <a>
       <img>
     </a>
   </div>
</div>
</code>```

The footer div needs to be height:10%. But I need to set the height of all the other elements to 100%(which I didn't do before). Otherwise it will extend outside those. 'borders'

Title: How to have img same size as div

Body:
I want to make a nav bar in the footer with images. The footer needs to be 10% of the total screen and the images need to be within those 10% as well. Only I don't get the images scale according to the screen size and are way bigger. What am I doing wrong?

I am using Bootstrap 4 and I intent to make a mobile version of my website but it is not displaying good.

    <img src="<source>" class="menu_img" alt="Logo"/>

<img src="<source>" class="menu_img" alt="Logo"/>

        <img src="<source>" class="menu_img" alt="Logo"/>

    <img src="<source>" class="menu_img" alt="Logo"/>

    <img src="<source>" class="menu_img" alt="Logo"/>

/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
        background-color: var(--primary-color-1);
        overflow: hidden;
        position: fixed;
        bottom: 0;
        width: 100%;
        margin: 0px;
        height: 10vh;
    }
    /* Style the menu blocks */
    .menu_item {
        position: relative;
        padding: 2px 10px;
        margin: 0px;
    }
    /* Style the links inside the navigation bar */
    .navbar a {
        float: left;
        display: block;
        text-align: center;
        text-decoration: none;

    }
   /* Style the images/icons of the links */
    .menu_img {
        height:100%;
        width: 100%;
        object-fit: cover;
      }

Body:
I found the solution. My structure is like

<div class="footer">
  <div>
     <a>
       <img>
     </a>
   </div>
</div>

The footer div needs to be height:10%. But I need to set the height of all the other elements to 100%(which I didn't do before). Otherwise it will extend outside those. 'borders'


问:
@MockBean seems to rerun context creation and fails afterMigrate.sql
I have two integration test classes. One of these classes depends on the bean that is talking to external service, so I need to mock this bean, and @MockBean seems perfect for this. For injecting some seeds into DB I'm using flyway's afterMigrate.sql. So here is hot it looks like:

```<code>@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class FooTest {

  @Autowired
  private MyService myService;
}

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class BarTest {

  @MockBean
  private ExternalService;

  @Autowired
  private MyService myService;
}
</code>```

And afterMigrate.sql:

```<code>INSERT INTO my_table (id, name) VALUES (1, 'John Doe')
</code>```

The problem appeared when I annotate the ExternatService as @MockBean as now the afretMigrate.sql runs twice and I'm getting the error:

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
....
Message    : ERROR: duplicate key value violates unique constraint "my_table_pkey"
</code>```

When I'm changing the @MockBean to @Autowired the error is gone and context is created without any problems. Also, tests run without problems if I run BarTest separately.
This is not the expected behavior for @MockBean as the documentation says:

Any existing single bean of the same type defined in the context will
  be replaced by the mock. If no existing bean is defined a new one will
  be added. Dependencies that are known to the application context but
  are not beans (such as those registered directly) will not be found
  and a mocked bean will be added to the context alongside the existing
  dependency.

It does not say that the context will be recreated.

答:
Because when you use @MockBean annotation your context will be loaded for each test. Please refer to this github issue. The citation from this page :

The Spring test framework will cache an ApplicationContext whenever possible between test runs. In order to be cached, the context must have an exactly equivalent configuration. Whenever you use @MockBean, you are by definition changing the context configuration.

So when you use your mock  bean in different tests - the context will be recreated each time for your test class. So if you for example have some beans that load data to DB on context creation - for example beans for flyway - they will be created each time context is recreated.

Body:
I have two integration test classes. One of these classes depends on the bean that is talking to external service, so I need to mock this bean, and @MockBean seems perfect for this. For injecting some seeds into DB I'm using flyway's afterMigrate.sql. So here is hot it looks like:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class FooTest {

  @Autowired
  private MyService myService;
}

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Transactional
@Rollback
class BarTest {

  @MockBean
  private ExternalService;

  @Autowired
  private MyService myService;
}

And afterMigrate.sql:

INSERT INTO my_table (id, name) VALUES (1, 'John Doe')

The problem appeared when I annotate the ExternatService as @MockBean as now the afretMigrate.sql runs twice and I'm getting the error:

java.lang.IllegalStateException: Failed to load ApplicationContext
....
Message    : ERROR: duplicate key value violates unique constraint "my_table_pkey"

When I'm changing the @MockBean to @Autowired the error is gone and context is created without any problems. Also, tests run without problems if I run BarTest separately.
This is not the expected behavior for @MockBean as the documentation says:

Any existing single bean of the same type defined in the context will
  be replaced by the mock. If no existing bean is defined a new one will
  be added. Dependencies that are known to the application context but
  are not beans (such as those registered directly) will not be found
  and a mocked bean will be added to the context alongside the existing
  dependency.

It does not say that the context will be recreated.


问:
how to display xml formatted jsp
I have XML as a string in JSP. But this XML is in a single line. I want to display this XML string formatted in JSP.

For example:

```<code><?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)
</code>```

I want to display this as follows in JSP:

```<code><?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>...(going on)
</code>```

How can I do this?

答: You need to convert the <, > and other characters which have special meaning in HTML to their HTML entities. To parse use this method. It will parse for you.</p>

ContentLicense: CC BY-SA 3.0

Title: how to display xml formatted jsp

Body:
I have XML as a string in JSP. But this XML is in a single line. I want to display this XML string formatted in JSP.

For example:

<?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price>...(is going on)

I want to display this as follows in JSP:

<?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>...(going on)

How can I do this?


问:
How to write stored procedure in DB2
Please Help me in to write the stored procedure in Db2.

```<code>CREATE PROCEDURE assedt
BEGIN

 SELECT ASSETNUM FROM ASSET
END
</code>```

I tried the above code it is throwing an error like below:

Error report -
  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=SELECT ASSETNUM;ROCEDURE p1
  BEGIN

;, DRIVER=4.12.55

答: The following redbook: http://www.redbooks.ibm.com/abstracts/sg248326.html?Open, is written for Db2 for IBM i (not zOS, not LUW), but chapter 2 is a great introduction to DB2 Procedural SQL and it is applicable to the other DB2s.  I hope this helps.</p>

Title: How to write stored procedure in DB2

Body:
Please Help me in to write the stored procedure in Db2.

CREATE PROCEDURE assedt
BEGIN

 SELECT ASSETNUM FROM ASSET
END

I tried the above code it is throwing an error like below:

Error report -
  DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=SELECT ASSETNUM;ROCEDURE p1
  BEGIN

;, DRIVER=4.12.55


问:
Curve fitting to a 3D polynomial with variable powers
I have 3 data sets. 2 for polynomial itself (let's call them x and y) and 1 for the function value (it's gonna be z).

Polynomial looks something like this (assuming the power of both dimensions is 3):

z = a00 + a01*x + a02*x^2 + a03*x^3 + a10*y + a11*y*x + a12*y*x^2 ... etc
```

<p>I need to be able to set the power of each dimension when preparing for approximation of values of "a".</p>

<p>I don't really get how CurveFitting functions work with Math.NET Numerics, but i've tried Fit.LinearMultiDim and MultipleRegression.QR. I'm having trouble with initializing the Func delegate</p>

<pre class="lang-cs prettyprint-override"><code>
    var zs = new double[]
    {
        //values here

    };

    var x = new double[]
    {
        //values here
    };

    var y = new double[]
    {
        //values here. But the amounts are equal
    };

    var design = Matrix<double>.Build.DenseOfRowArrays(Generate.Map2(x, y,(t, w) =>
    {
        var list = new List<double>();      //Can i get this working?
        for (int i = 0; i <= 3; i++)
        {
            for (int j = 0; j <= 3; j++)
            {
                list.Add(Math.Pow(t, j)*Math.Pow(w, i));
            }
        }
        return list.ToArray();
    }));

    double[] p = MultipleRegression.QR(design, Vector<double>.Build.Dense(zs)).ToArray();

</code>```

So ideally i need to be able to compose the function with some sort of loop that accounts for the max power of both variables.

UPD: The function is always above zero on any axis

答:
I think i got it working.

Here's the code:

    List<Func<double[], double>> ps = new List<Func<double[],double>>();

                for (int i = 0; i <= polynomialOrderFirstVal; i++)
                {
                    for (int j = 0; j <= polynomialOrderSecVal; j++)
                    {
                        var orderFirst = j;
                        var orderSecond = i;
                        ps.Add(d => Math.Pow(d[0], orderFirst) * Math.Pow(d[1],orderSecond));
                    }
                }
                var psArr = ps.ToArray();
                double[] coefs = Fit.LinearMultiDim(x, y, psArr);
```

Body:
I have 3 data sets. 2 for polynomial itself (let's call them x and y) and 1 for the function value (it's gonna be z).

Polynomial looks something like this (assuming the power of both dimensions is 3):

z = a00 + a01*x + a02*x^2 + a03*x^3 + a10*y + a11*y*x + a12*y*x^2 ... etc

I need to be able to set the power of each dimension when preparing for approximation of values of "a".

I don't really get how CurveFitting functions work with Math.NET Numerics, but i've tried Fit.LinearMultiDim and MultipleRegression.QR. I'm having trouble with initializing the Func delegate

    var zs = new double[]
    {
        //values here

    };

    var x = new double[]
    {
        //values here
    };

    var y = new double[]
    {
        //values here. But the amounts are equal
    };

    var design = Matrix<double>.Build.DenseOfRowArrays(Generate.Map2(x, y,(t, w) =>
    {
        var list = new List<double>();      //Can i get this working?
        for (int i = 0; i <= 3; i++)
        {
            for (int j = 0; j <= 3; j++)
            {
                list.Add(Math.Pow(t, j)*Math.Pow(w, i));
            }
        }
        return list.ToArray();
    }));

    double[] p = MultipleRegression.QR(design, Vector<double>.Build.Dense(zs)).ToArray();

So ideally i need to be able to compose the function with some sort of loop that accounts for the max power of both variables.

UPD: The function is always above zero on any axis


问:
How can I get consecutive nowrap spans to wrap as separate elements?
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

```<code><div class="block-of-text" style="max-width: 550px">
  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.
</div>
</code>```

The Result of the Base line will look something like this.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|
</code>```

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

```<code><style>
  .nowrap {
    white-space: nowrap;
  }
</style>

<div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe, </span>
  <span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span>
  <span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span>
  <span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span>
  <span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|
</code>```

What I want to have happen:

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|
</code>```

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

```<code><style>
  .nowrap {
    white-space: nowrap;
    display: inline-block;
  }
</style>

<div class="block-of-text" style="max-width: 550px; border: solid 1px red">
  One-two <span class="nowrap">Buckle-my-shoe, </span><span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span><span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span><span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span><span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

答:
This occurs because, without spaces between the spans, they act as characters in a single word. You need to put spaces between the spans, not inside them.

.nowrap {
  white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block-of-text" style="max-width: 550px; border: 1px solid red">
  One-two <span class="nowrap">Buckle-my-shoe,</span> <span class="nowrap">Three-four</span> <span class="nowrap">Shut-the-door,</span> <span class="nowrap">Five-six</span> <span class="nowrap">Pick-up-sticks,</span> <span class="nowrap">Seven-eight</span> <span class="nowrap">Lay-them-straight,</span> <span class="nowrap">Nine-ten</span> <span class="nowrap">Do-it-again.</span>
</div></code>```

Body:
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

The Result of the Base line will look something like this.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

  One-two Buckle-my-shoe,
  Three-four Shut-the-door,
  Five-six Pick-up-sticks,
  Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|

What I want to have happen:

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

  One-two Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

Body:
This occurs because, without spaces between the spans, they act as characters in a single word. You need to put spaces between the spans, not inside them.

.nowrap {
  white-space: nowrap;
}

<div class="block-of-text" style="max-width: 550px; border: 1px solid red">
  One-two <span class="nowrap">Buckle-my-shoe,</span> <span class="nowrap">Three-four</span> <span class="nowrap">Shut-the-door,</span> <span class="nowrap">Five-six</span> <span class="nowrap">Pick-up-sticks,</span> <span class="nowrap">Seven-eight</span> <span class="nowrap">Lay-them-straight,</span> <span class="nowrap">Nine-ten</span> <span class="nowrap">Do-it-again.</span>
</div>


问:
Assigning a function while subsetting a data.table
Is there a specific reason why one cannot perform the following action?

```<code>v <- data.table( A = 1:2, B = vector("list", 2) )
#    A B
# 1: 1
# 2: 2

v[ A == 1, B := list( identity ) ]
# RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.
</code>```

Note that B is a list column. On the other hand the following is possible (though giving a warning):

```<code>v[ A == 1, B := list(2) ]
</code>```

答:
We can wrap the function in a list as it is a function

```<code>v[A == 1,  B := list(list(identity))]
v
#   A          B
#1: 1 <function>
#2: 2
</code>```

Body:
Is there a specific reason why one cannot perform the following action?

v <- data.table( A = 1:2, B = vector("list", 2) )
#    A B
# 1: 1
# 2: 2

v[ A == 1, B := list( identity ) ]
# RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.

Note that B is a list column. On the other hand the following is possible (though giving a warning):

v[ A == 1, B := list(2) ]

Body:
We can wrap the function in a list as it is a function

v[A == 1,  B := list(list(identity))]
v
#   A          B
#1: 1 <function>
#2: 2


问:
define a function in which min() is used
I am trying to define a function in which I want a part of the function limited. I try to do this by using min() but it returns

```<code>The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

My code:

```<code>def f(x, beta):
    K_w = (1+((0.5*D)/(0.5*D+x))**2)**2
    K_c = min(11,(3.5*(x/D)**(-0.5)))   # <-- this is what gives me the problem. It should limit K_c to 11, but that does not work.
    K_tot = (K_c**2+K_w**2+2*K_c*K_w*np.cos(beta))**0.5
    return K_tot

x = np.linspace(0, 50, 100)
beta = np.linspace(0, 3.14, 180)

X, Y = np.meshgrid(x, beta)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 100, cmap = 'viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
</code>```

I expected K_c to be limited to 11, but it gave a

```<code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I might be making a rookie mistake, but help is much appreciated!

答:
Consider using np.clip of which its references can be found here.

```<code>np.clip(3.5*(x/D)**(-0.5), None, 11)
</code>```

for your case.

For example,

```<code>>>> import numpy as np
>>> np.clip([1, 2, 3, 15], None, 11)
array([ 1,  2,  3, 11])
</code>```

The problem with your code is that min is comparing a number with a list of which this is not expected.

Alternatively, here is a list comprehension approach:

```<code>A = [1, 2, 3, 15]
B = [min(11, a) for a in A]
print(B)
</code>```

Body:
I am trying to define a function in which I want a part of the function limited. I try to do this by using min() but it returns

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

My code:

def f(x, beta):
    K_w = (1+((0.5*D)/(0.5*D+x))**2)**2
    K_c = min(11,(3.5*(x/D)**(-0.5)))   # <-- this is what gives me the problem. It should limit K_c to 11, but that does not work.
    K_tot = (K_c**2+K_w**2+2*K_c*K_w*np.cos(beta))**0.5
    return K_tot

x = np.linspace(0, 50, 100)
beta = np.linspace(0, 3.14, 180)

X, Y = np.meshgrid(x, beta)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 100, cmap = 'viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');

I expected K_c to be limited to 11, but it gave a

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I might be making a rookie mistake, but help is much appreciated!

Body:
Consider using np.clip of which its references can be found here.

np.clip(3.5*(x/D)**(-0.5), None, 11)

for your case.

For example,

>>> import numpy as np
>>> np.clip([1, 2, 3, 15], None, 11)
array([ 1,  2,  3, 11])

The problem with your code is that min is comparing a number with a list of which this is not expected.

Alternatively, here is a list comprehension approach:

A = [1, 2, 3, 15]
B = [min(11, a) for a in A]
print(B)


问:
Initializing properties inside ngOnInit scope
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

```<code>private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];
</code>```

I expect output to not be undefined and be the data that is in the response

答:
fill your fields only when you get data like this:   </p>

```<code>private siteData: Kiosk;
site: any[];

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             site = [{title: data.title}];
    });
  }
</code>```

Body:
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];

I expect output to not be undefined and be the data that is in the response

Body:
fill your fields only when you get data like this:

private siteData: Kiosk;
site: any[];

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             site = [{title: data.title}];
    });
  }


问:
Calculate new column in pandas based on certain criteria
I am trying to multiple a two df based on certain values.

```<code>data = {'a':10,'b':20,'c':30} .
</code>```

df1:

```<code>id,tag,factor
1,a ,20
2,b ,22
3,c ,25
</code>```

my final result should look like something below:

```<code>id,factor,calc
1,20,200
2,22,440
3,24,750
</code>```

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

答:
```<code>df['calc'] = df['factor'] * pd.Series([data[key] for key in df["tag"]])
</code>```

OUTPUT

```<code>   id  factor  calc
0   1      20   200
1   2      22   440
2   3      25   750
</code>```

Body:
I am trying to multiple a two df based on certain values.

data = {'a':10,'b':20,'c':30} .

df1:

id,tag,factor
1,a ,20
2,b ,22
3,c ,25

my final result should look like something below:

id,factor,calc
1,20,200
2,22,440
3,24,750

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

Body:
df['calc'] = df['factor'] * pd.Series([data[key] for key in df["tag"]])

OUTPUT

   id  factor  calc
0   1      20   200
1   2      22   440
2   3      25   750


问:
Advanced table-layout to CSS
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

```<code>     padding-left: 200000px;
     margin-left: -200000px;
</code>```

To fake the expansion to the left?

答:
I would possibly do it like this:

Live Demo

CSS:

```<code>html, body {
    margin: 0;
    padding: 0;
    border: 0;
    overflow-x: hidden
}
body {
    background: #eee
}
#container {
    width: 300px;
    margin: 0 auto;
    background: #bbb;
}
li, li span {
    height: 25px;
}
li {
    position: relative;
    width: 200px;
    background: #777
}
li span {
    display: block;
    position: absolute;
    width: 9999px;
    left: -9999px;
    top: 0;
    background: url(http://dummyimage.com/50x30/f0f/fff)
}
</code>```

HTML:

```<code><div id="container">
    <ul>
        <li><span></span>Menu Item</li>
    </ul>
    <div id="content">
        Hi!
    </div>
</div>
</code>```

This answer was based on an older answer I wrote: 'Stretching' a div to the edge of a browser

Title: Advanced table-layout to CSS

Body:
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

     padding-left: 200000px;
     margin-left: -200000px;

To fake the expansion to the left?

Body:
I would possibly do it like this:

Live Demo

CSS:

html, body {
    margin: 0;
    padding: 0;
    border: 0;
    overflow-x: hidden
}
body {
    background: #eee
}
#container {
    width: 300px;
    margin: 0 auto;
    background: #bbb;
}
li, li span {
    height: 25px;
}
li {
    position: relative;
    width: 200px;
    background: #777
}
li span {
    display: block;
    position: absolute;
    width: 9999px;
    left: -9999px;
    top: 0;
    background: url(http://dummyimage.com/50x30/f0f/fff)
}

HTML:

<div id="container">
    <ul>
        <li><span></span>Menu Item</li>
    </ul>
    <div id="content">
        Hi!
    </div>
</div>

This answer was based on an older answer I wrote: 'Stretching' a div to the edge of a browser


问:
Render datatables doesn't work after ajax.reload
I have a code for expired date check when the data expired row change it background color,like this
success if expired date
but when I insert new row or search data background color is disappears,when table.ajax.reload();

my ajax render script

```<code>"aoColumns": [
                ../
                { "mData": "expired",
                "render": function ( data, type, row, meta ) {
                    var today = '<?php echo date("d/m/Y"); ?>';
                    if (data < today) {
                        $("td")
                        .filter(function() { return $.text([this]) == data; })
                        .parent()
                        .addClass("expired-date");
                        return '<td>'+data+'</td>';
                    }
                    else {
                        $("td")
                        .filter(function() { return $.text([this]) == data; })
                        .parent()
                        .removeClass("expired-date");
                        return '<td>'+data+'</td>';
                    }
                }
            },
</code>```

how does the background color not disappear after table.ajax.reload();?

答:
If you need to modify entire row style by assigning 'expired-date' class for outdated entries it is more logical to use createdRow option, e.g. like this:

```<code>$('#yourTableId').DataTable({
    ...
    createdRow: (tr, data) => new Date(data.expired.split('/').reverse().join('/')) < (new Date()).setHours(0,0,0,0) ? $(tr).addClass('expired-date') : true
});
</code>```

Also, you don't need to inject today serverside, you may get it user end just like I did above, assuming you got your dates in DD/MM/YYYY format as it can be seen on your screenshot. Otherwise, if user didn't refresh the entire page for a few days he may get unexpected results as certain entries will not get highlighted.

Body:
I have a code for expired date check when the data expired row change it background color,like this
success if expired date
but when I insert new row or search data background color is disappears,when table.ajax.reload();

my ajax render script

"aoColumns": [
                ../
                { "mData": "expired",
                "render": function ( data, type, row, meta ) {
                    var today = '<?php echo date("d/m/Y"); ?>';
                    if (data < today) {
                        $("td")
                        .filter(function() { return $.text([this]) == data; })
                        .parent()
                        .addClass("expired-date");
                        return ''+data+'	';
                    }
                    else {
                        $("td")
                        .filter(function() { return $.text([this]) == data; })
                        .parent()
                        .removeClass("expired-date");
                        return ''+data+'	';
                    }
                }
            },

how does the background color not disappear after table.ajax.reload();?

Body:
If you need to modify entire row style by assigning 'expired-date' class for outdated entries it is more logical to use createdRow option, e.g. like this:

$('#yourTableId').DataTable({
    ...
    createdRow: (tr, data) => new Date(data.expired.split('/').reverse().join('/')) < (new Date()).setHours(0,0,0,0) ? $(tr).addClass('expired-date') : true
});

Also, you don't need to inject today serverside, you may get it user end just like I did above, assuming you got your dates in DD/MM/YYYY format as it can be seen on your screenshot. Otherwise, if user didn't refresh the entire page for a few days he may get unexpected results as certain entries will not get highlighted.


问:
Comparing two Strings using Java 8 features
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

```<code>public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);
</code>```

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

```<code>public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);
</code>```

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

答:
Since Java 8 features is an abstract concept and includes all things introduced by Java 8, why not use BiPredicate?</p>

```<code>BiPredicate<String, String> checkIfStringsAreEqual = (str1, str2) -> Objects.nonNull(str1) && Objects.nonNull(str2) && str1.equals(str2);
System.out.println(checkIfStringsAreEqual.test(test1, test2));
</code>```

Body:
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

Body:
Since Java 8 features is an abstract concept and includes all things introduced by Java 8, why not use BiPredicate?

BiPredicate<String, String> checkIfStringsAreEqual = (str1, str2) -> Objects.nonNull(str1) && Objects.nonNull(str2) && str1.equals(str2);
System.out.println(checkIfStringsAreEqual.test(test1, test2));


问:
How can set dynamically path importResource, based on application.properties file?
I have this importResource @ImportResource({"classpath:spring/*/*.xml"})

I would set this path basing on value in application.properties file

I can pass dev or prod and the path should be classpath:spring/dev/*.xml or classpath:spring/prod/*.xml

答:
Something like this should work:

in application.properties

```<code>my_profile=dev
</code>```

Then add the string parameter to the annotation:

```<code>@ImportResource({"classpath:spring/${my_profile}/*.xml"})
</code>```

You might also want to look how profiles are configured in spring: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

Body:
Something like this should work:

in application.properties

my_profile=dev

Then add the string parameter to the annotation:

@ImportResource({"classpath:spring/${my_profile}/*.xml"})

You might also want to look how profiles are configured in spring: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html


问:
Spring 5 Java Config Set Default Profile
In my older Spring 4 web-app, I used an applicationContext.xml file, and my default spring profile was as follows;

```<code><beans profile="default">
    <context:property-placeholder location="file:/opt/myapp/myapp-ws.properties" />
</beans>
</code>```

And now I am using Spring 5 Framework, but NOT Spring Boot 2.x, and I want to do this in my Java Config class.

My main configuration class looks like this;

```<code>@Configuration
@ComponentScan(basePackages = "com.tomholmes.myapp")
@EnableWebMvc
public class MyAppConfig
{

}
</code>```

And I have the AppInitializer as follows;

```<code>public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{

    private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);

    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class[]
        { MyAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class[]{};
    }

    @Override
    protected String[] getServletMappings()
    {
        return new String[]
        { "/api/*" };
    }
}
</code>```

I've been doing some research on the Net since there is a lot of information on this, but a lot of it conflates Spring Boot,and I just want a Spring 5 without Spring Boot solution.   I'll keep looking, I am sure this is a simple issue.

Thanks!

答:
I believe something like this might do the trick:

```<code>@Configuration
public class PropertiesConfig {

@Bean
public PropertyPlaceholderConfigurer properties() {
    final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();

    final List<Resource> resources = new ArrayList<>();
    resources.add(new FileSystemResource("/etc/app/application-{profile_1}.properties"));
    resources.add(new FileSystemResource("/etc/app/application-{profile_2}.properties"));

    ppc.setLocations(resourceLst.toArray(new Resource[]{}));
    return ppc;
}
</code>```

Please note, that this is just the suggestion, this code is not tested.

Profile specific application properties should be resolved automatically by current active profile.

Body:
In my older Spring 4 web-app, I used an applicationContext.xml file, and my default spring profile was as follows;

<beans profile="default">
    <context:property-placeholder location="file:/opt/myapp/myapp-ws.properties" />
</beans>

And now I am using Spring 5 Framework, but NOT Spring Boot 2.x, and I want to do this in my Java Config class.

My main configuration class looks like this;

@Configuration
@ComponentScan(basePackages = "com.tomholmes.myapp")
@EnableWebMvc
public class MyAppConfig
{

}

And I have the AppInitializer as follows;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{

    private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);

    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class[]
        { MyAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class[]{};
    }

    @Override
    protected String[] getServletMappings()
    {
        return new String[]
        { "/api/*" };
    }
}

I've been doing some research on the Net since there is a lot of information on this, but a lot of it conflates Spring Boot,and I just want a Spring 5 without Spring Boot solution.   I'll keep looking, I am sure this is a simple issue.

Thanks!

Body:
I believe something like this might do the trick:

@Configuration
public class PropertiesConfig {

@Bean
public PropertyPlaceholderConfigurer properties() {
    final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();

    final List<Resource> resources = new ArrayList<>();
    resources.add(new FileSystemResource("/etc/app/application-{profile_1}.properties"));
    resources.add(new FileSystemResource("/etc/app/application-{profile_2}.properties"));

    ppc.setLocations(resourceLst.toArray(new Resource[]{}));
    return ppc;
}

Please note, that this is just the suggestion, this code is not tested.

Profile specific application properties should be resolved automatically by current active profile.


问:
MS Chart control - pie chart transparency
I'm trying to get a pie chart to display as transparent. Ideally it should look like the 3rd chart from the left on this page (link).

So far I've tried setting the transparency on the chartArea:

```<code><asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackGradientStyle="TopBottom"
            BackSecondaryColor="Transparent" BorderColor="64, 64, 64, 64"
            ShadowColor="Transparent">
</code>```

Also I tried setting it from codebehind:

```<code>    protected void pieChart_Customize(object sender, EventArgs e)
    {
        foreach (Series s in pieChart.Series)
        {
            s.Color = Color.FromArgb(128, s.Color);
        }
    }
</code>```

However neither of these approaches work. Has anybody managed to set the transparency on this type of chart control?

答:
I found the answer on the MSDN site: link

Here's the exact code that ended up working for me:

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        pieChart.Series[0].Palette = ChartColorPalette.SemiTransparent;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get a pie chart to display as transparent. Ideally it should look like the 3rd chart from the left on this page (link).

So far I've tried setting the transparency on the chartArea:

<asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackGradientStyle="TopBottom"
            BackSecondaryColor="Transparent" BorderColor="64, 64, 64, 64"
            ShadowColor="Transparent">

Also I tried setting it from codebehind:

    protected void pieChart_Customize(object sender, EventArgs e)
    {
        foreach (Series s in pieChart.Series)
        {
            s.Color = Color.FromArgb(128, s.Color);
        }
    }

However neither of these approaches work. Has anybody managed to set the transparency on this type of chart control?

Body:
I found the answer on the MSDN site: link

Here's the exact code that ended up working for me:

    protected void Page_Load(object sender, EventArgs e)
    {
        pieChart.Series[0].Palette = ChartColorPalette.SemiTransparent;
    }


问:
Can't find link element with driver.find_element_by_xpath for Selenium in Python
I am trying to click on the first link on the Google patents search page.

I used this to get to the link:

```<code>        result = driver.find_element_by_xpath("//a[@id='link']")
        result.click()
        time.sleep(10)
</code>```

However it does not find the link.

The HTML is:

```<code><a id="link" href="/patent/US7610070B2/en?assignee=Allegheny&page=1" class="style-scope state-modifier">
</code>```

Followed by:

```<code><h3 class="style-scope search-result-item"><raw-html class="style-scope search-result-item">
<span id="htmlContent" class="style-scope raw-html" style="display: inline;"> Dynamically configured antenna for multiple frequencies and bandwidths</span>
</code>```

Hope someone can help!

答:
Assuming that the search may return more than one result with the same id ("link"), try something like this:

```<code>result = driver.find_element_by_xpath("//*[@id='link'][1]")
</code>```

Note that the [1] select only the first element matching the condition (@id='link').

Body:
I am trying to click on the first link on the Google patents search page.

I used this to get to the link:

        result = driver.find_element_by_xpath("//a[@id='link']")
        result.click()
        time.sleep(10)

However it does not find the link.

The HTML is:

Followed by:

<raw-html class="style-scope search-result-item">
 Dynamically configured antenna for multiple frequencies and bandwidths

Hope someone can help!

Body:
Assuming that the search may return more than one result with the same id ("link"), try something like this:

result = driver.find_element_by_xpath("//*[@id='link'][1]")

Note that the [1] select only the first element matching the condition (@id='link').


问:
response.body is returning an empty file using scrapy in python
I am trying to make a web crawler, using scrapy from python, that extracts the information that google shows in the right side when you make a search

The URL I am using is: https://www.google.com/search?q=la%20cuarta

In this other question I asked the same (question), someone suggested me to write response.body to a file, but I am getting an empty file, when I tried a different URL this does not happend

This is my code:

```<code>import scrapy

class google1(scrapy.Spider):
    name = 'google1'

    def start_requests(self):
        urls = ['http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
        'https://www.google.com/search?q=la%20cuarta',
        'https://docs.scrapy.org/en/latest/intro/tutorial.html']
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'page-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)
</code>```

It does not even write the file from the google search, but in the scrapy shell response.body is not empty

答:
Ok, I tested your code and it works, that is the spiders downloads all the pages, including the googel page.
Your problem might be in the settings, add these to your settings:</p>

```<code>USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0'
ROBOTSTXT_OBEY = False
</code>```

Body:
I am trying to make a web crawler, using scrapy from python, that extracts the information that google shows in the right side when you make a search

The URL I am using is: https://www.google.com/search?q=la%20cuarta

In this other question I asked the same (question), someone suggested me to write response.body to a file, but I am getting an empty file, when I tried a different URL this does not happend

This is my code:

import scrapy

class google1(scrapy.Spider):
    name = 'google1'

    def start_requests(self):
        urls = ['http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
        'https://www.google.com/search?q=la%20cuarta',
        'https://docs.scrapy.org/en/latest/intro/tutorial.html']
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'page-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

It does not even write the file from the google search, but in the scrapy shell response.body is not empty

Body:
Ok, I tested your code and it works, that is the spiders downloads all the pages, including the googel page.
Your problem might be in the settings, add these to your settings:

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0'
ROBOTSTXT_OBEY = False


问:
Find all records associated with a user in same group as current_user
My models: User, Group, GroupsUser, and Availability.

I want to find all Availabilities created by users who are associated to a group, or several groups.

```<code>class Availability < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :group_users
  has_many :groups, through: :group_users

  has_many :availabilities
end

class Group < ApplicationRecord
  has_many :group_users
  has_many :users, through: :group_users
end

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
end
</code>```

Here is what I've tried to find all Availabilities created by a user in the same group as the first user. How can I make this query?

```<code>user = User.first

Availability.joins(:user).where('user.groups.pluck[:id] IN (?)', user.groups.pluck[:id])
</code>```

Would also be great to put a scope on the Group, but it throws an error each time I do that.

答:
There are two options to do so:

1) Through the join

```<code>Availability.joins(user: :groups).distinct
</code>```

2) Through the sub queries

```<code>Availability.where(user_id: User.joins(:groups).distinct.pluck(:id))
</code>```

If you need to filter Availability with a specific group you can add .where(groups: { name: 'Group name' }) condition

Body:
My models: User, Group, GroupsUser, and Availability.

I want to find all Availabilities created by users who are associated to a group, or several groups.

class Availability < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :group_users
  has_many :groups, through: :group_users

  has_many :availabilities
end

class Group < ApplicationRecord
  has_many :group_users
  has_many :users, through: :group_users
end

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
end

Here is what I've tried to find all Availabilities created by a user in the same group as the first user. How can I make this query?

user = User.first

Availability.joins(:user).where('user.groups.pluck[:id] IN (?)', user.groups.pluck[:id])

Would also be great to put a scope on the Group, but it throws an error each time I do that.

Body:
There are two options to do so:

1) Through the join

Availability.joins(user: :groups).distinct

2) Through the sub queries

Availability.where(user_id: User.joins(:groups).distinct.pluck(:id))

If you need to filter Availability with a specific group you can add .where(groups: { name: 'Group name' }) condition


问:
How to update NetSuite through Salesforce?
How would you go about updating NetSuite through Salesforce.
I know that you would use NetSuite's RESTlet and Salesforce Apex code to connect the two, but how would you actually go about doing this in a step by step process?</p>

答:
To send data from Salesforce to NetSuite (specifically customer/account data) you will need to do some preliminary setup in both.

In NetSuite:

Create a RESTlet Script that has at the bare minimum a get and post.
For instance I would create a javascript file on my desktop that contains:

```<code>/**
 *@NApiVersion 2.x
 *@NScriptType restlet
 */

//Use: Update NS customer with data (context) that is passed from SF

define(['N/record'], function(record) //use the record module
{
    function postData(context)
    {
        //load the customer I'm gonna update
        var cust = record.load({type:context.recordtype, id:context.id});
        log.debug("postData","loaded the customer with NSID: " + context.id);

        //set some body fields
        cust.setValue("companyname", context.name);
        cust.setValue("entityid", context.name + " (US LLC)");
        cust.setValue("custentity12", context.formerName);
        cust.setValue("phone",context.phone);
        cust.setValue("fax",context.fax);

        //remove all addresses
        while(cust.getLineCount('addressbook') != 0)
            cust.removeLine('addressbook',0);

        //add default billing address
        cust.insertLine('addressbook',0);
        cust.setSublistValue('addressbook','defaultbilling',0,true);
        cust.setSublistValue('addressbook','label',0,'BILL_TO');
        var billingAddress=cust.getSublistSubrecord('addressbook','addressbookaddress',0);
        billingAddress.setValue('country',context.billingCountry);
        billingAddress.setValue('addr1', context.billingStreet);
        billingAddress.setValue('city',context.billingCity);
        billingAddress.setValue('state',context.billingState);
        billingAddress.setValue('zip',context.billingZip);

        //add default shipping address
        cust.insertLine('addressbook',0);
        cust.setSublistValue('addressbook','defaultshipping',0,true);
        cust.setSublistValue('addressbook','label',0,'SHIP_TO');
        var shippingAddress=cust.getSublistSubrecord('addressbook','addressbookaddress',0);
        shippingAddress.setValue('country',context.shippingCountry);
        shippingAddress.setValue('addr1',context.shippingStreet);
        shippingAddress.setValue('city',context.shippingCity);
        shippingAddress.setValue('state',context.shippingState);
        shippingAddress.setValue('zip',context.shippingZip);

        //save the record
        var NSID = cust.save();
        log.debug("postData","saved the record with NSID: " + NSID);
        return NSID; //success return the ID to SF
    }

    //get and post both required, otherwise it doesn't work
    return {
      get : function (){return "get works";},
      post : postData //this is where the sauce happens
    };
});
</code>```

After You've saved this file, go to NetSuite>Customization>Scripting>Scripts>New.

Select the new file that you've saved and create the script record. Your script record in NetSuite should have GET and POST checked under scripts.

Next, click deploy script and choose who will call this script, specifically the user that will login on the salesforce end into NetSuite.

On the deployment page you will need the External URL it goes something like:
https://1234567.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1

Note: If any data that you are updating is critical for a process, I would highly recommond creating this in the sandbox first for testing, before moving to production.

In Salesforce sandbox:

Click YourName>Developer Console
In the developer console click File>New and create an Apex Class:

```<code>global class NetSuiteWebServiceCallout
{
    @future (callout=true) //allow restlet callouts to run asynchronously
    public static void UpdateNSCustomer(String body)
    {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndPoint('https://1234567.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1'); //external URL
        request.setMethod('POST');
        request.setHeader('Authorization', 'NLAuth nlauth_account=1234567, nlauth_email=login@login.com, nlauth_signature=password'); //login to netsuite, this person must be included in the NS restlet deployment
        request.setHeader('Content-Type','application/json');
        request.setBody(body);
        HttpResponse response = http.send(request);
        System.debug(response);
        System.debug(response.getBody());
    }
}
</code>```

You will have to set the endpoint here to the external url, the authorization nlauth_account=[your netsuite account number], and the header to your login email and password to a person who is on the deployment of the NS script, the body will be set in the trigger that calls this class.

Next create the trigger that will call this class. I made this script run every time I update the account in Salesforce.

```<code>trigger UpdateNSCustomer on Account (after update)
{
    for(Account a: Trigger.new)
    {
        String data = ''; //what to send to NS
        data = data + '{"recordtype":"customer","id":"'+a.Netsuite_Internal_ID__c+'","name":"'+a.Name+'","accountCode":"'+a.AccountCode__c+'",';
        data = data + '"formerName":"'+a.Former_Company_Names__c+'","phone":"'+a.Phone+'","fax":"'+a.Fax+'","billingStreet":"'+a.Billing_Street__c+'",';
        data = data + '"billingCity":"'+a.Billing_City__c+'","billingState":"'+a.Billing_State_Province__c+'","billingZip":"'+a.Billing_Zip_Postal_Code__c+'",';
        data = data + '"billingCountry":"'+a.Billing_Country__c+'","shippingStreet":"'+a.Shipping_Street__c+'","shippingCity":"'+a.Shipping_City__c+'",';
        data = data + '"shippingState":"'+a.Shipping_State_Province__c+'","shippingZip":"'+a.Shipping_Zip_Postal_Code__c+'","shippingCountry":"'+a.Shipping_Country__c+'"}';
        data = data.replaceAll('null','').replaceAll('\n',',').replace('\r','');
        System.debug(data);
        NetSuiteWebServiceCallout.UpdateNSCustomer(data); //call restlet
    }
}
</code>```

In this script data is the body that you are sending to NetSuite.

Additionally, you will have to create an authorized endpoint for NetSuite in your remote site setings in salesforce (sandbox and production). Go to setup, and quickfind remote site settings which will be under security controls.
Create a new Remote site that has its remote site URL set to the first half of your external url: https://1234567.restlets.api.netsuite.com.

From here, do some testing in the sandbox.
If all looks well deploy the class and trigger to salesforce production.

Body:
To send data from Salesforce to NetSuite (specifically customer/account data) you will need to do some preliminary setup in both.

In NetSuite:

Create a RESTlet Script that has at the bare minimum a get and post.
For instance I would create a javascript file on my desktop that contains:

/**
 *@NApiVersion 2.x
 *@NScriptType restlet
 */

//Use: Update NS customer with data (context) that is passed from SF

define(['N/record'], function(record) //use the record module
{
    function postData(context)
    {
        //load the customer I'm gonna update
        var cust = record.load({type:context.recordtype, id:context.id});
        log.debug("postData","loaded the customer with NSID: " + context.id);

        //set some body fields
        cust.setValue("companyname", context.name);
        cust.setValue("entityid", context.name + " (US LLC)");
        cust.setValue("custentity12", context.formerName);
        cust.setValue("phone",context.phone);
        cust.setValue("fax",context.fax);

        //remove all addresses
        while(cust.getLineCount('addressbook') != 0)
            cust.removeLine('addressbook',0);

        //add default billing address
        cust.insertLine('addressbook',0);
        cust.setSublistValue('addressbook','defaultbilling',0,true);
        cust.setSublistValue('addressbook','label',0,'BILL_TO');
        var billingAddress=cust.getSublistSubrecord('addressbook','addressbookaddress',0);
        billingAddress.setValue('country',context.billingCountry);
        billingAddress.setValue('addr1', context.billingStreet);
        billingAddress.setValue('city',context.billingCity);
        billingAddress.setValue('state',context.billingState);
        billingAddress.setValue('zip',context.billingZip);

        //add default shipping address
        cust.insertLine('addressbook',0);
        cust.setSublistValue('addressbook','defaultshipping',0,true);
        cust.setSublistValue('addressbook','label',0,'SHIP_TO');
        var shippingAddress=cust.getSublistSubrecord('addressbook','addressbookaddress',0);
        shippingAddress.setValue('country',context.shippingCountry);
        shippingAddress.setValue('addr1',context.shippingStreet);
        shippingAddress.setValue('city',context.shippingCity);
        shippingAddress.setValue('state',context.shippingState);
        shippingAddress.setValue('zip',context.shippingZip);

        //save the record
        var NSID = cust.save();
        log.debug("postData","saved the record with NSID: " + NSID);
        return NSID; //success return the ID to SF
    }

    //get and post both required, otherwise it doesn't work
    return {
      get : function (){return "get works";},
      post : postData //this is where the sauce happens
    };
});

After You've saved this file, go to NetSuite>Customization>Scripting>Scripts>New.

Select the new file that you've saved and create the script record. Your script record in NetSuite should have GET and POST checked under scripts.

Next, click deploy script and choose who will call this script, specifically the user that will login on the salesforce end into NetSuite.

On the deployment page you will need the External URL it goes something like:
https://1234567.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1

Note: If any data that you are updating is critical for a process, I would highly recommond creating this in the sandbox first for testing, before moving to production.

In Salesforce sandbox:

Click YourName>Developer Console
In the developer console click File>New and create an Apex Class:

global class NetSuiteWebServiceCallout
{
    @future (callout=true) //allow restlet callouts to run asynchronously
    public static void UpdateNSCustomer(String body)
    {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndPoint('https://1234567.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1'); //external URL
        request.setMethod('POST');
        request.setHeader('Authorization', 'NLAuth nlauth_account=1234567, nlauth_email=login@login.com, nlauth_signature=password'); //login to netsuite, this person must be included in the NS restlet deployment
        request.setHeader('Content-Type','application/json');
        request.setBody(body);
        HttpResponse response = http.send(request);
        System.debug(response);
        System.debug(response.getBody());
    }
}

You will have to set the endpoint here to the external url, the authorization nlauth_account=[your netsuite account number], and the header to your login email and password to a person who is on the deployment of the NS script, the body will be set in the trigger that calls this class.

Next create the trigger that will call this class. I made this script run every time I update the account in Salesforce.

trigger UpdateNSCustomer on Account (after update)
{
    for(Account a: Trigger.new)
    {
        String data = ''; //what to send to NS
        data = data + '{"recordtype":"customer","id":"'+a.Netsuite_Internal_ID__c+'","name":"'+a.Name+'","accountCode":"'+a.AccountCode__c+'",';
        data = data + '"formerName":"'+a.Former_Company_Names__c+'","phone":"'+a.Phone+'","fax":"'+a.Fax+'","billingStreet":"'+a.Billing_Street__c+'",';
        data = data + '"billingCity":"'+a.Billing_City__c+'","billingState":"'+a.Billing_State_Province__c+'","billingZip":"'+a.Billing_Zip_Postal_Code__c+'",';
        data = data + '"billingCountry":"'+a.Billing_Country__c+'","shippingStreet":"'+a.Shipping_Street__c+'","shippingCity":"'+a.Shipping_City__c+'",';
        data = data + '"shippingState":"'+a.Shipping_State_Province__c+'","shippingZip":"'+a.Shipping_Zip_Postal_Code__c+'","shippingCountry":"'+a.Shipping_Country__c+'"}';
        data = data.replaceAll('null','').replaceAll('\n',',').replace('\r','');
        System.debug(data);
        NetSuiteWebServiceCallout.UpdateNSCustomer(data); //call restlet
    }
}

In this script data is the body that you are sending to NetSuite.

Additionally, you will have to create an authorized endpoint for NetSuite in your remote site setings in salesforce (sandbox and production). Go to setup, and quickfind remote site settings which will be under security controls.
Create a new Remote site that has its remote site URL set to the first half of your external url: https://1234567.restlets.api.netsuite.com.

From here, do some testing in the sandbox.
If all looks well deploy the class and trigger to salesforce production.


问:
Elegant and maintainable way of populating Tree structures in c#
I have a Tree.

```<code>class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}
</code>```

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

```
Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2
```

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

```<code>var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);
</code>```

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

答:
Ideally you want a way to extend the language to literals of custom types.   C# doesn't have this, so you have to find another approach.

You can fabricate an internal DSL, typically with a fluent interface.

Follow the XElement example of functional construction.

Create an external DSL with a custom parser. If you design the language carefully, the parser can be easy.

Use XML. Basically this is a way to create an external DSL and get the parser for free.

The external DSL options are nice because when you read them, you know there's only data, and don't have to worry about making sense of code constructs. Also, the data is the file, and the file is the data.  That makes it easy to swap data around by changing files, and easier to ready file change histories.  Finally, and external DSL is good when a non-programmer will be supplying the data.

The tradeoff here is time vs. value. How much data you will have / how often it will change / who will change it are the questions you have to answer.

Body:
I have a Tree.

class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

OwnerDisplayName: Jay Bazuzi


问:
JS bookmarklet issue: Code works in console, fails in bookmarklet
Using a JS bookmarklet to set a custom field in the Wordpress Edit Post screen. The following code works well when I copy/paste it into the console (latest Chrome stable):

```<code>document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();
</code>```

Works without a hitch; I jut paste this into the console, and a new custom var is added to the post (I have "foo" as a var name in WP already).

In bookmarklet form, this same code looks like this:

```<code>javascript:document.getElementById('metakeyselect').value = "foo";document.getElementById('metavalue').value = "bar";document.getElementById('meta-add-submit').click();
</code>```

And it fails: When I click it, the Name and Value boxes are filled in, but nothing gets submitted. The console shows the following error:

```<code>Uncaught TypeError: Cannot call method 'click' of null
</code>```

Any idea why? Same exact code, same browser, same page.

答:
I had a similar problem and am quite sure that's what causes your code to break too.
My minimal example would be the following code on this website (should work afor the entire stackoverflow.com domain):

```<code>document.getElementsByName("q")[0].value="foo";
</code>```

This should write "foo" to the search field (that has no id but is the only element with the name "q"). Both web console and bookmarklet will set the value as expected but the bookmarklet will also change the page to an empty header and a body containing only the word "foo" after a short delay. Assuming that this is not a random bug that only applies to me, the reason for the thrown exception in your example is that the bookmarklet sets the value "foo", then "bar" but changes the content of the web page to "foo", then "bar" before your last line terminates.

Unfortunately I don't know the reason for this behaviour (I found this question looking for that exact information) but that is what most likely causes the TypeError in your excample.

It is possible that the same code runs without any problems when used in a Greasemonkey script (e.g. as the onclick script of a button you added using Greasemonkey).

[Edit:] Apparently, if a bookmarklet evaluates to anything other than undefined, the inner html of the website is replaced by a string representation of that value. To make sure that the bookmarklet evaluates to undefined, you can just type undefined as the last line outside of any condition block. unfortunately that means it is less likely that my assumption toward OP's error is correct but at least future visitors still might find this information usefull.

Body:
Using a JS bookmarklet to set a custom field in the Wordpress Edit Post screen. The following code works well when I copy/paste it into the console (latest Chrome stable):

document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();

Works without a hitch; I jut paste this into the console, and a new custom var is added to the post (I have "foo" as a var name in WP already).

In bookmarklet form, this same code looks like this:

javascript:document.getElementById('metakeyselect').value = "foo";document.getElementById('metavalue').value = "bar";document.getElementById('meta-add-submit').click();

And it fails: When I click it, the Name and Value boxes are filled in, but nothing gets submitted. The console shows the following error:

Uncaught TypeError: Cannot call method 'click' of null

Any idea why? Same exact code, same browser, same page.

Body:
I had a similar problem and am quite sure that's what causes your code to break too.
My minimal example would be the following code on this website (should work afor the entire stackoverflow.com domain):

document.getElementsByName("q")[0].value="foo";

This should write "foo" to the search field (that has no id but is the only element with the name "q"). Both web console and bookmarklet will set the value as expected but the bookmarklet will also change the page to an empty header and a body containing only the word "foo" after a short delay. Assuming that this is not a random bug that only applies to me, the reason for the thrown exception in your example is that the bookmarklet sets the value "foo", then "bar" but changes the content of the web page to "foo", then "bar" before your last line terminates.

Unfortunately I don't know the reason for this behaviour (I found this question looking for that exact information) but that is what most likely causes the TypeError in your excample.

It is possible that the same code runs without any problems when used in a Greasemonkey script (e.g. as the onclick script of a button you added using Greasemonkey).

[Edit:] Apparently, if a bookmarklet evaluates to anything other than undefined, the inner html of the website is replaced by a string representation of that value. To make sure that the bookmarklet evaluates to undefined, you can just type undefined as the last line outside of any condition block. unfortunately that means it is less likely that my assumption toward OP's error is correct but at least future visitors still might find this information usefull.


答:
Using list comprehension

```<code>df1['calc'] = [x.factor * data[x.tag] for i, x in df1.iterrows()]
</code>```

Output is

```<code>   id tag  factor  calc
0   1   a      20   200
1   2   b      22   440
2   3   c      25   750
</code>```

Title: Calculate new column in pandas based on certain criteria

Body:
I am trying to multiple a two df based on certain values.

data = {'a':10,'b':20,'c':30} .

df1:

id,tag,factor
1,a ,20
2,b ,22
3,c ,25

my final result should look like something below:

id,factor,calc
1,20,200
2,22,440
3,24,750

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

Body:
Using list comprehension

df1['calc'] = [x.factor * data[x.tag] for i, x in df1.iterrows()]

Output is

   id tag  factor  calc
0   1   a      20   200
1   2   b      22   440
2   3   c      25   750