问:
How can I make my TextView font as shown in image
I am trying to style my text of STUDENT LOGIN which is shown in the image.
But I don't know how can use a different custom font to make my STUDENT LOGIN to look like as shown in the image.

I want Style in that way. How Can I make my S and L shown in image

答:
Find font family then Get it font yourfont.ttf  file from internet and paste into assets folder in android.

Then apply your Textview

```<code>Typeface customTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/custum_font.ttf");
myTextView.setTypeface(customTypeface);
</code>```

Body:
Find font family then Get it font yourfont.ttf  file from internet and paste into assets folder in android.

Then apply your Textview

Typeface customTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/custum_font.ttf");
myTextView.setTypeface(customTypeface);


来源: stackexchange

答:
First of all set your font to the TextView

```<code>TextView textView = (TextView) findViewById(R.id.textview);
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/myFont.ttf");
textView.setTypeface(myTypeface);
</code>```

Now, You can achieve different size of S and T using SpannableString

```<code>String s = "STUDENT LOGIN";
SpannableString ss = new SpannableString(s);
ss.setSpan(new RelativeSizeSpan(2f), 0, 1, 0);       // Set Size
ss.setSpan(new RelativeSizeSpan(2f), 8, 9, 0);       // Set Size
textView.setText(ss);
</code>```

Here replace 2f according to size you want.

0 is starting index of S and 1 is ending index.

8 is starting index of L and 9 is ending index.

ContentLicense: CC BY-SA 3.0

Title: How can I make my TextView font as shown in image

Body:
I am trying to style my text of STUDENT LOGIN which is shown in the image.
But I don't know how can use a different custom font to make my STUDENT LOGIN to look like as shown in the image.

I want Style in that way. How Can I make my S and L shown in image

Body:
First of all set your font to the TextView

TextView textView = (TextView) findViewById(R.id.textview);
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "font/myFont.ttf");
textView.setTypeface(myTypeface);

Now, You can achieve different size of S and T using SpannableString

String s = "STUDENT LOGIN";
SpannableString ss = new SpannableString(s);
ss.setSpan(new RelativeSizeSpan(2f), 0, 1, 0);       // Set Size
ss.setSpan(new RelativeSizeSpan(2f), 8, 9, 0);       // Set Size
textView.setText(ss);

Here replace 2f according to size you want.

0 is starting index of S and 1 is ending index.

8 is starting index of L and 9 is ending index.


问:
Grid Layout Add Evenly Spaced Images
I am trying to fit a specified amount of images in a Grid Layout programmatically and I want them all to be evenly sized and spread out. Whenever I try to add multiple images the grid layout only shows one. What am I doing wrong?

XML:

```<code><GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:gravity="center"/>
</code>```

Java:

```<code>//reset data and grid
    data.clear();
    gridLayout.removeAllViews();

    Random random = new Random();
    for(int i = 0; i < num; i++){
        data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
        ImageView imageView = new ImageView(getContext());
        switch (data.get(i)) {
            case "1":
                imageView.setImageResource(R.drawable.dice1);
                break;
            case "2":
                imageView.setImageResource(R.drawable.dice2);
                break;
            case "3":
                imageView.setImageResource(R.drawable.dice3);
                break;
            case "4":
                imageView.setImageResource(R.drawable.dice4);
                break;
            case "5":
                imageView.setImageResource(R.drawable.dice5);
                break;
            default:
                imageView.setImageResource(R.drawable.dice6);
                break;
        }
        gridLayout.addView(imageView, i);
    }
</code>```

What shows up:

What I want:

答:
[![Screenshot][1]][1]

```<code>package com.plumtestongo.sample;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.GridLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final GridLayout layout = (GridLayout) findViewById(R.id.gridlayout);
        ViewTreeObserver vto = layout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                int width = layout.getMeasuredWidth();
                int height = layout.getMeasuredHeight();
                setViews(height, width);

            }
        });
    }

    private void setViews(int layoutHeight, int layoutWidth) {

        int width = layoutWidth / 3;
        int height = layoutHeight / 2;
        Log.i(getClass().getName(), "Image height" + height + " Width:" + width);
        ArrayList<String> data = new ArrayList<>();
        data.clear();
        GridLayout gridLayout = (GridLayout) findViewById(R.id.gridlayout);
        gridLayout.removeAllViews();
        Random random = new Random();
        int num = 6;
        for (int i = 0; i < num; i++) {
            data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
            ImageView imageView = new ImageView(this);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = width;
            layoutParams.height = height;
            imageView.setLayoutParams(layoutParams);
            switch (data.get(i)) {
                case "1":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "2":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "3":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "4":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "5":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                default:
                    imageView.setImageResource(R.drawable.dice2);
                    break;
            }
            gridLayout.addView(imageView, i);
        }
    }

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="3"
        android:padding="10dp"
        android:gravity="center"/>

</LinearLayout>
</code>```

you need row column 3 in xml layout.

you have to set width and height of imageview .

height and width can be calculated based on screen size.you may not
need the height but width is important.

another option would be to create scaled bitmap for background
resource based of screen size.

Title: Grid Layout Add Evenly Spaced Images

Body:
I am trying to fit a specified amount of images in a Grid Layout programmatically and I want them all to be evenly sized and spread out. Whenever I try to add multiple images the grid layout only shows one. What am I doing wrong?

XML:

<GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:gravity="center"/>

Java:

//reset data and grid
    data.clear();
    gridLayout.removeAllViews();

    Random random = new Random();
    for(int i = 0; i < num; i++){
        data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
        ImageView imageView = new ImageView(getContext());
        switch (data.get(i)) {
            case "1":
                imageView.setImageResource(R.drawable.dice1);
                break;
            case "2":
                imageView.setImageResource(R.drawable.dice2);
                break;
            case "3":
                imageView.setImageResource(R.drawable.dice3);
                break;
            case "4":
                imageView.setImageResource(R.drawable.dice4);
                break;
            case "5":
                imageView.setImageResource(R.drawable.dice5);
                break;
            default:
                imageView.setImageResource(R.drawable.dice6);
                break;
        }
        gridLayout.addView(imageView, i);
    }

What shows up:

What I want:

Body:
[![Screenshot][1]][1]

package com.plumtestongo.sample;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.GridLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final GridLayout layout = (GridLayout) findViewById(R.id.gridlayout);
        ViewTreeObserver vto = layout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                int width = layout.getMeasuredWidth();
                int height = layout.getMeasuredHeight();
                setViews(height, width);

            }
        });
    }

    private void setViews(int layoutHeight, int layoutWidth) {

        int width = layoutWidth / 3;
        int height = layoutHeight / 2;
        Log.i(getClass().getName(), "Image height" + height + " Width:" + width);
        ArrayList<String> data = new ArrayList<>();
        data.clear();
        GridLayout gridLayout = (GridLayout) findViewById(R.id.gridlayout);
        gridLayout.removeAllViews();
        Random random = new Random();
        int num = 6;
        for (int i = 0; i < num; i++) {
            data.add(String.format("%." + 0 + "f", random.nextDouble() * (6 - 1) + 1));
            ImageView imageView = new ImageView(this);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = width;
            layoutParams.height = height;
            imageView.setLayoutParams(layoutParams);
            switch (data.get(i)) {
                case "1":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "2":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "3":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "4":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                case "5":
                    imageView.setImageResource(R.drawable.dice2);
                    break;
                default:
                    imageView.setImageResource(R.drawable.dice2);
                    break;
            }
            gridLayout.addView(imageView, i);
        }
    }

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <GridLayout
        android:id="@+id/gridlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="3"
        android:padding="10dp"
        android:gravity="center"/>

