问:
Proper usage of twoLineListItem Android
I am new to development on android and trying to create a list that has a bold header

and a smaller description for each item.
Like the one shown here (sorry can't post images yet):

http://i.stack.imgur.com/UVqzq.png

This is the XML that I have to start with:

```<code><LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TwoLineListItem android:layout_width="fill_parent"
android:layout_height="wrap_content" android:mode="twoLine">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_below="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_alignLeft="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@android:id/text2" />
</TwoLineListItem>
</LinearLayout>
</code>```

Is there a way to populate the list from an array in another xml file?  If not how would I populate a list like this from the Java code?  Like I said I'm new to development, so I'm probably way off.  Thanks for any input!

答:
I have a similar implementation, but instead of a 2 line listview, I have 3 lines.

This is the XML:

```<code><LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical"  >
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="17sp"
        android:textStyle="bold"
        android:text="PROJECT NAME"
        android:typeface="monospace"
        android:paddingBottom="2dp"
        android:paddingTop="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:gravity="left|center"   >
    </TextView>
    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:text="Selected Type"
        android:textSize="16sp"
        android:paddingBottom="1dp"
        android:paddingTop="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"  >
    </TextView>
    <TextView
        android:id="@+id/text3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="16sp"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Project Description"  >
    </TextView>
</LinearLayout>
</code>```

And this is the JAVA code for filling the lines with data returned from a DB. This code is in the onCreate() method:

```<code>String[] fields = new String[]  {   db.TABLE_PRJ_NAME, db.TABLE_PRJ_TYPE, db.TABLE_PRJ_DESC };
    int[] views = new int[] {   R.id.text1, R.id.text2, R.id.text3  };

    c = db.getAllProjects();
    startManagingCursor(c);

    // Set the ListView
    SimpleCursorAdapter prjName = new SimpleCursorAdapter(
            this,
            R.layout.project_list_rows,
            //android.R.layout.simple_list_item_1,
            c, fields, views);
    setListAdapter(prjName);
</code>```

Title: Proper usage of twoLineListItem Android

Body:
I am new to development on android and trying to create a list that has a bold header

and a smaller description for each item.
Like the one shown here (sorry can't post images yet):

http://i.stack.imgur.com/UVqzq.png

This is the XML that I have to start with:

<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TwoLineListItem android:layout_width="fill_parent"
android:layout_height="wrap_content" android:mode="twoLine">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_below="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_alignLeft="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@android:id/text2" />
</TwoLineListItem>
</LinearLayout>

Is there a way to populate the list from an array in another xml file?  If not how would I populate a list like this from the Java code?  Like I said I'm new to development, so I'm probably way off.  Thanks for any input!

Body:
I have a similar implementation, but instead of a 2 line listview, I have 3 lines.

This is the XML:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical"  >
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="17sp"
        android:textStyle="bold"
        android:text="PROJECT NAME"
        android:typeface="monospace"
        android:paddingBottom="2dp"
        android:paddingTop="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:gravity="left|center"   >
    </TextView>
    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:text="Selected Type"
        android:textSize="16sp"
        android:paddingBottom="1dp"
        android:paddingTop="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"  >
    </TextView>
    <TextView
        android:id="@+id/text3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="16sp"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Project Description"  >
    </TextView>
</LinearLayout>

And this is the JAVA code for filling the lines with data returned from a DB. This code is in the onCreate() method:

String[] fields = new String[]  {   db.TABLE_PRJ_NAME, db.TABLE_PRJ_TYPE, db.TABLE_PRJ_DESC };
    int[] views = new int[] {   R.id.text1, R.id.text2, R.id.text3  };

    c = db.getAllProjects();
    startManagingCursor(c);

    // Set the ListView
    SimpleCursorAdapter prjName = new SimpleCursorAdapter(
            this,
            R.layout.project_list_rows,
            //android.R.layout.simple_list_item_1,
            c, fields, views);
    setListAdapter(prjName);


来源: stackexchange

问:
Debounce input to http service call
What I am currently doing is set the input 2-way-binding to appRequestParams.appName, and on every keyup event, the fetchApps() method will be called.

I am trying to debounce the input such that it will not fire off a backend http request on every keyup immediately.

I have read up on ways to go about doing it and here what I have come out with.

HTML

```<code><input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(searchBox.value)" />
</code>```

Typescript

```<code>private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           this.fetchApps();
       });
   }
</code>```

Error on line of .switchMap():

```<code>Argument of type '(value: string) => void' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.
</code>```

答:
The debounce related section of your code is fine. The problem is that you cant call switchMap withouth returning another observable.

SwitchMap basically transforms the last emitted value of an Observable into another Observable, giving the extra ability of autocanceling on the fly http requests.

Try the following:

```<code>private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       });
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           return this.fetchApps();
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }
</code>```

A typical example is associated to the route parameters in ActivatedRoute. Consider the following:

```<code>  @Injectable()
  export class FooService{
    ..
    getFooById(id:string): Observable<FooInterface>{
        return this.http.get('endpoint/${id}')
         .map(res=>res.json())
         .catch(_throw(error));
    }
  }
</code>```

Now we navigate to something like root/foo/10980312 , where the last part is defined as :id in the routing

```<code>@Component({...})
class FooPreviewComponent{
  data: FooInterface;
  constructor(
    private _route: ActivatedRoute,
    private _service: FooService) {
     this._route.params
        .switchMap(params=>
          this._service.getFooById(params.id))//switchMap return type is Observable<FooInterface> because of the definition of getFooById
        .subscribe(fooElement => this.data); //intellisense will detect the type of fooElement as FooInterface because of the return type of switchmap
  }
}
</code>```

During the time that the http is being processed, if we now navigate to root/foo/1312313, the previous request will be automatically canceled.

There are other applications for switchMap, but it requires some understanding of the internal/external observables an some internals of it.

Your solution is inefficient, because you are subscribing to the debounced input values and the http responses triggered by them, but you are doing nothing with the first, when you really just want to subscribe to the http responses. So you can save one of those subscriptions by using switchMap in the right way.

ContentLicense: CC BY-SA 3.0

Title: Debounce input to http service call

Body:
What I am currently doing is set the input 2-way-binding to appRequestParams.appName, and on every keyup event, the fetchApps() method will be called.

I am trying to debounce the input such that it will not fire off a backend http request on every keyup immediately.

I have read up on ways to go about doing it and here what I have come out with.

HTML

<input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(searchBox.value)" />

Typescript

private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           this.fetchApps();
       });
   }

Error on line of .switchMap():

Argument of type '(value: string) => void' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.

Body:
The debounce related section of your code is fine. The problem is that you cant call switchMap withouth returning another observable.

SwitchMap basically transforms the last emitted value of an Observable into another Observable, giving the extra ability of autocanceling on the fly http requests.

Try the following:

private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       });
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           return this.fetchApps();
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }

A typical example is associated to the route parameters in ActivatedRoute. Consider the following:

  @Injectable()
  export class FooService{
    ..
    getFooById(id:string): Observable<FooInterface>{
        return this.http.get('endpoint/${id}')
         .map(res=>res.json())
         .catch(_throw(error));
    }
  }

Now we navigate to something like root/foo/10980312 , where the last part is defined as :id in the routing

@Component({...})
class FooPreviewComponent{
  data: FooInterface;
  constructor(
    private _route: ActivatedRoute,
    private _service: FooService) {
     this._route.params
        .switchMap(params=>
          this._service.getFooById(params.id))//switchMap return type is Observable<FooInterface> because of the definition of getFooById
        .subscribe(fooElement => this.data); //intellisense will detect the type of fooElement as FooInterface because of the return type of switchmap
  }
}

During the time that the http is being processed, if we now navigate to root/foo/1312313, the previous request will be automatically canceled.

There are other applications for switchMap, but it requires some understanding of the internal/external observables an some internals of it.

Your solution is inefficient, because you are subscribing to the debounced input values and the http responses triggered by them, but you are doing nothing with the first, when you really just want to subscribe to the http responses. So you can save one of those subscriptions by using switchMap in the right way.


问:
Find if two strings are same in an array?
I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?</p>

答: I don't know how to do that specifically for swift but in general you can check every string of the array with any string after it in the array (just like the sorting algorithm) and if you find that a string is equal to another one then you have a double string in your array</p>


问:
The path to the driver executable must be set by the webdriver.chrome.driver system property;
```<code>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:199)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:120)
</code>```

答:
Here is the Answer to your Question:

When you work with Selenium 3.x you have to download chromedriver.exe from here and save it in your machine. Next you have to mention the absolute path of the chromedriver.exe through System.setProperty. While you mention the absolute path of the chromedriver.exe through System.setProperty you have either provide front slashes "/" or esacpe the back slases "\\". Here is your own working code with some simple tweaks:

```<code>public class first
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver","C:/your_directory/chromedriver.exe");
        WebDriver dr1= new ChromeDriver(); ;
        dr1.get("http://www.google.com/");
    }
}
</code>```

Let me know if this Answers your Question

Body:
Here is the Answer to your Question:

When you work with Selenium 3.x you have to download chromedriver.exe from here and save it in your machine. Next you have to mention the absolute path of the chromedriver.exe through System.setProperty. While you mention the absolute path of the chromedriver.exe through System.setProperty you have either provide front slashes "/" or esacpe the back slases "\\". Here is your own working code with some simple tweaks:

public class first
{
    public static void main(String args[])
    {
        System.setProperty("webdriver.chrome.driver","C:/your_directory/chromedriver.exe");
        WebDriver dr1= new ChromeDriver(); ;
        dr1.get("http://www.google.com/");
    }
}

Let me know if this Answers your Question


问:
Giving email account a name when sending emails with Django through Google Apps
I am sending emails to users using Django through Google Apps.

When the user receives emails sent from the Django app, they are from:
do_not_reply@domain.example

when looking at all emails in the inbox, people see the email's sender as:
do_not_reply or do_not_reply@domain.example depending on the email client used

If I log into that "do_not_reply" account using the browser and Google Apps itself and then send an email to myself, the emails are from:
Don't Reply <do_not_reply@domain.example>

As a result, the name displayed for the email's sender in the inbox is:
Don't Reply

In Django, is there a way to attach a "name" to the email account being used to send emails?

I have reviewed Django's mail.py, but had no luck finding a solution
http://code.djangoproject.com/browser/django/trunk/django/core/mail.py?rev=5548

Using:

Django 1.1

Python 2.6

Ubuntu 9.1

settings.EMAIL_HOST = smtp.gmail.com

答:
Apart from the send_mail method to send email, EmailMultiAlternatives can also be used to send email with HTML content with text content as an alternative.

try this in your project

```<code>from django.core.mail import EmailMultiAlternatives
text_content = "Hello World"
# set html_content
email = EmailMultiAlternatives('subject', text_content, 'Dont Reply <do_not_reply@domain.example>', ['youremail@example.com'])

email.attach_alternative(html_content, 'text/html')
email.send()
</code>```

This will send mail to youremail@example.com with Don't Reply wil be displayed as name instead of email do_not_reply@domain.example.

ContentLicense: CC BY-SA 4.0

Body:
Apart from the send_mail method to send email, EmailMultiAlternatives can also be used to send email with HTML content with text content as an alternative.

try this in your project

from django.core.mail import EmailMultiAlternatives
text_content = "Hello World"
# set html_content
email = EmailMultiAlternatives('subject', text_content, 'Dont Reply <do_not_reply@domain.example>', ['youremail@example.com'])

email.attach_alternative(html_content, 'text/html')
email.send()

This will send mail to youremail@example.com with Don't Reply wil be displayed as name instead of email do_not_reply@domain.example.


问:
Unreadable Notebook NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n {\\n "cell_type": "...',)
Getting this very strange error when I am trying to load my ipython notebook. Never had it before, and I cannot to my recollection, remember having done anything silly with ipython:

Unreadable Notebook: /path/to/notebooks/results.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n  {\\n   "cell_type": "...',)
```

<p>which is followed by</p>

<pre class="lang-none prettyprint-override"><code>400 GET /api/contents/results.ipynb?type=notebook&_=1440010858974 (127.0.0.1) 36.17ms referer=http://localhost:8888/notebooks/results.ipynb
</code>```

答:
This happened to me as well. I opened my data.ipynb file using notepad and found out it was blank.

I managed to recover my file by going into the hidden ipynb_checkpoints folder and copying data_checkpoint.ipynb out into my working directory.

In my Mac OS terminal

```<code>cd .ipynb_checkpoints
cp data-checkpoint.ipynb \..
</code>```

Thankfully the codes were preserved. Hope this helps!

Body:
Getting this very strange error when I am trying to load my ipython notebook. Never had it before, and I cannot to my recollection, remember having done anything silly with ipython:

Unreadable Notebook: /path/to/notebooks/results.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n  {\\n   "cell_type": "...',)

which is followed by

400 GET /api/contents/results.ipynb?type=notebook&_=1440010858974 (127.0.0.1) 36.17ms referer=http://localhost:8888/notebooks/results.ipynb

Body:
This happened to me as well. I opened my data.ipynb file using notepad and found out it was blank.

I managed to recover my file by going into the hidden ipynb_checkpoints folder and copying data_checkpoint.ipynb out into my working directory.

In my Mac OS terminal

cd .ipynb_checkpoints
cp data-checkpoint.ipynb \..

Thankfully the codes were preserved. Hope this helps!


问:
Object required error when using textbox
```<code>Private Sub TextBox1_Change()
Slide2.TextBox2.Value = Slide2.TextBox1.Value * 0.0225
Slide2.TextBox3.Value = Slide2.TextBox1.Value * 0.1
End Sub
</code>```

Everytime i run the presentation i get an object required error on line 2. I am fairly new to VBA so have no idea how to deal with it

答:
Maybe, coding  like this
Val(Slide2.TextBox1.Value)*0.1</p>

Body:
Private Sub TextBox1_Change()
Slide2.TextBox2.Value = Slide2.TextBox1.Value * 0.0225
Slide2.TextBox3.Value = Slide2.TextBox1.Value * 0.1
End Sub

Everytime i run the presentation i get an object required error on line 2. I am fairly new to VBA so have no idea how to deal with it


问:
Export data from SQL Server view to table with additional header row
I am using a view to feed a table in my database. While feeding the table, I am also adding a header row to the table. I am doing this for 5 tables.

However, for 2 tables, I could see that the header row in inserted at the top most where as for remaining 5 tables, the header row goes down. How can I fix it?

This is the query I am using to feed the data. I could see the header as 1st row in the JOB and EMPJOB tables.

```<code>INSERT INTO [JOB_Export](Job_Cd, Job_Name, Job_Note, Job_URL, OptJob_Currency, Domain_OrgCd, OptJob_Txt1, OptJob_Txt2, OptJob_Txt3, OptJob_Txt4, OptJob_Dt1, OptJob_Dt2, OptJob_Int1, OptJob_MONEY, OptJob_FLOAT1, OptJob_Ind1, OptJob_Memo1)
    SELECT
        'JOB_CODE' AS "JOB_CODE", 'JOB_NAME' AS "JOB_NAME",
        'JOB_DESC' AS "JOB_DESC", 'JOB_URL' AS "JOB_URL",
        'JOB_CURRENCY_CD' AS "JOB_CURRENCY_CD", 'JOB_DOMAIN' AS "JOB_DOMAIN",
        'CUSTOM_TEXT1' AS "CUSTOM_TEXT1", 'CUSTOM_TEXT2' AS "CUSTOM_TEXT2",
        'CUSTOM_TEXT3' AS "CUSTOM_TEXT3", 'CUSTOM_TEXT4' AS "CUSTOM_TEXT4",
        'CUSTOM_DATE1' AS "CUSTOM_DATE1", 'CUSTOM_DATE2' AS "CUSTOM_DATE2",
        'CUSTOM_INTEGER1' AS "CUSTOM_INTEGER1", 'CUSTOM_MONEY1'AS "CUSTOM_MONEY1",
        'CUSTOM_FLOAT1' AS "CUSTOM_FLOAT1", 'CUSTOM_IND1' AS "CUSTOM_IND1",
        'CUSTOM_MEMO1' AS "CUSTOM_MEMO1"
    UNION
    SELECT
        RTRIM(Job_Cd),
        Job_Name,
        CONVERT (VARCHAR(MAX),Job_Note) Job_Note,
        CONVERT (VARCHAR(255), Job_URL) Job_URL,
        CONVERT (VARCHAR(50), OptJob_Currency) OptJob_Currency,
        Domain_OrgCd,
        OptJob_Txt1,
        CONVERT (VARCHAR(255), OptJob_Txt2) OptJob_Txt2,
        CONVERT (VARCHAR(255), OptJob_Txt3)  OptJob_Txt3 ,
        CONVERT (VARCHAR(255), OptJob_Txt4)  OptJob_Txt4 ,
        CONVERT (VARCHAR(500), OptJob_Dt1)  OptJob_Dt1 ,
        CONVERT (VARCHAR(500), OptJob_Dt2)  OptJob_Dt2 ,
        CONVERT (VARCHAR(500), OptJob_Int1)  OptJob_Int1 ,
        CONVERT (VARCHAR(500), OptJob_MONEY) OptJob_MONEY ,
        CONVERT (VARCHAR(500), OptJob_FLOAT1) OptJob_FLOAT1,
        CONVERT (VARCHAR(500), OptJob_Ind1)  OptJob_Ind1 ,
        CONVERT (VARCHAR(MAX), OptJob_Memo1)   OptJob_Memo1
    FROM
        [OVERRIDE_JOB_VIEW]

INSERT INTO [EMPJOB_Export](Emp_No,Job_Cd,EmpJob_JoiningDate,EmpJob_PrmyInd,Domain_Cd)
SELECT 'EMP_NO' AS "EMP_NO",'JOB_CODE' AS "JOB_CODE",'JOIN_DATE' AS"JOIN_DATE",'PRIMARY' AS "PRIMARY",'JOB_DOMAIN' AS "JOB_DOMAIN"
UNION
SELECT [Emp_No],
    CASE    WHEN LEN(Job_Cd)<=30 THEN CONVERT (VARCHAR(500), JOB_CD)
    ELSE CONVERT(VARCHAR(500),SUBSTRING(rtrim([Job_Cd]),1,30))
    END AS Job_Cd,
    CONVERT(VARCHAR(500),[EmpJob_JoiningDate]) [EmpJob_JoiningDate] ,
    [EmpJob_PrmyInd],
    CASE    WHEN LEN(rtrim([Domain_Cd]))<=50 THEN [Domain_Cd]
    ELSE SUBSTRING(rtrim([Domain_Cd]),1,50)
    END AS [Domain_Cd]
    FROM [EMPJOB_VIEW]

INSERT INTO [EMPORG_Export] (Emp_No,Org_Cd,EmpOrg_JoiningDate,EmpOrg_RoleName,EmpOrg_PrmyInd,EmpOrg_DomainInd)
SELECT 'EMP_NO' AS "EMP_NO",'ORG_CODE' AS "ORG_CODE",'JOIN_DATE' AS "JOIN_DATE",'ROLE' AS "ROLE",'PRIMARY' AS "PRIMARY",'DOMAIN' AS "DOMAIN"
UNION
SELECT  [Emp_No],rtrim([Org_Cd]) AS [Org_Cd],[EmpOrg_JoiningDate],[EmpOrg_RoleName],    [EmpOrg_PrmyInd],[EmpOrg_DomainInd] FROM [EmpOrg_View]

INSERT INTO [ORG_Export]
(Org_Cd,Org_Name,POrg_Cd,HierType_Name,Org_DomainInd,Org_Note,Org_URL,Org_Add1,Org_Add2,Org_City,Org_State,Org_Zip,Org_Cntry,Org_Phn1,Org_Phn2,Org_Fax,OptOrg_Txt1,OptOrg_Txt2,OptOrg_Txt3,OptOrg_Txt4,OptOrg_Dt1,OptOrg_Dt2,OptOrg_Int1,OptOrg_FLOAT1,OptOrg_Ind1,OptOrg_MONEY,OptOrg_Memo1,OptOrg_Currency)
SELECT  'ORG_CODE'              AS "ORG_CODE",
    'ORG_NAME'              AS "ORG_NAME",
    'ORG_PARENT_CODE'       AS "ORG_PARENT_CODE",
    'HIERARCHY'             AS  "HIERARCHY",
    'DOMAIN_FLAG'           AS "DOMAIN_FLAG",
    'NOTE'                  AS "NOTE",
    'ORG_URL'               AS "ORG_URL",
    'ADDRESS1'              AS "ADDRESS1",
    'ADDRESS2'              AS "ADDRESS2",
    'CITY'                  AS "CITY",
    'STATE'                 AS "STATE",
    'ZIP'                   AS "ZIP",
    'COUNTRY'               AS "COUNTRY",
    'PHONE1'                AS "PHONE1",
    'PHONE2'                AS "PHONE2",
    'FAX'                   AS "FAX",
    'CUSTOM_TEXT1'          AS "CUSTOM_TEXT1",
    'CUSTOM_TEXT2'          AS "CUSTOM_TEXT2",
    'CUSTOM_TEXT3'          AS "CUSTOM_TEXT3",
    'CUSTOM_TEXT4'          AS "CUSTOM_TEXT4",
    'CUSTOM_DATE1'          AS "CUSTOM_DATE1",
    'CUSTOM_DATE2'          AS "CUSTOM_DATE2",
    'CUSTOM_INTEGER1'       AS "CUSTOM_INTEGER1",
    'CUSTOM_FLOAT1'         AS "CUSTOM_FLOAT1",
    'CUSTOM_IND1'           AS "CUSTOM_IND1",
    'CUSTOM_MONEY1'         AS "CUSTOM_MONEY1",
    'CUSTOM_MEMO1'          AS "CUSTOM_MEMO1",
    'CUSTOM_CURRENCY_CODE'  AS "CUSTOM_CURRENCY_CODE"
UNION
SELECT rtrim([Org_Cd]) AS [Org_Cd],[Org_Name],[POrg_Cd],[HierType_Name],
CASE    WHEN LEN(RTRIM([Org_DomainInd]))=1  THEN RTRIM([Org_DomainInd])
        ELSE SUBSTRING(rtrim([Org_DomainInd]),1,1)
END AS [Org_DomainInd],
[Org_Note],[Org_URL],[Org_Add1],[Org_Add2],
CASE    WHEN LEN(RTRIM([Org_City]))<=30 THEN RTRIM([Org_City])
        ELSE SUBSTRING(rtrim([Org_City]),1,30)
END AS [Org_City],
[Org_State],[Org_Zip],[Org_Cntry],
CASE    WHEN LEN(RTRIM([Org_Phn1]))<=30 THEN RTRIM([Org_Phn1])
        ELSE SUBSTRING(rtrim([Org_Phn1]),1,30)
END AS [Org_Phn2],
CASE    WHEN LEN(RTRIM([Org_Phn2]))<=30 THEN RTRIM([Org_Phn2])
        ELSE SUBSTRING(rtrim([Org_Phn2]),1,30)
END AS [Org_Phn2],
CASE    WHEN LEN(RTRIM([Org_Fax]))<=30 THEN RTRIM([Org_Fax])
        ELSE SUBSTRING(rtrim([Org_Fax]),1,30)
END AS [Org_Fax],
[OptOrg_Txt1],
[OptOrg_Txt2],[OptOrg_Txt3],[OptOrg_Txt4],[OptOrg_Dt1], [OptOrg_Dt2],[OptOrg_Int1],[OptOrg_FLOAT1],
CASE    WHEN LEN(RTRIM([OptOrg_Ind1]))=1  THEN RTRIM([OptOrg_Ind1])
        ELSE SUBSTRING(rtrim([OptOrg_Ind1]),1,1)
END AS [OptOrg_Ind1],
[OptOrg_MONEY],[OptOrg_Memo1],[OptOrg_Currency]
FROM [Org_View]

INSERT INTO [EMP_Export]
(Emp_No,Emp_Title,Emp_LName,Emp_FName,Emp_MI,Emp_Suffix,Emp_Ttl,EmpCd_Name,EmpStat_Name,Mgr_No,DefApprEmp_No,Emp_StartDt,Emp_EndDt,Emp_LastRvwDt,Emp_Add1,Emp_Add2,Emp_City,Emp_State,Emp_Zip,Emp_Cntry,Emp_Email,Emp_Phn1,Emp_Phn2,Emp_Fax,Emp_URL,Emp_Note,EmpDomain_Cd,Org_Cd,Job_Cd,Emp_Active,Usr_Enabled,Usr_Name,Usr_NTLogin,Role_Name,Usr_Timezone,Usr_Currency,Usr_Language,OptEmp_Txt1,OptEmp_Txt2,OptEmp_Txt3,OptEmp_Txt4,OptEmp_Memo1,OptEmp_Dt1,OptEmp_Dt2,OptEmp_Ind1,OptEmp_MONEY,OptEmp_Int1,OptEmp_FLOAT1,Emp_Job_JoiningDate,PublishCalendar,ViewAllEmpsInd,IsMobileEnabled,MobileUserName)
SELECT  'EMP_NO'                AS "EMP_NO"
    ,'NAME_PREFIX_TEXT'     AS "NAME_PREFIX_TEXT"
    ,'LAST_NAME'            AS "LAST_NAME"
    ,'FIRST_NAME'           AS "FIRST_NAME"
    ,'MIDDLE_NAME'          AS "MIDDLE_NAME"
    ,'NAME_SUFFIX_TEXT'     AS "NAME_SUFFIX_TEXT"
    ,'CUSTOM_TEXT5'         AS "CUSTOM_TEXT5"
    ,'USER_CODE_TEXT'       AS "USER_CODE_TEXT"
    ,'USER_STATUS_TEXT'     AS "USER_STATUS_TEXT"
    ,'MANAGER_NO'           AS "MANAGER_NO"
    ,'TRNG_DEF_APPROVER_NO' AS "TRNG_DEF_APPROVER_NO"
    ,'START_DATE'           AS "START_DATE"
    ,'END_DATE'             AS "END_DATE"
    ,'LAST_REVIEW_DATE'     AS "LAST_REVIEW_DATE"
    ,'WORK_ADDRESS1'        AS "WORK_ADDRESS1"
    ,'WORK_ADDRESS2'        AS "WORK_ADDRESS2"
    ,'WORK_CITY'            AS "WORK_CITY"
    ,'WORK_STATE_TEXT'      AS "WORK_STATE_TEXT"
    ,'WORK_ZIP'             AS "WORK_ZIP"
    ,'WORK_COUNTRY_TEXT'    AS "WORK_COUNTRY_TEXT"
    ,'EMAIL'                AS "EMAIL"
    ,'WORK_PHONE'           AS "WORK_PHONE"
    ,'WORK_PHONE_EXT'       AS "WORK_PHONE_EXT"
    ,'WORK_FAX1'            AS "WORK_FAX1"
    ,'URL'                  AS "URL"
    ,'NOTES'                AS "NOTES"
    ,'PRIMARY_DOMAIN'       AS "PRIMARY_DOMAIN"
    ,'PRIMARY_ORG'          AS "PRIMARY_ORG"
    ,'PRIMARY_JOB'          AS "PRIMARY_JOB"
    ,'ACTIVE_FLAG'          AS "ACTIVE_FLAG"
    ,'LOGIN_ENABLED_FLAG'   AS "LOGIN_ENABLED_FLAG"
    ,'LOGIN_USERNAME'       AS "LOGIN_USERNAME"
    ,'NT_LOGIN'             AS "NT_LOGIN"
    ,'SECURITY_ROLE'        AS "SECURITY_ROLE"
    ,'TIMEZONE_CD'          AS "TIMEZONE_CD"
    ,'CURRENCY_TEXT'        AS "CURRENCY_TEXT"
    ,'LOCALE_CD'            AS "LOCALE_CD"
    ,'CUSTOM_TEXT1'         AS "CUSTOM_TEXT1"
    ,'CUSTOM_TEXT2'         AS "CUSTOM_TEXT2"
    ,'CUSTOM_TEXT3'         AS "CUSTOM_TEXT3"
    ,'CUSTOM_TEXT4'         AS "CUSTOM_TEXT4"
    ,'CUSTOM_MEMO1'         AS "CUSTOM_MEMO1"
    ,'CUSTOM_DATE1'         AS "CUSTOM_DATE1"
    ,'CUSTOM_DATE2'         AS "CUSTOM_DATE2"
    ,'CUSTOM_IND1'          AS "CUSTOM_IND1"
    ,'CUSTOM_MONEY1'        AS "CUSTOM_MONEY1"
    ,'CUSTOM_INTEGER1'      AS "CUSTOM_INTEGER1"
    ,'CUSTOM_FLOAT1'        AS "CUSTOM_FLOAT1"
    ,'PRIMARY_JOB_JOINDATE' AS "PRIMARY_JOB_JOINDATE"
    ,'AUTO_PUBLISH_CAL'     AS "AUTO_PUBLISH_CAL"
    ,'CAN_VIEW_ALL_USERS_FLAG' AS "CAN_VIEW_ALL_USERS_FLAG"
    ,'MOBILE_ENABLED'       AS "MOBILE_ENABLED"
    ,'MOBILE_USERNAME'      AS "MOBILE_USERNAME"
UNION
SELECT      Emp_No,
        Emp_Title,
        CASE    WHEN LEN(RTRIM(Emp_LName)) <= 50  THEN RTRIM(Emp_LName)
                ELSE SUBSTRING(rtrim(Emp_LName),1,50)
        END AS Emp_LName,
        CASE    WHEN LEN(RTRIM(Emp_FName)) <= 50  THEN RTRIM(Emp_FName)
                ELSE SUBSTRING(rtrim(Emp_FName),1,50)
        END AS Emp_FName,
        CASE    WHEN LEN(RTRIM(Emp_MI)) <= 50  THEN RTRIM(Emp_MI)
                ELSE SUBSTRING(rtrim(Emp_MI),1,50)
        END AS Emp_MI,
        Emp_Suffix,
        Emp_Ttl     ,
        EmpCd_Name  ,
        EmpStat_Name,
        Mgr_No      ,
        CONVERT (VARCHAR(25),DefApprEmp_No) DefApprEmp_No,
        Emp_StartDt ,
        Emp_EndDt   ,
        Emp_LastRvwDt,
        Emp_Add1    ,
        Emp_Add2    ,
        CASE    WHEN LEN(RTRIM(Emp_City)) <= 50  THEN RTRIM(Emp_City)
                ELSE SUBSTRING(rtrim(Emp_City),1,50)
        END AS Emp_City,
        CASE    WHEN LEN(RTRIM(Emp_State)) <= 35  THEN RTRIM(Emp_State)
                ELSE SUBSTRING(rtrim(Emp_State),1,35)
        END AS Emp_State,
        Emp_Zip     ,
        CASE    WHEN LEN(RTRIM(Emp_Cntry)) <= 50  THEN RTRIM(Emp_Cntry)
                ELSE SUBSTRING(rtrim(Emp_Cntry),1,50)
        END AS Emp_Cntry,
        Emp_Email,
         Emp_Phn1,
         Emp_Phn2,
         Emp_Fax,
         Emp_URL,
         Emp_Note       ,
         EmpDomain_Cd   ,
         rtrim(Org_Cd)  ,
         CONVERT (VARCHAR(500),rtrim(Job_Cd)) Job_Cd    ,
         Emp_Active     ,
         Usr_Enabled    ,
        CASE    WHEN LEN(RTRIM(Usr_Name)) <= 85  THEN RTRIM(Usr_Name)
                ELSE SUBSTRING(rtrim(Usr_Name),1,85)
        END AS Usr_Name,
         Usr_NTLogin    ,
        CASE    WHEN LEN(RTRIM(Role_Name)) <= 100  THEN RTRIM(Role_Name)
                ELSE SUBSTRING(rtrim(Role_Name),1,100)
        END AS Role_Name,
         Usr_Timezone   ,
         Usr_Currency   ,
         Usr_Language   ,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt1)) <= 255  THEN RTRIM(OptEmp_Txt1)
                ELSE SUBSTRING(rtrim(OptEmp_Txt1),1,255)
        END AS OptEmp_Txt1,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt2)) <= 255  THEN RTRIM(OptEmp_Txt2)
                ELSE SUBSTRING(rtrim(OptEmp_Txt2),1,255)
        END AS OptEmp_Txt2,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt3)) <= 255  THEN RTRIM(OptEmp_Txt3)
                ELSE SUBSTRING(rtrim(OptEmp_Txt3),1,255)
        END AS OptEmp_Txt3,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt4)) <= 255  THEN RTRIM(OptEmp_Txt4)
                ELSE SUBSTRING(rtrim(OptEmp_Txt4),1,255)
        END AS OptEmp_Txt4,
         OptEmp_Memo1   ,
         OptEmp_Dt1 ,
         OptEmp_Dt2 ,
         CONVERT (VARCHAR(500),OptEmp_Ind1) OptEmp_Ind1,
        OptEmp_MONEY,
        OptEmp_Int1,
        CONVERT (VARCHAR(500),OptEmp_FLOAT1) OptEmp_FLOAT1,
        Emp_Job_JoiningDate,
        PublishCalendar,
        ViewAllEmpsInd  ,
        IsMobileEnabled ,
        MobileUserName
FROM [Employee_VIEW]
</code>```

答:
Without using ORDER clause the result returned from a SELECT in MSSQL Server is always ordered randomly. You sometimes see the same result when executing a query multiple times because of the MSSQL Server caching capabilities (plan cache).

You can use additional column to do the sortings on, you can rely on ORDER, RANK or something that will suit you best.

Body:
I am using a view to feed a table in my database. While feeding the table, I am also adding a header row to the table. I am doing this for 5 tables.

However, for 2 tables, I could see that the header row in inserted at the top most where as for remaining 5 tables, the header row goes down. How can I fix it?

This is the query I am using to feed the data. I could see the header as 1st row in the JOB and EMPJOB tables.

INSERT INTO [JOB_Export](Job_Cd, Job_Name, Job_Note, Job_URL, OptJob_Currency, Domain_OrgCd, OptJob_Txt1, OptJob_Txt2, OptJob_Txt3, OptJob_Txt4, OptJob_Dt1, OptJob_Dt2, OptJob_Int1, OptJob_MONEY, OptJob_FLOAT1, OptJob_Ind1, OptJob_Memo1)
    SELECT
        'JOB_CODE' AS "JOB_CODE", 'JOB_NAME' AS "JOB_NAME",
        'JOB_DESC' AS "JOB_DESC", 'JOB_URL' AS "JOB_URL",
        'JOB_CURRENCY_CD' AS "JOB_CURRENCY_CD", 'JOB_DOMAIN' AS "JOB_DOMAIN",
        'CUSTOM_TEXT1' AS "CUSTOM_TEXT1", 'CUSTOM_TEXT2' AS "CUSTOM_TEXT2",
        'CUSTOM_TEXT3' AS "CUSTOM_TEXT3", 'CUSTOM_TEXT4' AS "CUSTOM_TEXT4",
        'CUSTOM_DATE1' AS "CUSTOM_DATE1", 'CUSTOM_DATE2' AS "CUSTOM_DATE2",
        'CUSTOM_INTEGER1' AS "CUSTOM_INTEGER1", 'CUSTOM_MONEY1'AS "CUSTOM_MONEY1",
        'CUSTOM_FLOAT1' AS "CUSTOM_FLOAT1", 'CUSTOM_IND1' AS "CUSTOM_IND1",
        'CUSTOM_MEMO1' AS "CUSTOM_MEMO1"
    UNION
    SELECT
        RTRIM(Job_Cd),
        Job_Name,
        CONVERT (VARCHAR(MAX),Job_Note) Job_Note,
        CONVERT (VARCHAR(255), Job_URL) Job_URL,
        CONVERT (VARCHAR(50), OptJob_Currency) OptJob_Currency,
        Domain_OrgCd,
        OptJob_Txt1,
        CONVERT (VARCHAR(255), OptJob_Txt2) OptJob_Txt2,
        CONVERT (VARCHAR(255), OptJob_Txt3)  OptJob_Txt3 ,
        CONVERT (VARCHAR(255), OptJob_Txt4)  OptJob_Txt4 ,
        CONVERT (VARCHAR(500), OptJob_Dt1)  OptJob_Dt1 ,
        CONVERT (VARCHAR(500), OptJob_Dt2)  OptJob_Dt2 ,
        CONVERT (VARCHAR(500), OptJob_Int1)  OptJob_Int1 ,
        CONVERT (VARCHAR(500), OptJob_MONEY) OptJob_MONEY ,
        CONVERT (VARCHAR(500), OptJob_FLOAT1) OptJob_FLOAT1,
        CONVERT (VARCHAR(500), OptJob_Ind1)  OptJob_Ind1 ,
        CONVERT (VARCHAR(MAX), OptJob_Memo1)   OptJob_Memo1
    FROM
        [OVERRIDE_JOB_VIEW]

INSERT INTO [EMPJOB_Export](Emp_No,Job_Cd,EmpJob_JoiningDate,EmpJob_PrmyInd,Domain_Cd)
SELECT 'EMP_NO' AS "EMP_NO",'JOB_CODE' AS "JOB_CODE",'JOIN_DATE' AS"JOIN_DATE",'PRIMARY' AS "PRIMARY",'JOB_DOMAIN' AS "JOB_DOMAIN"
UNION
SELECT [Emp_No],
    CASE    WHEN LEN(Job_Cd)<=30 THEN CONVERT (VARCHAR(500), JOB_CD)
    ELSE CONVERT(VARCHAR(500),SUBSTRING(rtrim([Job_Cd]),1,30))
    END AS Job_Cd,
    CONVERT(VARCHAR(500),[EmpJob_JoiningDate]) [EmpJob_JoiningDate] ,
    [EmpJob_PrmyInd],
    CASE    WHEN LEN(rtrim([Domain_Cd]))<=50 THEN [Domain_Cd]
    ELSE SUBSTRING(rtrim([Domain_Cd]),1,50)
    END AS [Domain_Cd]
    FROM [EMPJOB_VIEW]

INSERT INTO [EMPORG_Export] (Emp_No,Org_Cd,EmpOrg_JoiningDate,EmpOrg_RoleName,EmpOrg_PrmyInd,EmpOrg_DomainInd)
SELECT 'EMP_NO' AS "EMP_NO",'ORG_CODE' AS "ORG_CODE",'JOIN_DATE' AS "JOIN_DATE",'ROLE' AS "ROLE",'PRIMARY' AS "PRIMARY",'DOMAIN' AS "DOMAIN"
UNION
SELECT  [Emp_No],rtrim([Org_Cd]) AS [Org_Cd],[EmpOrg_JoiningDate],[EmpOrg_RoleName],    [EmpOrg_PrmyInd],[EmpOrg_DomainInd] FROM [EmpOrg_View]

INSERT INTO [ORG_Export]
(Org_Cd,Org_Name,POrg_Cd,HierType_Name,Org_DomainInd,Org_Note,Org_URL,Org_Add1,Org_Add2,Org_City,Org_State,Org_Zip,Org_Cntry,Org_Phn1,Org_Phn2,Org_Fax,OptOrg_Txt1,OptOrg_Txt2,OptOrg_Txt3,OptOrg_Txt4,OptOrg_Dt1,OptOrg_Dt2,OptOrg_Int1,OptOrg_FLOAT1,OptOrg_Ind1,OptOrg_MONEY,OptOrg_Memo1,OptOrg_Currency)
SELECT  'ORG_CODE'              AS "ORG_CODE",
    'ORG_NAME'              AS "ORG_NAME",
    'ORG_PARENT_CODE'       AS "ORG_PARENT_CODE",
    'HIERARCHY'             AS  "HIERARCHY",
    'DOMAIN_FLAG'           AS "DOMAIN_FLAG",
    'NOTE'                  AS "NOTE",
    'ORG_URL'               AS "ORG_URL",
    'ADDRESS1'              AS "ADDRESS1",
    'ADDRESS2'              AS "ADDRESS2",
    'CITY'                  AS "CITY",
    'STATE'                 AS "STATE",
    'ZIP'                   AS "ZIP",
    'COUNTRY'               AS "COUNTRY",
    'PHONE1'                AS "PHONE1",
    'PHONE2'                AS "PHONE2",
    'FAX'                   AS "FAX",
    'CUSTOM_TEXT1'          AS "CUSTOM_TEXT1",
    'CUSTOM_TEXT2'          AS "CUSTOM_TEXT2",
    'CUSTOM_TEXT3'          AS "CUSTOM_TEXT3",
    'CUSTOM_TEXT4'          AS "CUSTOM_TEXT4",
    'CUSTOM_DATE1'          AS "CUSTOM_DATE1",
    'CUSTOM_DATE2'          AS "CUSTOM_DATE2",
    'CUSTOM_INTEGER1'       AS "CUSTOM_INTEGER1",
    'CUSTOM_FLOAT1'         AS "CUSTOM_FLOAT1",
    'CUSTOM_IND1'           AS "CUSTOM_IND1",
    'CUSTOM_MONEY1'         AS "CUSTOM_MONEY1",
    'CUSTOM_MEMO1'          AS "CUSTOM_MEMO1",
    'CUSTOM_CURRENCY_CODE'  AS "CUSTOM_CURRENCY_CODE"
UNION
SELECT rtrim([Org_Cd]) AS [Org_Cd],[Org_Name],[POrg_Cd],[HierType_Name],
CASE    WHEN LEN(RTRIM([Org_DomainInd]))=1  THEN RTRIM([Org_DomainInd])
        ELSE SUBSTRING(rtrim([Org_DomainInd]),1,1)
END AS [Org_DomainInd],
[Org_Note],[Org_URL],[Org_Add1],[Org_Add2],
CASE    WHEN LEN(RTRIM([Org_City]))<=30 THEN RTRIM([Org_City])
        ELSE SUBSTRING(rtrim([Org_City]),1,30)
END AS [Org_City],
[Org_State],[Org_Zip],[Org_Cntry],
CASE    WHEN LEN(RTRIM([Org_Phn1]))<=30 THEN RTRIM([Org_Phn1])
        ELSE SUBSTRING(rtrim([Org_Phn1]),1,30)
END AS [Org_Phn2],
CASE    WHEN LEN(RTRIM([Org_Phn2]))<=30 THEN RTRIM([Org_Phn2])
        ELSE SUBSTRING(rtrim([Org_Phn2]),1,30)
END AS [Org_Phn2],
CASE    WHEN LEN(RTRIM([Org_Fax]))<=30 THEN RTRIM([Org_Fax])
        ELSE SUBSTRING(rtrim([Org_Fax]),1,30)
END AS [Org_Fax],
[OptOrg_Txt1],
[OptOrg_Txt2],[OptOrg_Txt3],[OptOrg_Txt4],[OptOrg_Dt1], [OptOrg_Dt2],[OptOrg_Int1],[OptOrg_FLOAT1],
CASE    WHEN LEN(RTRIM([OptOrg_Ind1]))=1  THEN RTRIM([OptOrg_Ind1])
        ELSE SUBSTRING(rtrim([OptOrg_Ind1]),1,1)
END AS [OptOrg_Ind1],
[OptOrg_MONEY],[OptOrg_Memo1],[OptOrg_Currency]
FROM [Org_View]

INSERT INTO [EMP_Export]
(Emp_No,Emp_Title,Emp_LName,Emp_FName,Emp_MI,Emp_Suffix,Emp_Ttl,EmpCd_Name,EmpStat_Name,Mgr_No,DefApprEmp_No,Emp_StartDt,Emp_EndDt,Emp_LastRvwDt,Emp_Add1,Emp_Add2,Emp_City,Emp_State,Emp_Zip,Emp_Cntry,Emp_Email,Emp_Phn1,Emp_Phn2,Emp_Fax,Emp_URL,Emp_Note,EmpDomain_Cd,Org_Cd,Job_Cd,Emp_Active,Usr_Enabled,Usr_Name,Usr_NTLogin,Role_Name,Usr_Timezone,Usr_Currency,Usr_Language,OptEmp_Txt1,OptEmp_Txt2,OptEmp_Txt3,OptEmp_Txt4,OptEmp_Memo1,OptEmp_Dt1,OptEmp_Dt2,OptEmp_Ind1,OptEmp_MONEY,OptEmp_Int1,OptEmp_FLOAT1,Emp_Job_JoiningDate,PublishCalendar,ViewAllEmpsInd,IsMobileEnabled,MobileUserName)
SELECT  'EMP_NO'                AS "EMP_NO"
    ,'NAME_PREFIX_TEXT'     AS "NAME_PREFIX_TEXT"
    ,'LAST_NAME'            AS "LAST_NAME"
    ,'FIRST_NAME'           AS "FIRST_NAME"
    ,'MIDDLE_NAME'          AS "MIDDLE_NAME"
    ,'NAME_SUFFIX_TEXT'     AS "NAME_SUFFIX_TEXT"
    ,'CUSTOM_TEXT5'         AS "CUSTOM_TEXT5"
    ,'USER_CODE_TEXT'       AS "USER_CODE_TEXT"
    ,'USER_STATUS_TEXT'     AS "USER_STATUS_TEXT"
    ,'MANAGER_NO'           AS "MANAGER_NO"
    ,'TRNG_DEF_APPROVER_NO' AS "TRNG_DEF_APPROVER_NO"
    ,'START_DATE'           AS "START_DATE"
    ,'END_DATE'             AS "END_DATE"
    ,'LAST_REVIEW_DATE'     AS "LAST_REVIEW_DATE"
    ,'WORK_ADDRESS1'        AS "WORK_ADDRESS1"
    ,'WORK_ADDRESS2'        AS "WORK_ADDRESS2"
    ,'WORK_CITY'            AS "WORK_CITY"
    ,'WORK_STATE_TEXT'      AS "WORK_STATE_TEXT"
    ,'WORK_ZIP'             AS "WORK_ZIP"
    ,'WORK_COUNTRY_TEXT'    AS "WORK_COUNTRY_TEXT"
    ,'EMAIL'                AS "EMAIL"
    ,'WORK_PHONE'           AS "WORK_PHONE"
    ,'WORK_PHONE_EXT'       AS "WORK_PHONE_EXT"
    ,'WORK_FAX1'            AS "WORK_FAX1"
    ,'URL'                  AS "URL"
    ,'NOTES'                AS "NOTES"
    ,'PRIMARY_DOMAIN'       AS "PRIMARY_DOMAIN"
    ,'PRIMARY_ORG'          AS "PRIMARY_ORG"
    ,'PRIMARY_JOB'          AS "PRIMARY_JOB"
    ,'ACTIVE_FLAG'          AS "ACTIVE_FLAG"
    ,'LOGIN_ENABLED_FLAG'   AS "LOGIN_ENABLED_FLAG"
    ,'LOGIN_USERNAME'       AS "LOGIN_USERNAME"
    ,'NT_LOGIN'             AS "NT_LOGIN"
    ,'SECURITY_ROLE'        AS "SECURITY_ROLE"
    ,'TIMEZONE_CD'          AS "TIMEZONE_CD"
    ,'CURRENCY_TEXT'        AS "CURRENCY_TEXT"
    ,'LOCALE_CD'            AS "LOCALE_CD"
    ,'CUSTOM_TEXT1'         AS "CUSTOM_TEXT1"
    ,'CUSTOM_TEXT2'         AS "CUSTOM_TEXT2"
    ,'CUSTOM_TEXT3'         AS "CUSTOM_TEXT3"
    ,'CUSTOM_TEXT4'         AS "CUSTOM_TEXT4"
    ,'CUSTOM_MEMO1'         AS "CUSTOM_MEMO1"
    ,'CUSTOM_DATE1'         AS "CUSTOM_DATE1"
    ,'CUSTOM_DATE2'         AS "CUSTOM_DATE2"
    ,'CUSTOM_IND1'          AS "CUSTOM_IND1"
    ,'CUSTOM_MONEY1'        AS "CUSTOM_MONEY1"
    ,'CUSTOM_INTEGER1'      AS "CUSTOM_INTEGER1"
    ,'CUSTOM_FLOAT1'        AS "CUSTOM_FLOAT1"
    ,'PRIMARY_JOB_JOINDATE' AS "PRIMARY_JOB_JOINDATE"
    ,'AUTO_PUBLISH_CAL'     AS "AUTO_PUBLISH_CAL"
    ,'CAN_VIEW_ALL_USERS_FLAG' AS "CAN_VIEW_ALL_USERS_FLAG"
    ,'MOBILE_ENABLED'       AS "MOBILE_ENABLED"
    ,'MOBILE_USERNAME'      AS "MOBILE_USERNAME"
UNION
SELECT      Emp_No,
        Emp_Title,
        CASE    WHEN LEN(RTRIM(Emp_LName)) <= 50  THEN RTRIM(Emp_LName)
                ELSE SUBSTRING(rtrim(Emp_LName),1,50)
        END AS Emp_LName,
        CASE    WHEN LEN(RTRIM(Emp_FName)) <= 50  THEN RTRIM(Emp_FName)
                ELSE SUBSTRING(rtrim(Emp_FName),1,50)
        END AS Emp_FName,
        CASE    WHEN LEN(RTRIM(Emp_MI)) <= 50  THEN RTRIM(Emp_MI)
                ELSE SUBSTRING(rtrim(Emp_MI),1,50)
        END AS Emp_MI,
        Emp_Suffix,
        Emp_Ttl     ,
        EmpCd_Name  ,
        EmpStat_Name,
        Mgr_No      ,
        CONVERT (VARCHAR(25),DefApprEmp_No) DefApprEmp_No,
        Emp_StartDt ,
        Emp_EndDt   ,
        Emp_LastRvwDt,
        Emp_Add1    ,
        Emp_Add2    ,
        CASE    WHEN LEN(RTRIM(Emp_City)) <= 50  THEN RTRIM(Emp_City)
                ELSE SUBSTRING(rtrim(Emp_City),1,50)
        END AS Emp_City,
        CASE    WHEN LEN(RTRIM(Emp_State)) <= 35  THEN RTRIM(Emp_State)
                ELSE SUBSTRING(rtrim(Emp_State),1,35)
        END AS Emp_State,
        Emp_Zip     ,
        CASE    WHEN LEN(RTRIM(Emp_Cntry)) <= 50  THEN RTRIM(Emp_Cntry)
                ELSE SUBSTRING(rtrim(Emp_Cntry),1,50)
        END AS Emp_Cntry,
        Emp_Email,
         Emp_Phn1,
         Emp_Phn2,
         Emp_Fax,
         Emp_URL,
         Emp_Note       ,
         EmpDomain_Cd   ,
         rtrim(Org_Cd)  ,
         CONVERT (VARCHAR(500),rtrim(Job_Cd)) Job_Cd    ,
         Emp_Active     ,
         Usr_Enabled    ,
        CASE    WHEN LEN(RTRIM(Usr_Name)) <= 85  THEN RTRIM(Usr_Name)
                ELSE SUBSTRING(rtrim(Usr_Name),1,85)
        END AS Usr_Name,
         Usr_NTLogin    ,
        CASE    WHEN LEN(RTRIM(Role_Name)) <= 100  THEN RTRIM(Role_Name)
                ELSE SUBSTRING(rtrim(Role_Name),1,100)
        END AS Role_Name,
         Usr_Timezone   ,
         Usr_Currency   ,
         Usr_Language   ,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt1)) <= 255  THEN RTRIM(OptEmp_Txt1)
                ELSE SUBSTRING(rtrim(OptEmp_Txt1),1,255)
        END AS OptEmp_Txt1,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt2)) <= 255  THEN RTRIM(OptEmp_Txt2)
                ELSE SUBSTRING(rtrim(OptEmp_Txt2),1,255)
        END AS OptEmp_Txt2,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt3)) <= 255  THEN RTRIM(OptEmp_Txt3)
                ELSE SUBSTRING(rtrim(OptEmp_Txt3),1,255)
        END AS OptEmp_Txt3,
        CASE    WHEN LEN(RTRIM(OptEmp_Txt4)) <= 255  THEN RTRIM(OptEmp_Txt4)
                ELSE SUBSTRING(rtrim(OptEmp_Txt4),1,255)
        END AS OptEmp_Txt4,
         OptEmp_Memo1   ,
         OptEmp_Dt1 ,
         OptEmp_Dt2 ,
         CONVERT (VARCHAR(500),OptEmp_Ind1) OptEmp_Ind1,
        OptEmp_MONEY,
        OptEmp_Int1,
        CONVERT (VARCHAR(500),OptEmp_FLOAT1) OptEmp_FLOAT1,
        Emp_Job_JoiningDate,
        PublishCalendar,
        ViewAllEmpsInd  ,
        IsMobileEnabled ,
        MobileUserName