</LinearLayout>

you need row column 3 in xml layout.

you have to set width and height of imageview .

height and width can be calculated based on screen size.you may not
need the height but width is important.

another option would be to create scaled bitmap for background
resource based of screen size.


问:
Cross join on a group based on the condition in SQL Server
I have Item and Exam tables -

My desire result -

I tried a lot but I am unable to join Exam table to Item table based on Code group.

Is it possible to cross join or any other join for these two tables to get the desire result?

答:
You can try this</p>

```<code>SELECT A.Code, i.Item, A.Exam
FROM
(
SELECT Code,e.Exam
FROM Item i
CROSS JOIN Exam e
GROUP BY Code,e.Exam
) A
LEFT JOIN Item i ON i.Code= A.Code AND i.Exam = A.Exam
</code>```

Body:
You can try this

SELECT A.Code, i.Item, A.Exam
FROM
(
SELECT Code,e.Exam
FROM Item i
CROSS JOIN Exam e
GROUP BY Code,e.Exam
) A
LEFT JOIN Item i ON i.Code= A.Code AND i.Exam = A.Exam


问:
Convert numeric time format to POSIXlt
I have time imported from a file. The column is considered numeric and  is as follows:

head(RawData$TimeStart, 10)
 [1]  0.00  0.00  0.00 30.19  0.00 25.00  0.00  9.20  0.00  0.00

This data represents a sample taken at 0.0 minutes and at 30 minutes, 19 seconds (30.19) for example.

I wish this column to now be converted to the following format:

```<code>> head(RawData$Converted, 10)
 [1] "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:30:19 AEST"
 [5] "2017-07-05 00:00:00 AEST" "2017-07-05 00:25:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:09:20 AEST"
 [9] "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST"
</code>```

I have tried the following:
RawData$Converted <- as.POSIXct(RawData$TimeStart, origin='1970-01-01', tz='Australia/Darwin')

But this does not give today's date/ time. I am very confused, so any help would be greatly appreciated.

Title: Convert numeric time format to POSIXlt

Body:
I have time imported from a file. The column is considered numeric and  is as follows:

head(RawData$TimeStart, 10)
 [1]  0.00  0.00  0.00 30.19  0.00 25.00  0.00  9.20  0.00  0.00

This data represents a sample taken at 0.0 minutes and at 30 minutes, 19 seconds (30.19) for example.

I wish this column to now be converted to the following format:

> head(RawData$Converted, 10)
 [1] "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:30:19 AEST"
 [5] "2017-07-05 00:00:00 AEST" "2017-07-05 00:25:00 AEST" "2017-07-05 00:00:00 AEST" "2017-07-05 00:09:20 AEST"
 [9] "2017-07-05 00:00:00 AEST" "2017-07-05 00:00:00 AEST"

I have tried the following:
RawData$Converted <- as.POSIXct(RawData$TimeStart, origin='1970-01-01', tz='Australia/Darwin')

But this does not give today's date/ time. I am very confused, so any help would be greatly appreciated.

Body:
Break your numeric values to convert them all to seconds, and add that to a datetime for today:

x <- c(0.00,0.00,0.00,30.19,0.00,25.00,0.00,9.20,0.00,0.00)
as.POSIXct(format(Sys.Date()), tz="Australia/Darwin") + (floor(x)*60) + ((x-floor(x))*100)
# [1] "2017-07-05 00:00:00 ACST" "2017-07-05 00:00:00 ACST" "2017-07-05 00:00:00 ACST" "2017-07-05 00:30:19 ACST"
# [5] "2017-07-05 00:00:00 ACST" "2017-07-05 00:25:00 ACST" "2017-07-05 00:00:00 ACST" "2017-07-05 00:09:20 ACST"
# [9] "2017-07-05 00:00:00 ACST" "2017-07-05 00:00:00 ACST"

This is in Darwin time, ACST instead of AEST, but I gather that's what you want.


问:
Python divisible range
So I'm doing simple problems online to get an understanding of Python and came across this one:

Add all numbers in the range 1..1000 inclusive where the number is odd
  but is divisible by any number in the range 2..(n // 2) inclusive.

My attempt:

```<code>total = 0
for num in range(1, 1000, 2):
    if all(num % n == 0 for n in range(2, num // 2)):
        total += num
print(total)
</code>```

I don't understand what's wrong with the way I'm implementing it, getting an output of 9, instead of the expected output of 173874.

答:
Simply use any

```<code>total = 0
for num in range(1, 1000, 2):
    if any(num % n == 0 for n in range(2, num // 2)):
        total += num
print(total)
</code>```

when you used all you are only summing up 1,3,5 because all Return True only if all elements of the iterable are true (or if the iterable is empty). In your case, you want any which returns True if any element of the iterable is true.

Title: Python divisible range

Body:
So I'm doing simple problems online to get an understanding of Python and came across this one:

Add all numbers in the range 1..1000 inclusive where the number is odd
  but is divisible by any number in the range 2..(n // 2) inclusive.

My attempt:

total = 0
for num in range(1, 1000, 2):
    if all(num % n == 0 for n in range(2, num // 2)):
        total += num
print(total)

I don't understand what's wrong with the way I'm implementing it, getting an output of 9, instead of the expected output of 173874.

Body:
Simply use any

total = 0
for num in range(1, 1000, 2):
    if any(num % n == 0 for n in range(2, num // 2)):
        total += num
print(total)

when you used all you are only summing up 1,3,5 because all Return True only if all elements of the iterable are true (or if the iterable is empty). In your case, you want any which returns True if any element of the iterable is true.


问:
Convert Date string in NodeIS
I have a TranDate "2017/07/05 12:12:22", i want to convert it to this style : 20170705121222, can you help me what function of nodejs can I use to do this issue ? Thank you !</p>

答:
There might be built in function in nodeJS, but you can achieve expected output using regex. as below</p>

```<code>"2017/07/05 12:12:22".match(/\d/g).join('')
</code>```

Title: Convert Date string in NodeIS

Body:
There might be built in function in nodeJS, but you can achieve expected output using regex. as below

"2017/07/05 12:12:22".match(/\d/g).join('')


问:
SQL Count no result if condition is 0
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

```<code>id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink
</code>```

Client List Table:

```<code>id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12
</code>```

My code:

```<code>SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name
</code>```

My result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
</code>```

My desired result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red
</code>```

I want to show 0 even there's no row equal to it

Is it possible?

thanks

答:
You can use left join in this case : </p>

```<code>SELECT COUNT(*) as Count, clientgroup_name,clientgroup_color FROM client_group
cg LEFT JOIN client_list cl ON cg.id=cl.group_id GROUP BY
cg.clientgroup_name,cg.clientgroup_color
</code>```

Title: SQL Count no result if condition is 0

Body:
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink

Client List Table:

id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12

My code:

SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name

My result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink

My desired result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red

I want to show 0 even there's no row equal to it

Is it possible?

thanks

Body:
You can use left join in this case :

SELECT COUNT(*) as Count, clientgroup_name,clientgroup_color FROM client_group
cg LEFT JOIN client_list cl ON cg.id=cl.group_id GROUP BY
cg.clientgroup_name,cg.clientgroup_color


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
1. foreach and for

A foreach loop works with IEnumerator, when a for loop works with an index (in object myObject = myListOfObjects[i], i is the index).

There is a big difference between the two:

an index can access directly any object based on its position within a list.

an enumerator can only access the first element of a list, and then move to the next element (as described in the previous link from the msdn). It cannot access an element directly, just knowing the index of the element within a list.

So an enumerator may seem less powerful, but:

you don't always know the position of elements in a group, because all groups are not ordered/indexed.

you don't always know the number of elements in a list (think about a linked list).

even when it's ordered, the indexed access of a list may be based internally on an enumerator, which means that each time you're accessing an element by its position you may be actually enumerating all elements of the list up until the element you want.

indexes are not always numeric. Think about Dictionary.

So actually the big strength of the foreach loop and the underlying use of IEnumerator is that it applies to any type which implements IEnumerable (implementing IEnumerable just means that you provide a method that returns an enumerator). Lists, Arrays, Dictionaries, and all other group types all implement IEnumerable. And you can be sure that the enumerator they have is as good as it gets: you won't find a fastest way to go through a list.

So, the for loop can generally be considered as a specialized foreach loop:

```<code>public void GoThrough(List<object> myList)
{
    for (int i=0; i<myList.Count; i++)
    {
        MessageBox.Show(myList[i].ToString());
    }
}
</code>```

is perfectly equivalent to:

```<code>public void GoThrough(List<object> myList)
{
    foreach (object item in myList)
    {
        MessageBox.Show(item.ToString());
    }
}
</code>```

I said generally because there is an obvious case when the for loop is necessary: when you need the index (i.e. the position in the list) of the object, for some reason (like displaying it). You will though eventually realize that this happens only in specific cases when you do good .NET programming, and that foreach should be your default candidate for loops over a group of elements.

Now to keep comparing the foreach loop, it is indeed just an eye-candy specific while loop:

```<code>public void GoThrough(IEnumerable myEnumerable)
{
    foreach (object obj in myEnumerable)
    {
        MessageBox.Show(obj.ToString());
    }
}
</code>```

is perfectly equivalent to:

```<code>public void GoThrough(IEnumerable myEnumerable)
{
    IEnumerator myEnumerator = myEnumerable.GetEnumerator();
    while (myEnumerator.MoveNext())
    {
        MessageBox.Show(myEnumerator.Current.ToString());
    }
}
</code>```

The first writing is a lot simpler though.

2. while and do..while

The while (condition) {action} loop and the do {action} while (condition) loop just differ from each other by the fact that the first one tests the condition before applying the action, when the second one applies the action, then tests the condition. The do {..} while (..) loop is used quite marginally compared to the others, since it runs the action at least once even if the condition is initially not met (which can lead to trouble, since the action is generally dependent on the condition).

The while loop is more general than the for and foreach ones, which apply specifically to lists of objects. The while loop just has a condition to go on, which can be based on anything. For example:

```<code>string name = string.empty;
while (name == string.empty)
{
    Console.WriteLine("Enter your name");
    name = Console.ReadLine();
}
</code>```

asks the user to input his name then press Enter, until he actually inputs something. Nothing to do with lists, as you can see.

3. Conclusion

When you are going through a list, you should use foreach unless you need the numeric index, in which case you should use for.
When it doesn't have anything to do with list, and it's just a procedural construction, you should use while(..) {..}.

Now to conclude with something less restrictive: your first goal with .NET should be to make your code readable/maintainable and make it run fast, in that order of priority. Anything that achieves that is good for you. Personally though, I think the foreach loop has the advantage that potentially, it's the most readable and the fastest.

Edit: there is an other case where the for loop is useful: when you need indexing to go through a list in a special way or if you need to modify the list when in the loop. For example, in this case because we want to remove every null element from myList:

```<code>for (int i=myList.Count-1; i>=0; i--)
{
    if (myList[i] == null) myList.RemoveAt(i);
}
</code>```

You need the for loop here because myList cannot be modified from within a foreach loop, and we need to go through it backwards because if you remove the element at the position i, the position of all elements with an index >i will change.

But the use for these special constructions have been reduced since LINQ. The last example can be written like this in LINQ for example:

```<code>myList.RemoveAll(obj => obj == null);
</code>```

LINQ is a second step though, learn the loops first.

Title: When to use each type of loop?

Body:
1. foreach and for

A foreach loop works with IEnumerator, when a for loop works with an index (in object myObject = myListOfObjects[i], i is the index).

There is a big difference between the two:

an index can access directly any object based on its position within a list.

an enumerator can only access the first element of a list, and then move to the next element (as described in the previous link from the msdn). It cannot access an element directly, just knowing the index of the element within a list.

So an enumerator may seem less powerful, but:

you don't always know the position of elements in a group, because all groups are not ordered/indexed.

you don't always know the number of elements in a list (think about a linked list).

even when it's ordered, the indexed access of a list may be based internally on an enumerator, which means that each time you're accessing an element by its position you may be actually enumerating all elements of the list up until the element you want.

indexes are not always numeric. Think about Dictionary.

So actually the big strength of the foreach loop and the underlying use of IEnumerator is that it applies to any type which implements IEnumerable (implementing IEnumerable just means that you provide a method that returns an enumerator). Lists, Arrays, Dictionaries, and all other group types all implement IEnumerable. And you can be sure that the enumerator they have is as good as it gets: you won't find a fastest way to go through a list.

So, the for loop can generally be considered as a specialized foreach loop:

public void GoThrough(List<object> myList)
{
    for (int i=0; i<myList.Count; i++)
    {
        MessageBox.Show(myList[i].ToString());
    }
}

is perfectly equivalent to:

public void GoThrough(List<object> myList)
{
    foreach (object item in myList)
    {
        MessageBox.Show(item.ToString());
    }
}

I said generally because there is an obvious case when the for loop is necessary: when you need the index (i.e. the position in the list) of the object, for some reason (like displaying it). You will though eventually realize that this happens only in specific cases when you do good .NET programming, and that foreach should be your default candidate for loops over a group of elements.

Now to keep comparing the foreach loop, it is indeed just an eye-candy specific while loop:

public void GoThrough(IEnumerable myEnumerable)
{
    foreach (object obj in myEnumerable)
    {
        MessageBox.Show(obj.ToString());
    }
}

is perfectly equivalent to:

public void GoThrough(IEnumerable myEnumerable)
{
    IEnumerator myEnumerator = myEnumerable.GetEnumerator();
    while (myEnumerator.MoveNext())
    {
        MessageBox.Show(myEnumerator.Current.ToString());
    }
}

The first writing is a lot simpler though.

2. while and do..while

The while (condition) {action} loop and the do {action} while (condition) loop just differ from each other by the fact that the first one tests the condition before applying the action, when the second one applies the action, then tests the condition. The do {..} while (..) loop is used quite marginally compared to the others, since it runs the action at least once even if the condition is initially not met (which can lead to trouble, since the action is generally dependent on the condition).

The while loop is more general than the for and foreach ones, which apply specifically to lists of objects. The while loop just has a condition to go on, which can be based on anything. For example:

string name = string.empty;
while (name == string.empty)
{
    Console.WriteLine("Enter your name");
    name = Console.ReadLine();
}

asks the user to input his name then press Enter, until he actually inputs something. Nothing to do with lists, as you can see.

3. Conclusion

When you are going through a list, you should use foreach unless you need the numeric index, in which case you should use for.
When it doesn't have anything to do with list, and it's just a procedural construction, you should use while(..) {..}.

Now to conclude with something less restrictive: your first goal with .NET should be to make your code readable/maintainable and make it run fast, in that order of priority. Anything that achieves that is good for you. Personally though, I think the foreach loop has the advantage that potentially, it's the most readable and the fastest.

Edit: there is an other case where the for loop is useful: when you need indexing to go through a list in a special way or if you need to modify the list when in the loop. For example, in this case because we want to remove every null element from myList:

for (int i=myList.Count-1; i>=0; i--)
{
    if (myList[i] == null) myList.RemoveAt(i);
}

You need the for loop here because myList cannot be modified from within a foreach loop, and we need to go through it backwards because if you remove the element at the position i, the position of all elements with an index >i will change.

But the use for these special constructions have been reduced since LINQ. The last example can be written like this in LINQ for example:

myList.RemoveAll(obj => obj == null);

LINQ is a second step though, learn the loops first.

ContentLicense: CC BY-SA 2.5


问:
Slower while generating the XML from the bunch of model object
```<code>class GenericFormatter < Formatter
 attr_accessor :tag_name,:objects

 def generate_xml
   builder = Nokogiri::XML::Builder.new do |xml|
   xml.send(tag_name.pluralize) {
   objects.each do |obj|
        xml.send(tag_name.singularize){

            self.generate_obj_row obj,xml
        }
    end
    }
   end
   builder.to_xml
 end

def initialize tag_name,objects
  self.tag_name = tag_name
  self.objects = objects
end

def generate_obj_row obj,xml
   obj.attributes.except("updated_at").map do |key,value|
     xml.send(key, value)
   end
   xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at')
end
 end
</code>```

In the above code, I have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is larger like more than 10,000 records then It's slow down the XML to generate and takes at least 50-60 seconds.

Problem: Is there any way to generate the XML faster, I have tried XML Builders on view as well but did n't work.How can I generate the XML Faster? Should the solution be an application on rails 3 and suggestions to optimized above code?

答:
The Nokogiri gem has a nice interface for creating XML from scratch,
Nokogiri is a wrapper around libxml2.

Gemfile gem 'nokogiri' To generate xml simple use the Nokogiri XML Builder like this

```<code>xml = Nokogiri::XML::Builder.new { |xml|
    xml.body do
        xml.test1 "some string"
        xml.test2 890
        xml.test3 do
            xml.test3_1 "some string"
        end
        xml.test4 "with attributes", :attribute => "some attribute"
        xml.closing
    end
}.to_xml
</code>```

output

```<code><?xml version="1.0"?>
<body>
  <test1>some string</test1>
  <test2>890</test2>
  <test3>
    <test3_1>some string</test3_1>
  </test3>
  <test4 attribute="some attribute">with attributes</test4>
  <closing/>
</body>
</code>```

Demo: http://www.jakobbeyer.de/xml-with-nokogiri

Body:
class GenericFormatter < Formatter
 attr_accessor :tag_name,:objects

 def generate_xml
   builder = Nokogiri::XML::Builder.new do |xml|
   xml.send(tag_name.pluralize) {
   objects.each do |obj|
        xml.send(tag_name.singularize){

            self.generate_obj_row obj,xml
        }
    end
    }
   end
   builder.to_xml
 end

def initialize tag_name,objects
  self.tag_name = tag_name
  self.objects = objects
end

def generate_obj_row obj,xml
   obj.attributes.except("updated_at").map do |key,value|
     xml.send(key, value)
   end
   xml.updated_at obj.updated_at.try(:strftime,"%m/%d/%Y %H:%M:%S") if obj.attributes.key?('updated_at')
end
 end

In the above code, I have implemented the formatter where I have used the nokogiri XML Builder to generate the XML by manipulating the objects passing out inside the code.It's generated the faster XML when the data is not too large if data is larger like more than 10,000 records then It's slow down the XML to generate and takes at least 50-60 seconds.

Problem: Is there any way to generate the XML faster, I have tried XML Builders on view as well but did n't work.How can I generate the XML Faster? Should the solution be an application on rails 3 and suggestions to optimized above code?

Body:
The Nokogiri gem has a nice interface for creating XML from scratch,
Nokogiri is a wrapper around libxml2.

Gemfile gem 'nokogiri' To generate xml simple use the Nokogiri XML Builder like this

xml = Nokogiri::XML::Builder.new { |xml|
    xml.body do
        xml.test1 "some string"
        xml.test2 890
        xml.test3 do
            xml.test3_1 "some string"
        end
        xml.test4 "with attributes", :attribute => "some attribute"
        xml.closing
    end
}.to_xml

output

<?xml version="1.0"?>
<body>
  <test1>some string</test1>
  <test2>890</test2>
  <test3>
    <test3_1>some string</test3_1>
  </test3>
  <test4 attribute="some attribute">with attributes</test4>
  <closing/>
</body>

Demo: http://www.jakobbeyer.de/xml-with-nokogiri


问:
How to fetch last row using distinct and group by same column
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

```<code>|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |
</code>```

i want output as

```<code>|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |
</code>```

答:
In case your ledger ID is keep on incrementing by 1 then you can use the below query to fetch the last row:------

```<code> SELECT TOP 1 * FROM Table ORDER BY LEDGERID DESC
</code>```

OR

```<code> SELECT * FROM TABLE ORDER BY LEDGERID DESC LIMIT 1
</code>```

Body:
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |

i want output as

|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |

Body:
In case your ledger ID is keep on incrementing by 1 then you can use the below query to fetch the last row:------

 SELECT TOP 1 * FROM Table ORDER BY LEDGERID DESC

OR

 SELECT * FROM TABLE ORDER BY LEDGERID DESC LIMIT 1


问:
Change Password Test Cases Selenium - Debug
Below is the test that i wrote for changing password.

@Test

```<code>    public void changePassword() throws IOException, InterruptedException {
        Login();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a")).click();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[3]/a")).click();
        driver.findElement(By.xpath(".//*[@id='change-password']/div[1]/div/input")).sendKeys("abcd");
        driver.findElement(By.xpath(".//*[@id='Users_password']")).sendKeys("xyz123456");
        driver.findElement(By.xpath(".//*[@id='repassword']")).sendKeys("xyz123456");
        driver.findElement(By.xpath(".//*[@id='change-password']/div[4]/div/input")).click();
    }
}
</code>```

Below is the Error that I am getting, I have checked the Xpath is correct, Still getting this error -

```<code>org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='change-password']/div[1]/div/input"}
Command duration or timeout: 2.81 seconds
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:410)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:509)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:402)
    at pages.ChangePass.changePassword(ChangePass.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)
    at org.testng.TestRunner.run(TestRunner.java:602)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='change-password']/div[1]/div/input"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'DESKTOP-1AKPPH7', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Driver info: driver.version: unknown
    at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:11390)
    at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:11399)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/k(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12879)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12884)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12826)
</code>```

My questions are -
1. What is wrong in above code, When i execute this it takes me to the change password screen.
2. Is above way the best way to test change password functionality?
3. Are there any more test scenarios that you can recomend me to include and how?

答:
Here are the Answers to your Question:

What is wrong in above code:

The xpaths you have constructed, e.g. .//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a, .//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[3]/a and .//*[@id='change-password']/div[1]/div/input are absolute xpaths which contains index. Hence they are brittle and vulnerable. You can consider constructing unique logical xpath.

Is above way the best way to test change password functionality?:

I don't think there are best practices in this. Because it is really depended on what you are trying to solve. But definitely before using sendKeys("abcd") method for a text field, you should consider using clear() method first.

When there is a NoSuchElementException: Unable to locate element, we should consider inducing ExplicitWait with proper ExpectedConditions so Selenium can locate the element atleast.

Let me know if this Answers your Question.

Body:
Below is the test that i wrote for changing password.

@Test

    public void changePassword() throws IOException, InterruptedException {
        Login();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/a")).click();
        driver.findElement(By.xpath(".//*[@id='wrapper']/div[1]/div[2]/div/div/ul/li[3]/ul/li[3]/a")).click();
        driver.findElement(By.xpath(".//*[@id='change-password']/div[1]/div/input")).sendKeys("abcd");
        driver.findElement(By.xpath(".//*[@id='Users_password']")).sendKeys("xyz123456");
        driver.findElement(By.xpath(".//*[@id='repassword']")).sendKeys("xyz123456");
        driver.findElement(By.xpath(".//*[@id='change-password']/div[4]/div/input")).click();
    }
}

Below is the Error that I am getting, I have checked the Xpath is correct, Still getting this error -

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='change-password']/div[1]/div/input"}
Command duration or timeout: 2.81 seconds
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:410)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:509)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:402)
    at pages.ChangePass.changePassword(ChangePass.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:744)
    at org.testng.TestRunner.run(TestRunner.java:602)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
    at org.testng.TestNG.runSuites(TestNG.java:1144)
    at org.testng.TestNG.run(TestNG.java:1115)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='change-password']/div[1]/div/input"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'DESKTOP-1AKPPH7', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Driver info: driver.version: unknown
    at <anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:11390)
    at <anonymous class>.FirefoxDriver.prototype.findElement(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:11399)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/k(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12879)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12884)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/Avinash/AppData/Local/Temp/anonymous9034314523683234934webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12826)