FROM [Employee_VIEW]


问:
My JSP returns a 202 (SC_ACCEPTED) status, but the caller gets a 200 (SC_OK) status
I am accessing a simple JSP page on Tomcat:

```<code><%@ page import = "java.io.Writer" %>
<%
try {
    Writer outWriter = response.getWriter ();
    outWriter.write ("something");
    outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>
</code>```

But when I test this page with curl, I get a 200 response code instead of the expected 202:

```<code>$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Mon, 05 Jun 2017 08:09:36 GMT

something
</code>```

If I remove the content from the response:

```<code><%@ page import = "java.io.Writer" %>
<%
try {
    //Writer outWriter = response.getWriter ();
    //outWriter.write ("something");
    //outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>
</code>```

I get the desired response code:

```<code>$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 202 Accepted
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2
Date: Mon, 05 Jun 2017 08:12:57 GMT
</code>```

Is there some Tomcat configuration changing the response code?

My actual goal is to simulate responses of some 3rd party web API that is expected to return a 202 response code + some short content string for successful requests.

My server, which would call this API, expects a 202 response. I guess I can change it to accept both 200 and 202 responses, but I wanted my code to match the documentation of the 3rd party API.

答: Move the setStatus() to the top of the JSP. Look at the compiled JSP to see how the code is written by the compiler. Chances are once Status has been set, it cannot be overridden. The flush() method maybe have set the Status to 200.</p>

Body:
I am accessing a simple JSP page on Tomcat:

<%@ page import = "java.io.Writer" %>
<%
try {
    Writer outWriter = response.getWriter ();
    outWriter.write ("something");
    outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>

But when I test this page with curl, I get a 200 response code instead of the expected 202:

$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Mon, 05 Jun 2017 08:09:36 GMT

something

If I remove the content from the response:

<%@ page import = "java.io.Writer" %>
<%
try {
    //Writer outWriter = response.getWriter ();
    //outWriter.write ("something");
    //outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>

I get the desired response code:

$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 202 Accepted
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2
Date: Mon, 05 Jun 2017 08:12:57 GMT

Is there some Tomcat configuration changing the response code?

My actual goal is to simulate responses of some 3rd party web API that is expected to return a 202 response code + some short content string for successful requests.

My server, which would call this API, expects a 202 response. I guess I can change it to accept both 200 and 202 responses, but I wanted my code to match the documentation of the 3rd party API.


问:
Pros and Cons of multiple region databases
Can someone tell me pros and cons of using multiple region databases? I am working on an application which would be mostly used in one particular region but may be rarely used in different regions as well. So, I am thinking that should I make my application multi-region or not? That's why asking about pros and cons.</p>

答: I recommend to use region_id in your user table and add user_id as foreign key in  all tables where data inserted or updated. So when each user login you can distinguish to which region this user belong.


问:
How to uninstall Python indent plug-in from Notepad++?
I currently installed via plug-in manager of Notepad++ the Python Indent plug-in
I cannot uninstall it.

It's in update pane of Notepad++ plug-in manager, I check it and update it.
After update installation it is there again and not in installed plug-ins.
So it cannot be uninstalled.

Any idea how to remove it?

答:
I had the same problem. The only solution I found was to delete the dll of the plugin
"Python Indent.dll" (and Python Indent directory if it exists)
 from the Notepad++ plugin directory, tipically:

```<code>c:\Program Files (x86)\Notepad++\plugins
</code>```

Once I deleted the dll and restarted Notepad++ the Python Indent plug-in was gone

Body:
I had the same problem. The only solution I found was to delete the dll of the plugin
"Python Indent.dll" (and Python Indent directory if it exists)
 from the Notepad++ plugin directory, tipically:

c:\Program Files (x86)\Notepad++\plugins

Once I deleted the dll and restarted Notepad++ the Python Indent plug-in was gone


问:
how to get a average of days with two different tables
There are two tables 1)HR_OrderRequest (column to be considered is HRdate) other columns are HRUID,UID
                     2)HR_Supplydetails(colmn to be considered is HRUID) other columns are createddttm,UID