My questions are -
1. What is wrong in above code, When i execute this it takes me to the change password screen.
2. Is above way the best way to test change password functionality?
3. Are there any more test scenarios that you can recomend me to include and how?


问:
Laravel authentication: localhost redirected you too many times laravel 5.3
Sorry if this question have already existsed. I'm building web application with Laravel framework and version is 5.3. I have a problem that you can help me. It's redirected you too many times when authentication.

My route :

```<code>Route::get('/', [
'as' => 'ui.home',
'uses' => 'HandleController@home'
]);
Auth::routes();
</code>```

My middleware :

```<code>public function handle($request, Closure $next)
{
    if (!Auth::check()) {
        return redirect('/login');
    }

    return $next($request);
}
</code>```

I see a problem cause from Auth::check(). But, I can't fixed it. Please help me.

Thank you,

答:
may be the permission issue to the storage folder

```<code>sudo chmod -R 777 storage/
</code>```

ps: if you are in linux

Body:
Sorry if this question have already existsed. I'm building web application with Laravel framework and version is 5.3. I have a problem that you can help me. It's redirected you too many times when authentication.

My route :

Route::get('/', [
'as' => 'ui.home',
'uses' => 'HandleController@home'
]);
Auth::routes();

My middleware :

public function handle($request, Closure $next)
{
    if (!Auth::check()) {
        return redirect('/login');
    }

    return $next($request);
}