by considering the date from HR_Supplydetails we should find the average days taken for that particular UID time taken to release of HRdate .I have a problem getting a average of days

Please do the need .

答:
You can do a datediff:

```<code>SELECT AVG(DATEDIFF(day, createddttm,HRdate))
</code>```

And then do your join on the two tables.

ContentLicense: CC BY-SA 2.5

Body:
You can do a datediff:

SELECT AVG(DATEDIFF(day, createddttm,HRdate))

And then do your join on the two tables.


问:
jquery click, toggle one or more div block
I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div id='toggle'>
  <span id='show'><p>fhslkjklsfjl</p></span>
</div></code>```

答:
You can not use same id. ID should be unique.

Try by giving class:

  $(".toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  }); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div class='toggle'>2 nd button
  <span id='show'><p>fhslkjklsfjl</p></span>
</div></code>```

Body:
I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});

this clicked

Show this

fhslkjklsfjl

Body:
You can not use same id. ID should be unique.

Try by giving class:

  $(".toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div class='toggle'>2 nd button
  <span id='show'><p>fhslkjklsfjl</p></span>
</div>


问:
getter always returns 0
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

```<code>public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}
</code>```

答:
You don't change draws value anywhere, getAmountOfComputerCards = draws; at this point you always assign 0.

After computerSumCards += randomCard; add draws++; and it should be fine. Without it you will get infinite loop.

Title: getter always returns 0

Body:
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}


问:
Troubleshooting LaunchAgent (LaunchAgent not starting loading)
I had I had a problem in starting the LaunchAgent and googled a lot and found multiple methods to troubleshoot, Noting them all down here in one place for the benefits of others</p>

答:
1) Ensure that after agents are copied in /Library/LaunchAgent folder reads as following.

```<code>-rw-r--r--  1 root  wheel  798 Jun  5 11:52 /Library/LaunchAgents/com.mycompany.myproduct.LaunchAgent.plist
</code>```

(When you manually copy these files for debugging, you may have manually change these attributes using chown and chgroup commands).

2) Ensure that the path given in plist-> ProgramArguments is correct. (note that space is not required here)

3) Ensure that execution permission exists for file specified in "launchAgent plist->ProgramArguments"

4) check RunAtLoad attribute

5) Ensure that WatchPath file is present, please check if the the WatchPath need need any  parameterization like /path/dir1/dir2/productname%BUILDNO%.trigger

6)  if there is a file com.mycompanynewname.MyProductLaunchAgent.plist in the folder it may conflict with com.mycompanyoldname.MyProductLaunchAgent.plist

7)  Look for /var/log/system.log for launchctl specific logs.

8) Read more about how LaunchDemon and LaunchAgent works and Apple documentation and http://www.launchd.info/

Body:
1) Ensure that after agents are copied in /Library/LaunchAgent folder reads as following.

-rw-r--r--  1 root  wheel  798 Jun  5 11:52 /Library/LaunchAgents/com.mycompany.myproduct.LaunchAgent.plist

(When you manually copy these files for debugging, you may have manually change these attributes using chown and chgroup commands).

2) Ensure that the path given in plist-> ProgramArguments is correct. (note that space is not required here)

3) Ensure that execution permission exists for file specified in "launchAgent plist->ProgramArguments"

4) check RunAtLoad attribute

5) Ensure that WatchPath file is present, please check if the the WatchPath need need any  parameterization like /path/dir1/dir2/productname%BUILDNO%.trigger

6)  if there is a file com.mycompanynewname.MyProductLaunchAgent.plist in the folder it may conflict with com.mycompanyoldname.MyProductLaunchAgent.plist

7)  Look for /var/log/system.log for launchctl specific logs.

8) Read more about how LaunchDemon and LaunchAgent works and Apple documentation and http://www.launchd.info/


问:
CASE Statement to select a particular value if value exists in another table
I have a requirement where I need to order the records in the result set cursor returned by a stored procedure in a particular order. For example, assume that the SP returned 10 records.The result contains a field named FLD1. The records whose FLD1 value is present in another table must be placed at the top of the result set. That is the records whose FLD1 value returns results when used in a query like SELECT * FROM RESULTS WHERE FLD1 IN (SELECT FLD2 FROM TABLE2) must be placed at the top of the result set and the records which do not return any records must come afterward.

The approach I am following is to first select the records which satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign a seq.no 1 and store the results in a temp table. Then select the records which do not satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign them a sequence 2. Finally, merge the results and open a result cursor at the end of the SP ordering by the Sequence number.

Please suggest any better approach if you know of one. I was thinking of using a CASE statement like CASE WHEN FLD1 IN (SELECT FLD2 FROM TABLE2) THEN "1" ELSE "2". But this does not seem to work in DB2.

答:
So I seemed to have found the answer.

The trick is to use case as below:

```<code>CASE
  WHEN (SELECT T41SBI FROM TC401F
        WHERE T40BID = TC401F.T41SBI) IS NOT NULL THEN '1'
  ELSE '2'
END AS SEQ,
</code>```

and finally order by SEQ field. If somebody could validate this , that would be great

Body:
So I seemed to have found the answer.

The trick is to use case as below:

CASE
  WHEN (SELECT T41SBI FROM TC401F
        WHERE T40BID = TC401F.T41SBI) IS NOT NULL THEN '1'
  ELSE '2'
END AS SEQ,

and finally order by SEQ field. If somebody could validate this , that would be great


问:
temporal dead zone (ES6) doesnt seem to work
Below is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<h1 id="message"></h1>

<script src="traceur/traceur.js"></script>
<script src="traceur/BrowserSystem.js"></script>
<script src="traceur/bootstrap.js"></script>
<script type="module">

    var x = 'outer scope';
    (function() {
        console.log(x); //Expected undefined, got undefined ! this is as expected.
        var x = 'inner scope';
    }());

    //same as above, but changed to var to let and x to y
    let y = 'outer scope';
    (function() {
        console.log(y); //Was expecting ReferenceError here, but got undefined. WTF ??!!!
        let y = 'inner scope';
    }());

</script>

</body>
</html>
</code>```

Its seems the temporal drop zone (TDZ) in es6 should throw a referenceError in case the let-var is used before it is declared.

However, in this example, I am getting undefined for let.
Where am i going wrong?

Been at this problem for a long time and wasted a day on this. (Any pointers would be very help). I am using Chrome v58.

v58 has es6 compatibility as per https://kangax.github.io/compat-table/es6/ under current browser).

I stripped off the traceur part and posted on babel-try it out, and got the same result.

Am wondering why is it not working in my chrome v58. Maybe it requires something else too??

答:
I removed the transpiler code and enabled the Experimental Features in JS
chrome://flags/#enable-javascript-harmony here and it worked as expected now.

Chrome version v58

Body:
Below is my code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Its seems the temporal drop zone (TDZ) in es6 should throw a referenceError in case the let-var is used before it is declared.

However, in this example, I am getting undefined for let.
Where am i going wrong?

Been at this problem for a long time and wasted a day on this. (Any pointers would be very help). I am using Chrome v58.

v58 has es6 compatibility as per https://kangax.github.io/compat-table/es6/ under current browser).

I stripped off the traceur part and posted on babel-try it out, and got the same result.

Am wondering why is it not working in my chrome v58. Maybe it requires something else too??


问:
Ordered Dictionary in c# and unity3d FIREBASE
I currently have a firebase project that parses data from the web.

All the data is coming down however I'm wanting to reverse order the results.

I achieve this by doing the following code

```<code>public class ExampleItemModel{

    public string name;
    public string score;
    public string level;
    public int iconIdx1, iconIdx2, iconIdx3;
}
</code>```

Then in my fetch data method :-

```<code>    public  void GetDataFromFireBase(string reference, Action<ExampleItemModel[]> onDone){

         FirebaseDatabase.DefaultInstance
          .GetReference(reference).OrderByChild("score")
          .GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted) {
              // Handle the error...
              print("Error: " + task.Exception);
            }
            else if (task.IsCompleted) {
              DataSnapshot snapshot = task.Result;
              // Do something with snapshot...

                var items = snapshot.Value as Dictionary<string, object>;
                int count = items.Count;
                var results = new ExampleItemModel[count];
                int i = 0;
                foreach(var item in items){
                    results[i] = new ExampleItemModel();

                    //print("items =  " + item);
                       var values = item.Value as Dictionary<string, object>;

                            if (reference == "scores"){
                            print("values count =" + values.Count);

                                foreach(var value in values){

                                    if(value.Key == "name"){ results[i].name = "" + value.Value;}
                                    if(value.Key == "score"){ print("Score = " + value.Value); results[i].score = "" + value.Value;}
                                    if(value.Key == "level"){ results[i].level = "" + value.Value;}

                                }
                            i++;
                            }
            onDone(results);

}

          });

}
</code>```

Ive tried the following : -

in firebase rules I've set

```<code>  ".indexOn":"score",
"score": {
  ".indexOn": ".value"
}
</code>```

I've also tried to add the following line of code

```<code>            results = results.OrderByDescending( x => x.score);
            onDone(results);