I see a problem cause from Auth::check(). But, I can't fixed it. Please help me.

Thank you,

Body:
may be the permission issue to the storage folder

sudo chmod -R 777 storage/

ps: if you are in linux


问:
Change pdf file name in report definition Odoo 10
Given this report definition, how can I change the file name used in the PDF so it uses names such as "SO-001.pdf".

```<code><report
        id = "report_custom_sale_order"
        string = "Quotation / Order"
        model = "sale.order"
        report_type = "qweb-pdf"
        file = "custom_saleorder.report_saleorder"
        name = "custom_saleorder.report_saleorder"
        paperformat = "custom_saleorder.paperformat_a4"
/>
</code>```

Odoo 10.

Thanks

答:
For giving your custom pdf file name use field "report_name".

For more information and any help related qweb report you can refer following link:

https://www.odoo.com/documentation/10.0/reference/reports.html

Body:
Given this report definition, how can I change the file name used in the PDF so it uses names such as "SO-001.pdf".

<report
        id = "report_custom_sale_order"
        string = "Quotation / Order"
        model = "sale.order"
        report_type = "qweb-pdf"
        file = "custom_saleorder.report_saleorder"
        name = "custom_saleorder.report_saleorder"
        paperformat = "custom_saleorder.paperformat_a4"
/>

Odoo 10.

Thanks


问:
Text to Speech Converter not working
I am trying to do text to speech converter using java code.And i am using freetts.jar to do this.I need to use this in my web application.

```<code>import com.sun.speech.freetts.*;
public class convert {
    private static final String VOICENAME="kevin";

    public static void call(){
    Voice voice;

    VoiceManager vm=VoiceManager.getInstance();
    System.out.println("come");
    voice=vm.getVoice(VOICENAME);

    voice.allocate();

    try{

        voice.speak("wellcome to my world");
        System.out.println("coming here good");
    }
    catch(Exception e){
        System.out.println(e);
    }
    }
    public static void main(String agrs[]){

        call();

    }

}
</code>```

In the above code was not working voice.speak() method was not working .I don't know why.can any one help me to fix this?

And also i need to know how to make the text to voice conversion  with own voice .
Thank you

答:
I know i am posting it little late, but this may help someone. I tried the similar, and it worked for me. Please find the code below.

```<code>    package com.mani.texttospeech;

import java.beans.PropertyVetoException;
import java.util.Locale;

import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;

/**
 *
 * @author Manindar
 */
public class SpeechUtils {

    SynthesizerModeDesc desc;
    Synthesizer synthesizer;
    Voice voice;

    public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
        if (desc == null) {
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            desc = new SynthesizerModeDesc(Locale.US);
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            synthesizer = Central.createSynthesizer(desc);
            synthesizer.allocate();
            synthesizer.resume();
            SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer.getEngineModeDesc();
            Voice[] voices = smd.getVoices();
            for (Voice voice1 : voices) {
                if (voice1.getName().equals(voiceName)) {
                    voice = voice1;
                    break;
                }
            }
            synthesizer.getSynthesizerProperties().setVoice(voice);
        }
    }

    public void terminate() throws EngineException, EngineStateError {
        synthesizer.deallocate();
    }

    public void doSpeak(String speakText) throws EngineException, AudioException, IllegalArgumentException, InterruptedException {
        synthesizer.speakPlainText(speakText, null);
        synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
    }

    public static void main(String[] args) throws Exception {
        SpeechUtils su = new SpeechUtils();
        su.init("kevin16");
//        su.init("kevin");
//        su.init("mbrola_us1");
//        su.init("mbrola_us2");
//        su.init("mbrola_us3");
        // high quality
        su.doSpeak("Hi this is Manindar. Welcome to audio world.");
        su.terminate();
    }
}
</code>```

And add the below dependencies to your pom.xml file.

```<code><dependencies>
        <dependency>
            <groupId>net.sf.sociaal</groupId>
            <artifactId>freetts</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>
</code>```

Hope this will be helpful.

Title: Text to Speech Converter not working