</code>```

but I get the following error

severity: 'Error'
message: 'Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'ExampleItemModel[]' [Assembly-CSharp]'
at: '137,14'
source: ''

Would anybody please be able to help

thanks

答:
Thanks Jeff for your response

On the back of this I managed to order the results by doing the following

```<code>List <ExampleItemModel> orderedArray = results.OrderByDescending(x => x.score).ToList();
</code>```

Hope this will help somebody else with this issue in the future

Body:
I currently have a firebase project that parses data from the web.

All the data is coming down however I'm wanting to reverse order the results.

I achieve this by doing the following code

public class ExampleItemModel{

    public string name;
    public string score;
    public string level;
    public int iconIdx1, iconIdx2, iconIdx3;
}

Then in my fetch data method :-

    public  void GetDataFromFireBase(string reference, Action<ExampleItemModel[]> onDone){

         FirebaseDatabase.DefaultInstance
          .GetReference(reference).OrderByChild("score")
          .GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted) {
              // Handle the error...
              print("Error: " + task.Exception);
            }
            else if (task.IsCompleted) {
              DataSnapshot snapshot = task.Result;
              // Do something with snapshot...

                var items = snapshot.Value as Dictionary<string, object>;
                int count = items.Count;
                var results = new ExampleItemModel[count];
                int i = 0;
                foreach(var item in items){
                    results[i] = new ExampleItemModel();

                    //print("items =  " + item);
                       var values = item.Value as Dictionary<string, object>;

                            if (reference == "scores"){
                            print("values count =" + values.Count);

                                foreach(var value in values){

                                    if(value.Key == "name"){ results[i].name = "" + value.Value;}
                                    if(value.Key == "score"){ print("Score = " + value.Value); results[i].score = "" + value.Value;}
                                    if(value.Key == "level"){ results[i].level = "" + value.Value;}

                                }
                            i++;
                            }
            onDone(results);

}

          });

}

Ive tried the following : -

in firebase rules I've set

  ".indexOn":"score",
"score": {
  ".indexOn": ".value"
}

I've also tried to add the following line of code

            results = results.OrderByDescending( x => x.score);
            onDone(results);

but I get the following error

severity: 'Error'
message: 'Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'ExampleItemModel[]' [Assembly-CSharp]'
at: '137,14'
source: ''

Would anybody please be able to help

thanks

Body:
Thanks Jeff for your response

On the back of this I managed to order the results by doing the following

List <ExampleItemModel> orderedArray = results.OrderByDescending(x => x.score).ToList();

Hope this will help somebody else with this issue in the future


答:
The class does not "ignores" the while loop. The loop is inside the method drawLoop(). If you want it to run you need to call it explicitly

```<code>computerDraw draw = new computerDraw();
draw.drawLoop();
</code>```

As a side note, class names start with capital later. computerDraw should be ComputerDraw.

Title: getter always returns 0

Body:
The class does not "ignores" the while loop. The loop is inside the method drawLoop(). If you want it to run you need to call it explicitly

computerDraw draw = new computerDraw();
draw.drawLoop();

As a side note, class names start with capital later. computerDraw should be ComputerDraw.


问:
How to select
 inside

Assume I have html structure as

```<code>ul
  li //this one
    ul
      li
      li
      li
  li //this one
</code>```

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

```<code>document.querySelectorAll("ul > li");
</code>```

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

答:
You could traverse the first ul's children and look for li's like the following.</p>

```<code>function firstLis() {
  var firstUl = document.querySelector('ul');
  var list = [];
  for(var i = 0; i < firstUl.children.length; i++) {
    var element = firstUl.children[i];
    if(element.tagName === 'LI')
      list.push(element);
  }
  return list;
}
</code>```

Title: How to select <li> inside <ul>

Body:
Assume I have html structure as

ul
  li //this one
    ul
      li
      li
      li
  li //this one

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

document.querySelectorAll("ul > li");

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

Body:
You could traverse the first ul's children and look for li's like the following.

function firstLis() {
  var firstUl = document.querySelector('ul');
  var list = [];
  for(var i = 0; i < firstUl.children.length; i++) {
    var element = firstUl.children[i];
    if(element.tagName === 'LI')
      list.push(element);
  }
  return list;
}


问:
How does wininet handle cookies
I have a .NET client application that needs to communicate with a server using two distinct user credentials.
Lets say that the application runs two threads. When start running, every thread sends the user & password to authenticate and the server in return stores a cookie on the http session. The subsequent calls send the authentication cookie and not the user credentials.

We have two cookies for the same process. How does wininet "knows" to send the appropriate cookie for each thread?

Does wininet manage the cookies collection per thread? per http session? per process?

Thanks

答:
Wininet uses cookies per process.

However in a .NET client you can use a Cookie container with the HttpWebRequest object.

You create one cookie container for each "session".  Assign the appropriate container to each HttpWebRequest when making the various requests for each session.

OwnerDisplayName: LiorH

Title: How does wininet handle cookies

LastEditorDisplayName: LiorH

OwnerDisplayName: AnthonyWJones

LastEditorDisplayName: Ates Goral


问:
Write list of objects to text file
I've got a class Dish like this:

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
</code>```

In the main form the user can enter the previous data.
Then I create a list of "Dish":

```<code>public static List<Piatto> List = new List<Piatto>();
</code>```

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

```<code>public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
</code>```

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

答:
Override the ToString() method in Dish. For example:

```<code>public class Dish
{
   // rest of code..

   public override string ToString()
   {
      return Cost.ToString() + " " + Name;
   }
}
</code>```

Title: Write list of objects to text file

Body:
I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data.
Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

Body:
Override the ToString() method in Dish. For example:

public class Dish
{
   // rest of code..

   public override string ToString()
   {
      return Cost.ToString() + " " + Name;
   }
}


问:
Android:java.util.concurrent.ThreadPoolExecutor
In my app there is RecyclerView with tons of images in it.Images are loaded as user scrolls RecyclerView with this code:

```<code>    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,url);
    else
        loader.execute(url);
</code>```

Unfortunately sometimes when user scrolls fast this error occurs:

```<code>Task android.os.AsyncTask$3@73f1d84 rejected from
java.util.concurrent.ThreadPoolExecutor@8f5f96d[Running, pool size = 9,
active threads = 9, queued tasks = 128, completed tasks = 279]
</code>```

Is there way to detect if poolExecutor is full and skip image loading?

Whole Image class:

```<code>public class Image extends ImageView {
private AsyncTask<String,Integer,Bitmap> loader;

public Image(Context context) {
    super(context);
    this.setScaleType(ScaleType.FIT_XY);
}

public Image(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setScaleType(ScaleType.FIT_XY);
}

public void loadURL(String url) {
    if(loader!=null)
        loader.cancel(true);
    loader=new AsyncTask<String, Integer, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            byte[] bytes = null;
            HttpURLConnection connection=null;
            try {
                url = new URL(params[0]);
                connection=(HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Connection", "close");
                connection.setRequestMethod("GET");
                connection.setUseCaches(true);
                InputStream is = null;
                is=connection.getInputStream();
                bytes = IOUtils.toByteArray(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection!=null)
                connection.disconnect();
            Bitmap res=null;
            if(!isCancelled() && bytes!=null)
                res=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            return res;
        }
        @Override
        protected void onPostExecute(Bitmap res) {
            if(res!=null) {
                setImageBitmap(res);
                _animate();
            }
        }
    };
    if (this.getDrawable()!=null) {
        Bitmap bmp=((BitmapDrawable) this.getDrawable()).getBitmap();
        this.setAnimation(null);
        if (bmp!=null) {
            bmp.recycle();
            //Log.d("image","recycled");
        }
        this.setImageBitmap(null);
    }
    /*
    ThreadPoolExecutor e =(ThreadPoolExecutor) Executors.newFixedThreadPool(9);
    Log.d("pool size",e.getActiveCount()+"/"+e.getMaximumPoolSize());
    if (e.getActiveCount() == e.getMaximumPoolSize()) {
    }
    */
    //start loading
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
    else
        loader.execute(url);
}
private void _animate() {
    ValueAnimator bgAnim= ValueAnimator.ofObject(new IntEvaluator(),0,255);
    bgAnim.setDuration(500);
    bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Image.this.getDrawable().setAlpha((int) (animation.getAnimatedValue()));
        }
    });
    bgAnim.start();
}
</code>```

}

答:
You can check if active threads count is equal to thread pool maximum size then your thread pool is full by using this</p>

```<code>ThreadPoolExecutor e =(ThreadPoolExecutor)Executors.newFixedThreadPool(totalnofthreads);
if (e.getActiveCount() == e.getMaximumPoolSize())
{

}
</code>```

Body:
In my app there is RecyclerView with tons of images in it.Images are loaded as user scrolls RecyclerView with this code:

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,url);
    else
        loader.execute(url);

Unfortunately sometimes when user scrolls fast this error occurs:

Task android.os.AsyncTask$3@73f1d84 rejected from
java.util.concurrent.ThreadPoolExecutor@8f5f96d[Running, pool size = 9,
active threads = 9, queued tasks = 128, completed tasks = 279]

Is there way to detect if poolExecutor is full and skip image loading?

Whole Image class:

public class Image extends ImageView {
private AsyncTask<String,Integer,Bitmap> loader;

public Image(Context context) {
    super(context);
    this.setScaleType(ScaleType.FIT_XY);
}

public Image(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setScaleType(ScaleType.FIT_XY);
}

public void loadURL(String url) {
    if(loader!=null)
        loader.cancel(true);
    loader=new AsyncTask<String, Integer, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            byte[] bytes = null;
            HttpURLConnection connection=null;
            try {
                url = new URL(params[0]);
                connection=(HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Connection", "close");
                connection.setRequestMethod("GET");
                connection.setUseCaches(true);
                InputStream is = null;
                is=connection.getInputStream();
                bytes = IOUtils.toByteArray(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection!=null)
                connection.disconnect();
            Bitmap res=null;
            if(!isCancelled() && bytes!=null)
                res=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            return res;
        }
        @Override
        protected void onPostExecute(Bitmap res) {
            if(res!=null) {
                setImageBitmap(res);
                _animate();
            }
        }
    };
    if (this.getDrawable()!=null) {
        Bitmap bmp=((BitmapDrawable) this.getDrawable()).getBitmap();
        this.setAnimation(null);
        if (bmp!=null) {
            bmp.recycle();
            //Log.d("image","recycled");
        }
        this.setImageBitmap(null);
    }
    /*
    ThreadPoolExecutor e =(ThreadPoolExecutor) Executors.newFixedThreadPool(9);
    Log.d("pool size",e.getActiveCount()+"/"+e.getMaximumPoolSize());
    if (e.getActiveCount() == e.getMaximumPoolSize()) {
    }
    */
    //start loading
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
    else
        loader.execute(url);
}
private void _animate() {
    ValueAnimator bgAnim= ValueAnimator.ofObject(new IntEvaluator(),0,255);
    bgAnim.setDuration(500);
    bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Image.this.getDrawable().setAlpha((int) (animation.getAnimatedValue()));
        }
    });
    bgAnim.start();
}

}

Body:
You can check if active threads count is equal to thread pool maximum size then your thread pool is full by using this

ThreadPoolExecutor e =(ThreadPoolExecutor)Executors.newFixedThreadPool(totalnofthreads);
if (e.getActiveCount() == e.getMaximumPoolSize())
{

}


答:
use :scope