Body:
I am trying to do text to speech converter using java code.And i am using freetts.jar to do this.I need to use this in my web application.

import com.sun.speech.freetts.*;
public class convert {
    private static final String VOICENAME="kevin";

    public static void call(){
    Voice voice;

    VoiceManager vm=VoiceManager.getInstance();
    System.out.println("come");
    voice=vm.getVoice(VOICENAME);

    voice.allocate();

    try{

        voice.speak("wellcome to my world");
        System.out.println("coming here good");
    }
    catch(Exception e){
        System.out.println(e);
    }
    }
    public static void main(String agrs[]){

        call();

    }

}

In the above code was not working voice.speak() method was not working .I don't know why.can any one help me to fix this?

And also i need to know how to make the text to voice conversion  with own voice .
Thank you

Body:
I know i am posting it little late, but this may help someone. I tried the similar, and it worked for me. Please find the code below.

    package com.mani.texttospeech;

import java.beans.PropertyVetoException;
import java.util.Locale;

import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;

/**
 *
 * @author Manindar
 */
public class SpeechUtils {

    SynthesizerModeDesc desc;
    Synthesizer synthesizer;
    Voice voice;

    public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
        if (desc == null) {
            System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            desc = new SynthesizerModeDesc(Locale.US);
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            synthesizer = Central.createSynthesizer(desc);
            synthesizer.allocate();
            synthesizer.resume();
            SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer.getEngineModeDesc();
            Voice[] voices = smd.getVoices();
            for (Voice voice1 : voices) {
                if (voice1.getName().equals(voiceName)) {
                    voice = voice1;
                    break;
                }
            }
            synthesizer.getSynthesizerProperties().setVoice(voice);
        }
    }

    public void terminate() throws EngineException, EngineStateError {
        synthesizer.deallocate();
    }

    public void doSpeak(String speakText) throws EngineException, AudioException, IllegalArgumentException, InterruptedException {
        synthesizer.speakPlainText(speakText, null);
        synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
    }

    public static void main(String[] args) throws Exception {
        SpeechUtils su = new SpeechUtils();
        su.init("kevin16");
//        su.init("kevin");
//        su.init("mbrola_us1");
//        su.init("mbrola_us2");
//        su.init("mbrola_us3");
        // high quality
        su.doSpeak("Hi this is Manindar. Welcome to audio world.");
        su.terminate();
    }
}

And add the below dependencies to your pom.xml file.

<dependencies>
        <dependency>
            <groupId>net.sf.sociaal</groupId>
            <artifactId>freetts</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>

Hope this will be helpful.


问:
Twitter API: simple status update (Python)
I've been looking for a way to update my Twitter status from a Python client. As this client only needs to access one Twitter account, it should be possible to do this with a pre-generated oauth_token and secret, according to http://dev.twitter.com/pages/oauth_single_token

However the sample code does not seem to work, I'm getting 'could not authenticate you' or 'incorrect signature'..

As there are a bunch of different python-twitter library out there (and not all of them are up-to-date) I'd really appreciate if anybody could point me a library that's currently working for POST requests, or post some sample code!

Update:
I've tried Pavel's solution, and it works as long as the new message is only one word long, but as soon as it contains spaces, i get this error:

```<code>status = api.PostUpdate('hello world')
Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 2459, in PostUpdate
        self._CheckForTwitterError(data)
      File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 3394, in _CheckForTwitterErro
    r
        raise TwitterError(data['error'])
    python_twitter.twitter.TwitterError: Incorrect signature
</code>```

If however the update is just one word, it works:

```<code>status = api.PostUpdate('helloworld')
{'status': 'helloworld'}
</code>```

Any idea why this might be happening?

Thanks a lot in advance,

Hoff

答:
I've been able to solve this problem using another library - so I'll post my solution here for reference:</p>

```<code>import tweepy
# http://dev.twitter.com/apps/myappid
CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
# http://dev.twitter.com/apps/myappid/my_token
ACCESS_TOKEN_KEY= 'my access token key'
ACCESS_TOKEN_SECRET= 'my access token secret'

def tweet(status):
    '''
    updates the status of my twitter account
    requires tweepy (https://github.com/joshthecoder/tweepy)
    '''
    if len(status) > 140:
        raise Exception('status message is too long!')
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)
    result = api.update_status(status)
    return result
</code>```

Body:
I've been looking for a way to update my Twitter status from a Python client. As this client only needs to access one Twitter account, it should be possible to do this with a pre-generated oauth_token and secret, according to http://dev.twitter.com/pages/oauth_single_token

However the sample code does not seem to work, I'm getting 'could not authenticate you' or 'incorrect signature'..

As there are a bunch of different python-twitter library out there (and not all of them are up-to-date) I'd really appreciate if anybody could point me a library that's currently working for POST requests, or post some sample code!

Update:
I've tried Pavel's solution, and it works as long as the new message is only one word long, but as soon as it contains spaces, i get this error:

status = api.PostUpdate('hello world')
Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 2459, in PostUpdate
        self._CheckForTwitterError(data)
      File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 3394, in _CheckForTwitterErro
    r
        raise TwitterError(data['error'])
    python_twitter.twitter.TwitterError: Incorrect signature

If however the update is just one word, it works:

status = api.PostUpdate('helloworld')
{'status': 'helloworld'}

Any idea why this might be happening?

Thanks a lot in advance,

Hoff

Body:
I've been able to solve this problem using another library - so I'll post my solution here for reference:

import tweepy
# http://dev.twitter.com/apps/myappid
CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
# http://dev.twitter.com/apps/myappid/my_token
ACCESS_TOKEN_KEY= 'my access token key'
ACCESS_TOKEN_SECRET= 'my access token secret'

def tweet(status):
    '''
    updates the status of my twitter account
    requires tweepy (https://github.com/joshthecoder/tweepy)
    '''
    if len(status) > 140:
        raise Exception('status message is too long!')
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)
    result = api.update_status(status)
    return result


问:
type of object while implementing interface
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

```<code>public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}
</code>```

答:
You can use interface as a reference type in java.
It can only refer to objects of those classes that implement that interface.
But remember with interface as reference you can access only those methods that are declared in that interface. Your class may define additional methods but that won't be accessible using the interface reference.

In a way when you say class and interface are of different type you are right but when a class implements an interface it provides definition to all the methods declared in that interface and hence that interface can refer to the implementing class object.

It is kind of like with inheritance.

When a class implements an interface it is bound under a contract to provide implementation to all the methods.
So when a interface refers to a class object you can be pretty sure that that class must have implemented that interface and hence all your methods declaration now have definitions that can be called.

Body:
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}


答:
First try to add HTML snippet , so the locators can be written in much more redundant way.

2nd , Use some wait mechanism for the page to be loaded properly. In your case You are clicking on a link and trying to enter data in change password input filed, the exception you are getting due to the reason the page is not loaded properly and Selenium trying to enter the value in change password filed.

For a simple solution you can use Implicit wait and it will work

```<code>driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
</code>```

Title: Change Password Test Cases Selenium - Debug

Body:
First try to add HTML snippet , so the locators can be written in much more redundant way.

2nd , Use some wait mechanism for the page to be loaded properly. In your case You are clicking on a link and trying to enter data in change password input filed, the exception you are getting due to the reason the page is not loaded properly and Selenium trying to enter the value in change password filed.

For a simple solution you can use Implicit wait and it will work

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);


问:
writing data from forms to a SQLAlchemy database
I'm new to flask and making a microblogging application to get to know it.
I'm having a problem , The registration details of a new user are not being written to the database.
can someone help me?

Hers's my views function:

```<code>from app import app,db
from .forms import LoginForm,Register
from flask import render_template,session,redirect,url_for
from flask_login import login_user, logout_user, current_user,
login_required
@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html')

@app.route('/login',methods=['GET','POST'])
def login():
    form=LoginForm()
    return render_template('login.html',
                            title='Sign In',
                            form=form)
@app.route('/user',methods=['GET','POST'])
def user():
    return render_template('user.html')

@app.route('/register',methods=['GET','POST'])
def registration():
    reg=Register()
    if reg.validate_on_submit():
        u=User()
        u.username=register.username.data
        u.First_name=register.First_name.data
        u.Last_name=register.Last_name.data
        u.password=register.password.data
        u.email=register.email.data
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('index'))

    return render_template('register.html',
                            title='New Registration',
                            register=reg)
</code>```

Here's my model:

```<code>from app import db

class User(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    username=db.Column(db.String(32),index=True,unique=True)
    First_name=db.Column(db.String(32))
    Last_name=db.Column(db.String(32))
    password=db.Column(db.String(32))
    email=db.Column(db.String(20))
    posts=db.relationship('Post',backref='author',lazy='dynamic')

    def get_id(self):
        try:
            return unicode(self.id)  # python 2
        except NameError:
            return str(self.id)      #python 3

class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    body=db.Column(db.String(300))
    timestamp=db.Column(db.DateTime)
    user_id=db.Column(db.Integer,db.ForeignKey(User.id))
</code>```

forms.py

```<code>from flask_wtf import Form
from wtforms import StringField,BooleanField,PasswordField,validators

class LoginForm(Form):
    username=StringField('username',[validators.DataRequired()])
    password=PasswordField('password',[validators.DataRequired()])
    remember_me=BooleanField('remember me',default=False)

class Register(Form):
    first_name=StringField('f_name',[validators.DataRequired(message=None)])
    last_name=StringField('l_name',[validators.DataRequired(message=None)])
    email=StringField('email',[validators.Email(message='Enter a valid Email ID')])
    password=PasswordField('reg_password',[validators.Length(min=8,max=20)])
    username=StringField('u_name',[validators.DataRequired(message=None)])
    confirm_password=PasswordField('c_password',[validators.DataRequired(),validators.EqualTo('password',message='passwords should match')])
</code>```

here's the template for the registration page:

```<code><form action="" method="post" name="Login">
{{ register.hidden_tag() }}
<h1>New Registration</h1>
<p>First Name: {{ register.first_name }}</p>
<p>Last Name: {{ register.last_name}}</p>
<p>email:{{ register.email }}</p>
<p>username: {{register.username}}</p>
<p>Password:{{register.password}}</p>
<p>Password:{{register.confirm_password}}</p>
<p type="submit"><a href='/user' value="Register">Register</a></p>
</code>```

答:
I can't comment but is it possible you made a lot of changes in the code? I believe a review is necessary. For example the mapping between the elements in the form 'register' and the view don't seem to add up:

```<code>u.First_name=register.First_name.data
...
first_name=StringField('f_name',[validators.DataRequired(message=None)])
</code>```

but also the references in the view seem to point to 'register' instead of reg:

```<code>reg=Register()
if reg.validate_on_submit():
    u=User()
    u.username=register.username.data
</code>```

Also when going through your code I also made changes to the button in your template, as a quick change I changed the code for the button in:

```<code><button type="submit">register</button>
</code>```

It was for me unclear why you placed a link to the user page there (while using a redirect in your view):

```<code><p type="submit"><a href='/user' value="Register">Register</a></p>
</code>```

Body:
I'm new to flask and making a microblogging application to get to know it.
I'm having a problem , The registration details of a new user are not being written to the database.
can someone help me?

Hers's my views function:

from app import app,db
from .forms import LoginForm,Register
from flask import render_template,session,redirect,url_for
from flask_login import login_user, logout_user, current_user,
login_required
@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html')

@app.route('/login',methods=['GET','POST'])
def login():
    form=LoginForm()
    return render_template('login.html',
                            title='Sign In',
                            form=form)
@app.route('/user',methods=['GET','POST'])
def user():
    return render_template('user.html')

@app.route('/register',methods=['GET','POST'])
def registration():
    reg=Register()
    if reg.validate_on_submit():
        u=User()
        u.username=register.username.data
        u.First_name=register.First_name.data
        u.Last_name=register.Last_name.data
        u.password=register.password.data
        u.email=register.email.data
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('index'))

    return render_template('register.html',
                            title='New Registration',
                            register=reg)

Here's my model:

from app import db