console.log(source.querySelectorAll("ul:scope > li"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="source">
  <li>
    this
    <ul>
      <li>not this</li>
      <li>not this</li>
      <li>not this</li>
    </ul>
  </li>
  <li>
  this
  </li>
</ul></code>```

Snapshot from Chrome console:

Title: How to select <li> inside <ul>

Body:
use :scope

console.log(source.querySelectorAll("ul:scope > li"));

<ul id="source">
  <li>
    this
    <ul>
      <li>not this</li>
      <li>not this</li>
      <li>not this</li>
    </ul>
  </li>
  <li>
  this
  </li>
</ul>

Snapshot from Chrome console:


问:
How to ask choices from user in multi line?
I'm asking user to select from multiple options as follows

```<code>var reportData = {
    "Report A Traffic Violation": {
        intent: 'report_a_traffic_violation'
    },
    "Report a Lost Property": {
        intent: 'report_a_traffic_violation'
    },
    "Describe Incident": {
        intent: '/describeIncident'
    }
};

builder.Prompts.choice(session, "please select from options", reportData);
</code>```

But the options shows to the user in single line. How can I show the options to the user using multiple lines as follows?

option one

option two

option three

答:
Node.js

Based on the code you provided I suppose you are using node.js

You may have a look to the Contoso-Flowers sample provided by Microsoft, in its settings function: code here and preview with the list visible here.

Here is how they are handling the list:

```<code>var SettingChoice = {
    Email: 'edit_email',
    Phone: 'edit_phone',
    Addresses: 'edit_addresses',
    Cancel: 'cancel'
};

var lib = new builder.Library('settings');
lib.dialog('/', [
    // Display options
    function (session) {
        builder.Prompts.choice(session, 'settings_intro', [
            session.gettext(SettingChoice.Email),
            session.gettext(SettingChoice.Phone),
            session.gettext(SettingChoice.Addresses),
            session.gettext(SettingChoice.Cancel)
        ]);
    },
</code>```

Did you try to use an array like here?

C#

For those building their bots in C#, you just have to specify your  PromptStyle to PromptStyle.PerLine

Body:
I'm asking user to select from multiple options as follows

var reportData = {
    "Report A Traffic Violation": {
        intent: 'report_a_traffic_violation'
    },
    "Report a Lost Property": {
        intent: 'report_a_traffic_violation'
    },
    "Describe Incident": {
        intent: '/describeIncident'
    }
};

builder.Prompts.choice(session, "please select from options", reportData);

But the options shows to the user in single line. How can I show the options to the user using multiple lines as follows?

option one

option two

option three

Body:
Node.js

Based on the code you provided I suppose you are using node.js

You may have a look to the Contoso-Flowers sample provided by Microsoft, in its settings function: code here and preview with the list visible here.

Here is how they are handling the list:

var SettingChoice = {
    Email: 'edit_email',
    Phone: 'edit_phone',
    Addresses: 'edit_addresses',
    Cancel: 'cancel'
};

var lib = new builder.Library('settings');
lib.dialog('/', [
    // Display options
    function (session) {
        builder.Prompts.choice(session, 'settings_intro', [
            session.gettext(SettingChoice.Email),
            session.gettext(SettingChoice.Phone),
            session.gettext(SettingChoice.Addresses),
            session.gettext(SettingChoice.Cancel)
        ]);
    },

Did you try to use an array like here?

C#

For those building their bots in C#, you just have to specify your  PromptStyle to PromptStyle.PerLine


答:
You need to use the attributes, so something like:</p>

```<code>foreach (var item in Data.List)
{
    tw.WriteLine(item.Cost.ToString() + " " + item.Name);
}
</code>```

Title: Write list of objects to text file

Body:
You need to use the attributes, so something like:

foreach (var item in Data.List)
{
    tw.WriteLine(item.Cost.ToString() + " " + item.Name);
}


问:
Raise exception on logging.warning
I want to temporarily make logging.warning calls raise an exception, instead of printing and continuing. How can I do this?

```<code>import logging
logging.warning("Foo") # Should raise exception
logging.info("Bar") # Should not raise exception
</code>```

答:
when you init your logging change warning call</p>

```<code>def warning(self, message, *args, **kws):
    if self.isEnabledFor(logging.WARNING):
        self._log(logging.WARNING, message, args, **kws)
        raise Exception(message)

logging.Logger.warning = warning
</code>```

Title: Raise exception on logging.warning

Body:
I want to temporarily make logging.warning calls raise an exception, instead of printing and continuing. How can I do this?

import logging
logging.warning("Foo") # Should raise exception
logging.info("Bar") # Should not raise exception

Body:
when you init your logging change warning call

def warning(self, message, *args, **kws):
    if self.isEnabledFor(logging.WARNING):
        self._log(logging.WARNING, message, args, **kws)
        raise Exception(message)

logging.Logger.warning = warning


答:
In jQuery you can use this selector ul > li:not('ul > li > ul > li'):

$("ul > li:not('ul > li > ul > li')").css("background", "green");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul > li {
  background: white;
}</code>```

    First

        Second

Third

Second

Second

Second

First

First

First

```

Title: How to select <li> inside <ul>

Body:
In jQuery you can use this selector ul > li:not('ul > li > ul > li'):

$("ul > li:not('ul > li > ul > li')").css("background", "green");

ul > li {
  background: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    First
    <ul>
      <li>
        Second
        <ul>
          <li>Third</li>
        </ul>
      </li>
      <li>Second</li>
      <li>Second</li>
      <li>Second</li>
    </ul>
  </li>
  <li>First</li>
  <li>First</li>
  <li>First</li>
</ul>


答:
You can get the father's direct children. In this case, the "lis":

console.log(document.querySelector("ul").children)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
</ul></code>```

Title: How to select <li> inside <ul>

Body:
You can get the father's direct children. In this case, the "lis":

console.log(document.querySelector("ul").children)

<ul>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
</ul>


问:
How to change the height and width of the table (javax.microedition.lcdui.CustomItem) inside the form in J2ME
I create a table in j2me.Using javax.microedition.lcdui.CustomItem by drawing lines & placing a string.Then i place the table inside the form (javax.microedition.lcdui.Form).

I also implement traversing using the method

```<code>protected boolean traverse(int dir, int viewportWidth, int viewportHeight, int[] visRect_inout){}
</code>```

Here I want to do when traversing is fails I place the new table after deleting the old table inside the form. Or I want to change the contents in the table and also change the height and width of the table inside form.

答:
The solution I got: Delete the table from the form then create a new table by creating an object & add into the form.

In the constructor of table get the form's height & width as an argument then adjust the size of the new table based on the form's dimensions.

Body:
I create a table in j2me.Using javax.microedition.lcdui.CustomItem by drawing lines & placing a string.Then i place the table inside the form (javax.microedition.lcdui.Form).

I also implement traversing using the method

protected boolean traverse(int dir, int viewportWidth, int viewportHeight, int[] visRect_inout){}

Here I want to do when traversing is fails I place the new table after deleting the old table inside the form. Or I want to change the contents in the table and also change the height and width of the table inside form.


问:
AssertCalled always fails with testify library
I am using testify to test my code and I want to check if a function was called.

I am doing the following:

```<code>type Foo struct {
    mock.Mock
}

func (m Foo) Bar() {

}

func TestFoo(t *testing.T) {
    m := Foo{}
    m.Bar()
    m.AssertCalled(t, "Bar")
}
</code>```

The error I am getting:

```<code>Error:      Should be true
Messages:   The "Bar" method should have been called with 0 argument(s), but was not.

mock.go:419: []
</code>```

I call function "Bar" and immediately ask if it was called but it returns false.
What am I doing wrong?
What is the proper way to test if a function was called with testify?

答:
Looking at the documentation of testify I think you have to explicitly call func (*Mock) Called to tell the mock object that a method has been called.

```<code>func (m *Foo) Bar() {
    m.Called()
}
</code>```

There are some examples in the testify tests.

Body:
I am using testify to test my code and I want to check if a function was called.

I am doing the following:

type Foo struct {
    mock.Mock
}

func (m Foo) Bar() {

}

func TestFoo(t *testing.T) {
    m := Foo{}
    m.Bar()
    m.AssertCalled(t, "Bar")
}

The error I am getting:

Error:      Should be true
Messages:   The "Bar" method should have been called with 0 argument(s), but was not.

mock.go:419: []

I call function "Bar" and immediately ask if it was called but it returns false.
What am I doing wrong?
What is the proper way to test if a function was called with testify?

Body:
Looking at the documentation of testify I think you have to explicitly call func (*Mock) Called to tell the mock object that a method has been called.

func (m *Foo) Bar() {
    m.Called()
}

There are some examples in the testify tests.


问:
Alignment issue in mail message in Java
I am trying to get some chat messages from the system and creating the mail message body rom those messages. The issue i am facing is that both users have different name length due to which mail is looking cluttered:-

```<code>[2017-03-01] Amit : Hi
[2017-03-01] Rakesh Kumar : Hello
</code>```

I want the messsage in the mail should be like this:-

```<code>[2017-03-01] Amit         : Hi
[2017-03-01] Rakesh Kumar : Hello
</code>```

As of now i am trying to append the spaces according to max length of both of the names.but when string is sent in the mail(text/html) spaces are not preserved.

Can anybody suggest me a way to do this.

Thanks,

答:
If you are using text/html as your email mime type, then you need to use Non Breaking Space ( ) HTML character instead of the space () character.

For example:

```<code>[2017-03-01] Amit               : Hi<br />
[2017-03-01] Rakesh Kumar : Hello
</code>```

It should be something like the above. You will need to tweak the number of   characters for adjusting the alignment. I think you get the idea.

The above snippet will get translated to HTML and get rendered in the email message like below:

```<code>[2017-03-01] Amit               : Hi
[2017-03-01] Rakesh Kumar       : Hello
</code>```

So, you may want to do a replace in your mail content String like this:

```<code>mailContent.replaceAll(" " , "&nbsp");
</code>```

See this page for more info.

Hope this helps!

Title: Alignment issue in mail message in Java

Body:
I am trying to get some chat messages from the system and creating the mail message body rom those messages. The issue i am facing is that both users have different name length due to which mail is looking cluttered:-

[2017-03-01] Amit : Hi
[2017-03-01] Rakesh Kumar : Hello

I want the messsage in the mail should be like this:-

[2017-03-01] Amit         : Hi
[2017-03-01] Rakesh Kumar : Hello

As of now i am trying to append the spaces according to max length of both of the names.but when string is sent in the mail(text/html) spaces are not preserved.

Can anybody suggest me a way to do this.

Thanks,

Body:
If you are using text/html as your email mime type, then you need to use Non Breaking Space (&nbsp;) HTML character instead of the space () character.

For example:

[2017-03-01] Amit&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: Hi<br />
[2017-03-01] Rakesh Kumar&nbsp;: Hello

It should be something like the above. You will need to tweak the number of &nbsp; characters for adjusting the alignment. I think you get the idea.

The above snippet will get translated to HTML and get rendered in the email message like below:

[2017-03-01] Amit               : Hi
[2017-03-01] Rakesh Kumar       : Hello

So, you may want to do a replace in your mail content String like this:

mailContent.replaceAll(" " , "&nbsp");

See this page for more info.

Hope this helps!