class User(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    username=db.Column(db.String(32),index=True,unique=True)
    First_name=db.Column(db.String(32))
    Last_name=db.Column(db.String(32))
    password=db.Column(db.String(32))
    email=db.Column(db.String(20))
    posts=db.relationship('Post',backref='author',lazy='dynamic')

    def get_id(self):
        try:
            return unicode(self.id)  # python 2
        except NameError:
            return str(self.id)      #python 3

class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    body=db.Column(db.String(300))
    timestamp=db.Column(db.DateTime)
    user_id=db.Column(db.Integer,db.ForeignKey(User.id))

forms.py

from flask_wtf import Form
from wtforms import StringField,BooleanField,PasswordField,validators

class LoginForm(Form):
    username=StringField('username',[validators.DataRequired()])
    password=PasswordField('password',[validators.DataRequired()])
    remember_me=BooleanField('remember me',default=False)

class Register(Form):
    first_name=StringField('f_name',[validators.DataRequired(message=None)])
    last_name=StringField('l_name',[validators.DataRequired(message=None)])
    email=StringField('email',[validators.Email(message='Enter a valid Email ID')])
    password=PasswordField('reg_password',[validators.Length(min=8,max=20)])
    username=StringField('u_name',[validators.DataRequired(message=None)])
    confirm_password=PasswordField('c_password',[validators.DataRequired(),validators.EqualTo('password',message='passwords should match')])

here's the template for the registration page:

<form action="" method="post" name="Login">
{{ register.hidden_tag() }}

New Registration

First Name: {{ register.first_name }}

Last Name: {{ register.last_name}}

email:{{ register.email }}

username: {{register.username}}

Password:{{register.password}}

Password:{{register.confirm_password}}

Register

Body:
I can't comment but is it possible you made a lot of changes in the code? I believe a review is necessary. For example the mapping between the elements in the form 'register' and the view don't seem to add up:

u.First_name=register.First_name.data
...
first_name=StringField('f_name',[validators.DataRequired(message=None)])

but also the references in the view seem to point to 'register' instead of reg:

reg=Register()
if reg.validate_on_submit():
    u=User()
    u.username=register.username.data

Also when going through your code I also made changes to the button in your template, as a quick change I changed the code for the button in:

<button type="submit">register</button>

It was for me unclear why you placed a link to the user page there (while using a redirect in your view):

<p type="submit"><a href='/user' value="Register">Register</a></p>


问:
Unable to set status on pull request of a different open source project using Github API v3
I have a public repository on github on which there is a random pull request. Using Github API v3 and my personal access token, I am able to set the status using :

```<code>curl "https://api.github.com/repos/user/DummyProject/statuses/xxx42a7aaa2aab10875aexxxxxxf675a73c52ac?access_token=xxxxxxxx4d765693ac40a4a51cxxxx7a3100ef50"   -H "Content-Type: application/json"   -X POST   -d "{\"state\": \"success\", \"context\":\"BuildBot\", \"description\": \"build success\", \"target_url\": \"http://www.example.com\"}"
</code>```

However, I need to create a separate github account for this build bot, which will set the build statuses on my projects. The moment I replace my token with the buildbot token, I get the following response :

```<code>{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3"
}
</code>```

The token that I generated for buildbot has all the permissions marked, still why this buildbot is not able to set status? The project is open source.

答: I figured this out later that the non-project-owner need to be added as a collaborator in order to set statuses on the project.</p>

Body:
I have a public repository on github on which there is a random pull request. Using Github API v3 and my personal access token, I am able to set the status using :

curl "https://api.github.com/repos/user/DummyProject/statuses/xxx42a7aaa2aab10875aexxxxxxf675a73c52ac?access_token=xxxxxxxx4d765693ac40a4a51cxxxx7a3100ef50"   -H "Content-Type: application/json"   -X POST   -d "{\"state\": \"success\", \"context\":\"BuildBot\", \"description\": \"build success\", \"target_url\": \"http://www.example.com\"}"

However, I need to create a separate github account for this build bot, which will set the build statuses on my projects. The moment I replace my token with the buildbot token, I get the following response :

{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3"
}

The token that I generated for buildbot has all the permissions marked, still why this buildbot is not able to set status? The project is open source.


问:
How can I make my TextView font as shown in image
I am trying to style my text of STUDENT LOGIN which is shown in the image.
But I don't know how can use a different custom font to make my STUDENT LOGIN to look like as shown in the image.

I want Style in that way. How Can I make my S and L shown in image

答:
If you don't want to use default font and want to use different font without hassle, just use this library. You can apply custom font to whole app or particular TextView.

Example for specific TextView :

```<code><TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fontPath="fonts/Roboto-Bold.ttf"/>
</code>```

Follow the instruction from read me file and you will get what you want.

Body:
If you don't want to use default font and want to use different font without hassle, just use this library. You can apply custom font to whole app or particular TextView.

Example for specific TextView :

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fontPath="fonts/Roboto-Bold.ttf"/>

Follow the instruction from read me file and you will get what you want.


问:
updating a fragment from activity during runtime, view variable not global
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

```<code>public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}
</code>```

and my activity

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
</code>```

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

```<code>    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);
</code>```

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
LocalBroadcastManager will do the trick for you

Register LocalBroadcastManager into you fragment

```<code>private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get data from intent and update
  }
};
</code>```

Register mMessageReceiver in onCreate()

```<code>@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive data.
  // with actions named "my-event".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}
</code>```

Write the code below to update data from activity to fragment, This is to be written in Activity

```<code>Intent intent = new Intent("my-event");
// You can also include some extra data.
intent.putExtra("data", "my data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
</code>```

Do not forget to unregister the BroadcastReceiver on OnDestory() methos

Body:
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}

and my activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
LocalBroadcastManager will do the trick for you

Register LocalBroadcastManager into you fragment

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get data from intent and update
  }
};

Register mMessageReceiver in onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive data.
  // with actions named "my-event".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}

Write the code below to update data from activity to fragment, This is to be written in Activity

Intent intent = new Intent("my-event");
// You can also include some extra data.
intent.putExtra("data", "my data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Do not forget to unregister the BroadcastReceiver on OnDestory() methos


问:
In Delphi: How to skip sections of code while debugging?
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

```<code>function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;
</code>```

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

答:
AFAIK, the debugger is only aware of the files in Browsing Path that you can modify in Options. So if you exclude the paths of modules you're not interested in debugging that will give the effect of what you want to do.

One caveat: code completion also relies on Browsing Path so you might run into occasions that code completion falls short when needed.

OwnerDisplayName: Wouter van Nifterick

Body:
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

LastEditorDisplayName: Wouter van Nifterick

OwnerDisplayName: utku karatas


问:
IE8 ul menu styling problem
I have a menu using an UL, as usual it works finr in FFX but not in IE. I've tried a few things but can't get any good results. Anyone have any ideas or pointers?

please see the attached code and image. If you look closely you can see the bullet points(black) on the left hand side. Where as in firefox a lovely menu is displayed....correctly! :)

Merry Xmas!!!

L

答:
i can't find any code here, can you upload it at pastebin.com?

```<code>#menu ul
{
    margin: 0 auto;
    font-weight:bold;
    list-style:none;
}
</code>```

This code makes me not seeing any dot in IE!

Title: IE8 ul menu styling problem

Body:
i can't find any code here, can you upload it at pastebin.com?

#menu ul
{
    margin: 0 auto;
    font-weight:bold;
    list-style:none;
}

This code makes me not seeing any dot in IE!


问:
Django Url direct error
My Django urlpatterns:

```<code>urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login', views.login_page, name='login'),
url(r'^logout', views.logout_page, name='logout'),
url(r'^register', views.register_page, name='register'),
url(r'^create_book', views.create_book, name='create_book'),

url(r'^^(?P<book_id>[0-9]+)/$', views.book_details, name='book_details'),

url(r'^^(?P<book_id>[0-9]+)/create_entry$', views.create_entry, name='create_entry'),   ]
</code>```

I am trying to do this:

```<code>{% url 'book:book_details' book.pk %}
</code>```

It gives this error:

```<code>NoReverseMatch at /
</code>```

Reverse for 'book_details' with keyword arguments '{'book_id': 1}' not found. 1 pattern(s) tried: ['^(?P<book_id>[0-9]+)/$']

But going to localhost:8000/ <some id> directly in the browser works

How do I write the {% url %} part so that it goes to /(some id)

答:
change this line in template

```<code>{% url 'book:book_details' book.pk %}
</code>```

to

```<code>{% url 'book_details' book.pk %}
</code>```

and remove the extra caret sign ^ from the url

```<code>url(r'^(?P<book_id>[0-9]+)/$', views.book_details, name='book_details'),

url(r'^(?P<book_id>[0-9]+)/create_entry$', views.create_entry, name='create_entry'),
</code>```

Title: Django Url direct error

Body:
My Django urlpatterns:

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login', views.login_page, name='login'),
url(r'^logout', views.logout_page, name='logout'),
url(r'^register', views.register_page, name='register'),
url(r'^create_book', views.create_book, name='create_book'),

url(r'^^(?P<book_id>[0-9]+)/$', views.book_details, name='book_details'),

url(r'^^(?P<book_id>[0-9]+)/create_entry$', views.create_entry, name='create_entry'),   ]

I am trying to do this:

{% url 'book:book_details' book.pk %}

It gives this error:

NoReverseMatch at /

Reverse for 'book_details' with keyword arguments '{'book_id': 1}' not found. 1 pattern(s) tried: ['^(?P<book_id>[0-9]+)/$']

But going to localhost:8000/ <some id> directly in the browser works

How do I write the {% url %} part so that it goes to /(some id)

Body:
change this line in template

{% url 'book:book_details' book.pk %}

to

{% url 'book_details' book.pk %}

and remove the extra caret sign ^ from the url

url(r'^(?P<book_id>[0-9]+)/$', views.book_details, name='book_details'),

url(r'^(?P<book_id>[0-9]+)/create_entry$', views.create_entry, name='create_entry'),