问:
How to find all positions of the maximum value in a list?
I have a list:

```<code>a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]
</code>```

max element is 55 (two elements on position 9 and 12)

I need to find on which position(s) the maximum value is situated. Please, help.

答:
If you want to get the indices of the largest n numbers in a list called data, you can use Pandas sort_values:

```<code>pd.Series(data).sort_values(ascending=False).index[0:n]
</code>```

Body:
I have a list:

a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]

max element is 55 (two elements on position 9 and 12)

I need to find on which position(s) the maximum value is situated. Please, help.

Body:
If you want to get the indices of the largest n numbers in a list called data, you can use Pandas sort_values:

pd.Series(data).sort_values(ascending=False).index[0:n]


来源: stackexchange

问:
Does "autoWebView" APPIUM capability guarantee correct WEB_VIEW out of multiple webviews ,in relation to cordova app?
I am working on automating a iOS app using Appium-Java.

In appium documentation it was mentioned that- "autoWebView" APPIUM capability should be used for Cordova based app

In our case, app keeps on stacking multiple WebViews, as the user goes on navigating the screens.
And in that case normally I have 1 Native View & 3-4 WebViews.
So if I set autoWebView, will it gurantee that- it will always point to correct webview (i.e. the webview, which contains HTML for current page)

答:
Hope you are using ios_webkit_debug_proxy to handle webview embedded in ios native app. Also switch the context accordingly in your script whenever the app pages change("NATIVE" or "WEBVIEW").

Have a look at this link https://github.com/google/ios-webkit-debug-proxy

ContentLicense: CC BY-SA 3.0


问:
WP7 ListPicker scrolling issue
I have created the following:

```<code>    <!--Pivot Control-->
   < controls:Pivot Title="name"

        <!--Pivot item one-->
       < controls:PivotItem Header="h1">
            <Grid>
                <Image Height="140" HorizontalAlignment="Left" Margin="24,21,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
               <TextBlock Height="146" HorizontalAlignment="Left" Margin="246,21,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="194" />
                <StackPanel Margin="10,200,0,0">
                    <toolkit:ListPicker Header="header1" HorizontalAlignment="Left" Name="ListPicker1" VerticalAlignment="Top" Width="429" />
                    <toolkit:ListPicker Header="header2" HorizontalAlignment="Left" Name="ListPicker2" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    <toolkit:ListPicker Header="header3" HorizontalAlignment="Left" Name="ListPicker3" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    </StackPanel>
            <Grid>
        <controls:PivotItem>

        <!--Pivot item two-->
        <controls:PivotItem Header="h2">
            <Grid/>
        <controls:PivotItem>
        <!--Pivot item three-->
        <controls:PivotItem Header="h3">
           < Grid/>
        </controls:PivotItem>
    </controls:Pivot>
</Grid>
</code>```

the third lisppicker ListPicker3 has 5 items I can only see the first two items and the remaining 3 items are invisble because they are below in the page.  The prob is that I cannot scroll down to see them.

Could someone tell me if there is a way to scroll down the page to see the value of the expanded ListPicker3 or suggest me a method to resolve this.

Thanks

答:
You could configure the ListPickers to open in "Full" mode - no matter how many items there are in them. Normally they open in different mode depending on how many items they contain.

If you set ItemCountThreshold="0" and ListPickerMode="Full" they should always open in full mode (like a popup/new window).

You can read more about it here: ListPicker for WP7 in depth

ContentLicense: CC BY-SA 2.5

Title: WP7 ListPicker scrolling issue

Body:
I have created the following:

   < controls:Pivot Title="name"

       < controls:PivotItem Header="h1">
            <Grid>
                <Image Height="140" HorizontalAlignment="Left" Margin="24,21,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
               <TextBlock Height="146" HorizontalAlignment="Left" Margin="246,21,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="194" />
                <StackPanel Margin="10,200,0,0">
                    <toolkit:ListPicker Header="header1" HorizontalAlignment="Left" Name="ListPicker1" VerticalAlignment="Top" Width="429" />
                    <toolkit:ListPicker Header="header2" HorizontalAlignment="Left" Name="ListPicker2" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    <toolkit:ListPicker Header="header3" HorizontalAlignment="Left" Name="ListPicker3" VerticalAlignment="Top" Width="429" CacheMode="BitmapCache" />
                    </StackPanel>
            <Grid>
        <controls:PivotItem>

        <controls:PivotItem Header="h2">
            <Grid/>
        <controls:PivotItem>

        <controls:PivotItem Header="h3">
           < Grid/>
        </controls:PivotItem>
    </controls:Pivot>
</Grid>

the third lisppicker ListPicker3 has 5 items I can only see the first two items and the remaining 3 items are invisble because they are below in the page.  The prob is that I cannot scroll down to see them.

Could someone tell me if there is a way to scroll down the page to see the value of the expanded ListPicker3 or suggest me a method to resolve this.

Thanks


问:
Upload Photo in Python
I try to upload avatar using code (I am using Python and Linux os):

```<code>photo = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="ButtonChangePhoto"]')))
photo.send_keys('/home/nataliya/Desktop/puppy.jpg')
</code>```

But the problem I am facing - avatar stays the same.
Question: what is not correct in here?

Update:
here is error i got on Chrome:

```<code>Traceback (most recent call last):

WebDriverException: Message: unknown error: cannot focus element
(Session info: chrome=62.0.3202.75)
(Driver info: chromedriver=2.33.506092   (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.10.0-38-generic x86_64)
</code>```

答:
Simply you can use this

```<code>driver.find_element_by_id("Locator").send_keys(os.getcwd()+"/image.png")
</code>```

You can use any locator

os.getcwd() : returns the current working directory

Title: Upload Photo in Python

Body:
I try to upload avatar using code (I am using Python and Linux os):

photo = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="ButtonChangePhoto"]')))
photo.send_keys('/home/nataliya/Desktop/puppy.jpg')

But the problem I am facing - avatar stays the same.
Question: what is not correct in here?

Update:
here is error i got on Chrome:

Traceback (most recent call last):

WebDriverException: Message: unknown error: cannot focus element
(Session info: chrome=62.0.3202.75)
(Driver info: chromedriver=2.33.506092   (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.10.0-38-generic x86_64)

Body:
Simply you can use this

driver.find_element_by_id("Locator").send_keys(os.getcwd()+"/image.png")

You can use any locator

os.getcwd() : returns the current working directory


问:
Indexwise sum of list of lists using rxjava
I have a list of array lists. Each list in the main list contains constant number of items. (Say 3 items in each array list)
. What I want to do is I need to get the indexwise sum of each list as a new List.
for example If my main List contains array lists like

```<code>       1, 2, 3
       1, 2, 3
       1, 2, 3
</code>```

then my resultant list should be

```<code>       3, 6, 9
</code>```

and I have to do this with RxJava only. Since I am very new to RxJava I'm confused with wich operators I should use. I tried many ways but since those are not working I'm not posting with question. If anyone could suggest a hint or suggestion it would be very helpful. Thanks in advance

My source list is

```<code>        List<ArrayList<Integer>> mainList;
</code>```

and I need a resultant List<Integer> sumList

答:
1)You should add the following RxMath dependency in your build.gradle (app level).

```<code>  compile 'io.reactivex:rxjava-math:1.0.0'
</code>```

2) Use the following code to add sum of integer values from an Array or List.

```<code>int totalCount =  MathObservable.sumInteger(Observable.just(classesItemList)
                .flatMapIterable(new Func1<List<ClassesItem>, Iterable<? extends ClassesItem>>() {
                    @Override
                    public Iterable<? extends ClassesItem> call(List<ClassesItem> list) {
                        return list;
                    }
                })
                .map(new Func1<ClassesItem, Integer>() {
                    @Override
                    public Integer call(ClassesItem classesItem) {
                        return classesItem != null ? classesItem.getStudentsCount() : 0;
                    }
                })).toBlocking().single();
</code>```

3) use the total count wherever you want.

Body:
I have a list of array lists. Each list in the main list contains constant number of items. (Say 3 items in each array list)
. What I want to do is I need to get the indexwise sum of each list as a new List.
for example If my main List contains array lists like

       1, 2, 3
       1, 2, 3
       1, 2, 3

then my resultant list should be

       3, 6, 9

and I have to do this with RxJava only. Since I am very new to RxJava I'm confused with wich operators I should use. I tried many ways but since those are not working I'm not posting with question. If anyone could suggest a hint or suggestion it would be very helpful. Thanks in advance

My source list is

        List<ArrayList<Integer>> mainList;

and I need a resultant List<Integer> sumList

Body:
1)You should add the following RxMath dependency in your build.gradle (app level).

  compile 'io.reactivex:rxjava-math:1.0.0'

2) Use the following code to add sum of integer values from an Array or List.

int totalCount =  MathObservable.sumInteger(Observable.just(classesItemList)
                .flatMapIterable(new Func1<List<ClassesItem>, Iterable<? extends ClassesItem>>() {
                    @Override
                    public Iterable<? extends ClassesItem> call(List<ClassesItem> list) {
                        return list;
                    }
                })
                .map(new Func1<ClassesItem, Integer>() {
                    @Override
                    public Integer call(ClassesItem classesItem) {
                        return classesItem != null ? classesItem.getStudentsCount() : 0;
                    }
                })).toBlocking().single();

3) use the total count wherever you want.


问:
How can I define one specific fragment instance's style/theme in XML?
I've created a UI component in my app that is used in multiple places (some light, some dark) and needs to be lifecycle-aware, so I've converted it into a fragment.  I instantiate this fragment exclusively using <fragment> tags in my activities' XML layout files.

I'm struggling to find a way to enable the fragment to render its own controls and text in a colour that's appropriate for its background as set by its parent element.  Currently, no matter what theme or style I set on the parent view or the <fragment> tag itself, the fragment controls are shown as if on a light background:

I've tried setting android:theme on the <fragment> to both @style/ThemeOverlay.AppCompat.Dark and @style/ThemeOverlay.AppCompat.Dark.ActionBar in an attempt to get the text light-coloured on the dark background, but with no luck.

I would prefer not to program this colour switching into the fragment itself, because I feel like the theming/styling framework must surely be able to handle this.

Ideally, I would also be able to incorporate an icon into this fragment at a later stage with its colour matching the text.  My priority right now though is getting the correct text colour.

What is the correct way to tell one specific instance of a fragment, “you are on a dark background instead of a light one,” or “you need to render your text and controls in a light colour instead of a dark one,” and have it render accordingly?

Update

I've posted an answer that does it by implementing a custom attribute on the <fragment> tag and initialising from it in my fragment's code.

Previous update

Chris Banes' article on Theme vs. Style states:

One thing to note is that android:theme in Lollipop propogates to all children declared in the layout:

```<code><LinearLayout
    android:theme="@android:style/ThemeOverlay.Material.Dark">

    <!-- Anything here will also have a dark theme -->

</LinearLayout>
</code>```

Your children can set their own theme if needed.

This is distinctly not happening in my case with the use of fragments—it seems that the android:theme attribute of the <fragment> tag in the XML is not being considered at all during the inflation, but should be.

My fragment's onCreateView method is quite standard:

```<code>@Override
public View onCreateView(
        @NonNull LayoutInflater inflater,
        @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState
) {
    return inflater.inflate(R.layout.fragment_task_search, container, false);
}
</code>```

I suppose either the container is not getting the theme to begin with, or the inflater is not “attaching” that information to the inflated child view.  I'm not proficient enough in Android development to determine which (if either) is the case.

答:
I have achieved the desired effect by explicitly specifying the parent container's theme in a custom attribute on the <fragment> tag, and manually reading it during the fragment's initialisation.

XML layout file using the <fragment>

Ensure the root element of the XML has the following xmlns:app attribute:

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

Add a custom attribute of app:customTheme to the <fragment> tag:

```<code><fragment
    android:name="net.alexpeters.myapp.TaskSearchFragment"
    app:customTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</code>```

Attributes XML file values/attrs.xml

Add the declare-styleable element shown below:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <!-- ↓↓↓ -->
        <declare-styleable name="TaskSearchFragment">
            <attr name="customTheme" format="reference" />
        </declare-styleable>
        <!-- ↑↑↑ -->
    </resources>
</code>```

Fragment subclass

Add an instance variable to hold a custom theme ID:

```<code>private @StyleRes int themeResId;
</code>```

Add a constant to handle the case where no custom theme is passed in:

```<code>private static final int NO_CUSTOM_THEME = 0;
</code>```

Override the onInflate method as follows:

```<code>@Override
public void onInflate(
        @NonNull Context context,
        AttributeSet attrs,
        Bundle savedInstanceState
) {
    super.onInflate(context, attrs, savedInstanceState);
    TypedArray a = context.obtainStyledAttributes(
            attrs,
            R.styleable.TaskSearchFragment
    );
    themeResId = a.getResourceId(
            R.styleable.TaskSearchFragment_customTheme,
            NO_CUSTOM_THEME
    );
    a.recycle();
}
</code>```

Add some logic to the onCreateView method to inject the custom theme reference into the inflater:

```<code>@Nullable
@Override
public View onCreateView(
        @NonNull LayoutInflater inflater,
        @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState
) {
    // ↓↓↓
    if (themeResId != NO_CUSTOM_THEME) {
        inflater = inflater.cloneInContext(
            new ContextThemeWrapper(getActivity(), themeResId)
        );
    }
    // ↑↑↑
    return inflater.inflate(R.layout.fragment_task_search, container, false);
}
</code>```

I'd prefer to just infer the parent container's theme somehow, but I don't know whether this is possible.

Failing that, I'd prefer to use a standard attribute (i.e. android:theme) instead of a custom one, but I don't know whether this is possible either.

Body:
I've created a UI component in my app that is used in multiple places (some light, some dark) and needs to be lifecycle-aware, so I've converted it into a fragment.  I instantiate this fragment exclusively using <fragment> tags in my activities' XML layout files.

I'm struggling to find a way to enable the fragment to render its own controls and text in a colour that's appropriate for its background as set by its parent element.  Currently, no matter what theme or style I set on the parent view or the <fragment> tag itself, the fragment controls are shown as if on a light background:

I've tried setting android:theme on the <fragment> to both @style/ThemeOverlay.AppCompat.Dark and @style/ThemeOverlay.AppCompat.Dark.ActionBar in an attempt to get the text light-coloured on the dark background, but with no luck.

I would prefer not to program this colour switching into the fragment itself, because I feel like the theming/styling framework must surely be able to handle this.

Ideally, I would also be able to incorporate an icon into this fragment at a later stage with its colour matching the text.  My priority right now though is getting the correct text colour.

What is the correct way to tell one specific instance of a fragment, “you are on a dark background instead of a light one,” or “you need to render your text and controls in a light colour instead of a dark one,” and have it render accordingly?

Update

I've posted an answer that does it by implementing a custom attribute on the <fragment> tag and initialising from it in my fragment's code.

Previous update

Chris Banes' article on Theme vs. Style states:

One thing to note is that android:theme in Lollipop propogates to all children declared in the layout:

<LinearLayout
    android:theme="@android:style/ThemeOverlay.Material.Dark">

</LinearLayout>

Your children can set their own theme if needed.

This is distinctly not happening in my case with the use of fragments—it seems that the android:theme attribute of the <fragment> tag in the XML is not being considered at all during the inflation, but should be.

My fragment's onCreateView method is quite standard:

@Override
public View onCreateView(
        @NonNull LayoutInflater inflater,
        @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState
) {
    return inflater.inflate(R.layout.fragment_task_search, container, false);
}

I suppose either the container is not getting the theme to begin with, or the inflater is not “attaching” that information to the inflated child view.  I'm not proficient enough in Android development to determine which (if either) is the case.

Body:
I have achieved the desired effect by explicitly specifying the parent container's theme in a custom attribute on the <fragment> tag, and manually reading it during the fragment's initialisation.

XML layout file using the <fragment>

Ensure the root element of the XML has the following xmlns:app attribute:

xmlns:app="http://schemas.android.com/apk/res-auto"

Add a custom attribute of app:customTheme to the <fragment> tag:

<fragment
    android:name="net.alexpeters.myapp.TaskSearchFragment"
    app:customTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

Attributes XML file values/attrs.xml

Add the declare-styleable element shown below:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <!-- ↓↓↓ -->
        <declare-styleable name="TaskSearchFragment">
            <attr name="customTheme" format="reference" />
        </declare-styleable>
        <!-- ↑↑↑ -->
    </resources>

Fragment subclass

Add an instance variable to hold a custom theme ID:

private @StyleRes int themeResId;

Add a constant to handle the case where no custom theme is passed in:

private static final int NO_CUSTOM_THEME = 0;

Override the onInflate method as follows:

@Override
public void onInflate(
        @NonNull Context context,
        AttributeSet attrs,
        Bundle savedInstanceState
) {
    super.onInflate(context, attrs, savedInstanceState);
    TypedArray a = context.obtainStyledAttributes(
            attrs,
            R.styleable.TaskSearchFragment
    );
    themeResId = a.getResourceId(
            R.styleable.TaskSearchFragment_customTheme,
            NO_CUSTOM_THEME
    );
    a.recycle();
}

Add some logic to the onCreateView method to inject the custom theme reference into the inflater:

@Nullable
@Override
public View onCreateView(
        @NonNull LayoutInflater inflater,
        @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState
) {
    // ↓↓↓
    if (themeResId != NO_CUSTOM_THEME) {
        inflater = inflater.cloneInContext(
            new ContextThemeWrapper(getActivity(), themeResId)
        );
    }
    // ↑↑↑
    return inflater.inflate(R.layout.fragment_task_search, container, false);
}

I'd prefer to just infer the parent container's theme somehow, but I don't know whether this is possible.

Failing that, I'd prefer to use a standard attribute (i.e. android:theme) instead of a custom one, but I don't know whether this is possible either.


问:
Shrink the size of 2D array by removing specific rows and columns from it
I'm learning C, and I can't find a solution to this problem.

If I have a matrix of random size filled with '*'(star), '-'(horizontal bar), '|'(vertical bar),'+'(plus sign) and I want to remove every row that has a '-', every column that has a '|', every row and column in which there is a '+'.

How would i reduce the size of the matrix so that when i print the remaining '*'(star) there are no rows and columns between them that were removed?

For example:

```<code>char mat[3][3] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};
</code>```

The output would be:

```<code>**
**
**
</code>```

Another example:

```<code>char mat[3][3] = {{'*', '*', '*'},
                  {'*', '+', '*'},
                  {'*', '*', '*'}};
</code>```

The output would be:

```<code>**
**
</code>```

Larger matrix:

```<code>char mat[4][5] = {{'*', '|', '*', '|', '*'},
                  {'*', '*', '*', '*', '*'},
                  {'*', '+', '*', '-', '*'}
                  {'*', '*', '*', '*', '-'}};
</code>```

The output would be:

```<code>***
***
</code>```

Thanks in advance.

答:
I think it's quite simple.

One of brutal methods is 1) scan the whole input matrix and find the numbers of rows and columns that should be removed according to those '-', '|', '+' found in the input matrix, say they are r, c, 2) the numbers of rows and columns in the output matrix can be inferred, which are x - r, y - c, assuming x, y are the numbers of rows and columns in the input matrix.

Body:
I'm learning C, and I can't find a solution to this problem.

If I have a matrix of random size filled with '*'(star), '-'(horizontal bar), '|'(vertical bar),'+'(plus sign) and I want to remove every row that has a '-', every column that has a '|', every row and column in which there is a '+'.

How would i reduce the size of the matrix so that when i print the remaining '*'(star) there are no rows and columns between them that were removed?

For example:

char mat[3][3] = {{'|', '*', '*'},
                  {'*', '*', '*'},
                  {'*', '*', '*'}};

The output would be:

**
**
**

Another example:

char mat[3][3] = {{'*', '*', '*'},
                  {'*', '+', '*'},
                  {'*', '*', '*'}};

The output would be:

**
**

Larger matrix:

char mat[4][5] = {{'*', '|', '*', '|', '*'},
                  {'*', '*', '*', '*', '*'},
                  {'*', '+', '*', '-', '*'}
                  {'*', '*', '*', '*', '-'}};

The output would be:

***
***

Thanks in advance.


问:
c-sharp Get working hours within a time span
Given multiple time span, how can I get an array that gives me number of working hours for a day.

The working hours start at 09:00 and end at 17:00

Examples:

15-Nov-2017 16:00 - 17-Nov-2017 12:00 -> Should give me an array of [1,8,3]

15-Nov-2017 09:00 - 17-Nov-2017 12:00 -> Should give me an array of [8,8,1] (This seems easy as I can do Hrs / 8 and Hrs % 8 to get the result.)

16-Nov-2017 15:00 - 17-Nov-2017 15:00 -> Should give me an array of [2,6]

This is the method that currently gives me total working hours between the start time and end time:

```<code>protected double getWorkingHrs(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;

    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
    }

    return count;
}
</code>```

Any help would be appreciated.

Task showed like this in 8 hour blocks. So when I add a 20 Hour task, I have to break them down into sets and display them in the grid. I have to split them as chances are the task on different day might get assigned to a different user and may have different notes etc.

Cheers

答:
Here is a solution for your problem:

```<code>    public static double[] GetWorkHours(DateTime start, DateTime end, TimeSpan workStartTime, TimeSpan workEndTime)
    {
        IList<double> result = new List<double>();

        if (start > end)
        {
            throw new ArgumentException("Start date is later than end date");
        }

        DateTime currentDate = start.Date;
        while (currentDate <= end.Date)
        {
            if (currentDate.DayOfWeek != DayOfWeek.Saturday && currentDate.DayOfWeek != DayOfWeek.Sunday)
            {
                TimeSpan realStartTime = GetStartTimeForDay(start, end, workStartTime, currentDate);
                TimeSpan realEndTime = GetEndTimeForDay(start, end, workEndTime, currentDate);

                if (realStartTime >= workEndTime || realEndTime <= workStartTime)
                {
                    result.Add(0);
                }
                else
                {
                    result.Add(GetHoursInTimePeriod(realStartTime, realEndTime));
                }
            }

            currentDate = currentDate.AddDays(1);
        }

        return result.ToArray();
    }

    private static TimeSpan GetStartTimeForDay(DateTime start, DateTime end, TimeSpan workStartTime, DateTime day)
    {
        return day == start.Date ? (start.TimeOfDay < workStartTime ? workStartTime : start.TimeOfDay) : workStartTime;
    }

    private static TimeSpan GetEndTimeForDay(DateTime start, DateTime end, TimeSpan workEndTime, DateTime day)
    {
        return day == end.Date ? (end.TimeOfDay < workEndTime ? end.TimeOfDay : workEndTime) : workEndTime;
    }

    private static double GetHoursInTimePeriod(TimeSpan start, TimeSpan end)
    {
        return (end - start).TotalHours;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given multiple time span, how can I get an array that gives me number of working hours for a day.

The working hours start at 09:00 and end at 17:00

Examples:

15-Nov-2017 16:00 - 17-Nov-2017 12:00 -> Should give me an array of [1,8,3]

15-Nov-2017 09:00 - 17-Nov-2017 12:00 -> Should give me an array of [8,8,1] (This seems easy as I can do Hrs / 8 and Hrs % 8 to get the result.)

16-Nov-2017 15:00 - 17-Nov-2017 15:00 -> Should give me an array of [2,6]

This is the method that currently gives me total working hours between the start time and end time:

protected double getWorkingHrs(DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    double count = 0;

    for (var i = _dtTaskStart; i < _dtTaskEnd; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
    }

    return count;
}

Any help would be appreciated.

Task showed like this in 8 hour blocks. So when I add a 20 Hour task, I have to break them down into sets and display them in the grid. I have to split them as chances are the task on different day might get assigned to a different user and may have different notes etc.

Cheers

Body:
Here is a solution for your problem:

    public static double[] GetWorkHours(DateTime start, DateTime end, TimeSpan workStartTime, TimeSpan workEndTime)
    {
        IList<double> result = new List<double>();

        if (start > end)
        {
            throw new ArgumentException("Start date is later than end date");
        }

        DateTime currentDate = start.Date;
        while (currentDate <= end.Date)
        {
            if (currentDate.DayOfWeek != DayOfWeek.Saturday && currentDate.DayOfWeek != DayOfWeek.Sunday)
            {
                TimeSpan realStartTime = GetStartTimeForDay(start, end, workStartTime, currentDate);
                TimeSpan realEndTime = GetEndTimeForDay(start, end, workEndTime, currentDate);

                if (realStartTime >= workEndTime || realEndTime <= workStartTime)
                {
                    result.Add(0);
                }
                else
                {
                    result.Add(GetHoursInTimePeriod(realStartTime, realEndTime));
                }
            }

            currentDate = currentDate.AddDays(1);
        }

        return result.ToArray();
    }

    private static TimeSpan GetStartTimeForDay(DateTime start, DateTime end, TimeSpan workStartTime, DateTime day)
    {
        return day == start.Date ? (start.TimeOfDay < workStartTime ? workStartTime : start.TimeOfDay) : workStartTime;
    }

    private static TimeSpan GetEndTimeForDay(DateTime start, DateTime end, TimeSpan workEndTime, DateTime day)
    {
        return day == end.Date ? (end.TimeOfDay < workEndTime ? end.TimeOfDay : workEndTime) : workEndTime;
    }

    private static double GetHoursInTimePeriod(TimeSpan start, TimeSpan end)
    {
        return (end - start).TotalHours;
    }


问:
How to configure log4j to only keep log files for the last seven days?
I have the following logging problem with several Java applications using log4j for logging:

I want log files to be rotated daily, like

```<code>log.2010-09-10
log.2010-09-09
log.2010-09-08
log.2010-09-07
log.2010-09-06
log.2010-09-05
log.2010-09-04
</code>```

But for data security reasons we are not allowed to keep log files for longer than seven days at my company. So the generation of the next next log file log.2010-09-11 should trigger the deletion of log.2010-09-04. Is it possible to configure such a behaviour with log4j? If not, do you know another elegant solution for this kind of logging problem?

答:
Inspite of starting a chrone job, for the task, we can use log4j2.properties file in config folder of logstash. Have a look at the link below, this will be helpful.

https://github.com/elastic/logstash/issues/7482

Body:
I have the following logging problem with several Java applications using log4j for logging:

I want log files to be rotated daily, like

log.2010-09-10
log.2010-09-09
log.2010-09-08
log.2010-09-07
log.2010-09-06
log.2010-09-05
log.2010-09-04

But for data security reasons we are not allowed to keep log files for longer than seven days at my company. So the generation of the next next log file log.2010-09-11 should trigger the deletion of log.2010-09-04. Is it possible to configure such a behaviour with log4j? If not, do you know another elegant solution for this kind of logging problem?


问:
Get spinner selected item inside RecyclerView
I have added Spinner inside RecyclerView , when i am trying to get spinner selected item data, its getting another/wrong position data, any one suggest me to get correct selected item and position from Spinner onItemSelected

Here is my code

```<code>@Override
public void onBindViewHolder(final QuestionHolder holder, final int position) {
        if (position % 2 == 1)
            holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
        adapter = new ArrayAdapter<Option>(binding.getRoot().getContext(),
                        R.layout.item_spinner, questionList.get(position).getOptions());
        adapter.setDropDownViewResource(R.layout.item_spinner);
        binding.optionSpinner.setAdapter(adapter);

        binding.serialNo.setText((position + 1) + ".");
        binding.setQuestion(questionList.get(position));
        binding.executePendingBindings();
        binding.optionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(holder.itemView.getContext(), position+" : "+binding.optionSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                spinnerData.setSelectedData(position, binding.optionSpinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
</code>```

答:
I think you have to try this</p>

```<code>  showSpinnerList.setOnItemSelectedListener(new
         AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int
               position, long id) {
                // On selecting a spinner item

                String item = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // todo for nothing selected
            }
        });
</code>```

Body:
I have added Spinner inside RecyclerView , when i am trying to get spinner selected item data, its getting another/wrong position data, any one suggest me to get correct selected item and position from Spinner onItemSelected

Here is my code

@Override
public void onBindViewHolder(final QuestionHolder holder, final int position) {
        if (position % 2 == 1)
            holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
        adapter = new ArrayAdapter<Option>(binding.getRoot().getContext(),
                        R.layout.item_spinner, questionList.get(position).getOptions());
        adapter.setDropDownViewResource(R.layout.item_spinner);
        binding.optionSpinner.setAdapter(adapter);

        binding.serialNo.setText((position + 1) + ".");
        binding.setQuestion(questionList.get(position));
        binding.executePendingBindings();
        binding.optionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(holder.itemView.getContext(), position+" : "+binding.optionSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                spinnerData.setSelectedData(position, binding.optionSpinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

Body:
I think you have to try this

  showSpinnerList.setOnItemSelectedListener(new
         AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int
               position, long id) {
                // On selecting a spinner item

                String item = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // todo for nothing selected
            }
        });


问:
PL/SQL Program that uses a Cursor to Rank
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment. </p>

```<code>CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;
</code>```

<p>I'm trying to get an output like this: </p>

```<code>Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL
</code>```

答:
You could consider using windowed functions:

```<code>SELECT s1.snum, s1.sname, s1.gpa, s1.Major,RANK() OVER(ORDER BY s1.gpa) AS r
FROM students s1;
</code>```

From RANK doc:

RANK calculates the rank of a value in a group of values. The return type is NUMBER.

Body:
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment.

CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;

I'm trying to get an output like this:

Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL

Body:
You could consider using windowed functions:

SELECT s1.snum, s1.sname, s1.gpa, s1.Major,RANK() OVER(ORDER BY s1.gpa) AS r
FROM students s1;

From RANK doc:

RANK calculates the rank of a value in a group of values. The return type is NUMBER.


问:
Filtered HTML list: making li elements initially invisible
This is the HTML:

```<code><input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

<ul id="myUL">
    <li>Bucuresti</li>
    <li>Cluj</li>
    <li>Timisoara</li>
</ul>
</code>```

And this is my scipt:

```<code>var value = $('#myInput').val();
if(value.length == 0) {
    $("#myUL li").style.display = "none";
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
        if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
           $(value).show();
        } else {
            $(value).hide();
        }
    });
});
</code>```

I want to filter the elements of the ul based on the text in the input.

Everything is working perfectly without that initial if statement, but I want all the li elements to initially have diplay:none. Adding that if deactivates the whole filtering. Any possible solution for how I could do that?

Any help would be appreciated.

答:
Try $('#myUL li').hide() like the following:

var value = $('#myInput').val();
if(value.length == 0) {
  $('#myUL li').hide();
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
      if(searchString == ''){$('#myUL li').hide(); }
      else if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
       $(value).show();
      } else {
        $(value).hide();
      }
  });
});

function myFunction(){}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

<ul id="myUL">
    <li>Bucuresti</li>
    <li>Cluj</li>
    <li>Timisoara</li>
</ul></code>```

Body:
This is the HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

Bucuresti

Cluj

Timisoara

And this is my scipt:

var value = $('#myInput').val();
if(value.length == 0) {
    $("#myUL li").style.display = "none";
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
        if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
           $(value).show();
        } else {
            $(value).hide();
        }
    });
});

I want to filter the elements of the ul based on the text in the input.

Everything is working perfectly without that initial if statement, but I want all the li elements to initially have diplay:none. Adding that if deactivates the whole filtering. Any possible solution for how I could do that?

Any help would be appreciated.

Body:
Try $('#myUL li').hide() like the following:

var value = $('#myInput').val();
if(value.length == 0) {
  $('#myUL li').hide();
}

$('#myInput').bind('keyup', function() {
    var searchString = $(this).val();
    $("ul li").each(function(index, value) {
        currentName = $(value).text()
      if(searchString == ''){$('#myUL li').hide(); }
      else if( currentName.toUpperCase().indexOf(searchString.toUpperCase()) > -1) {
       $(value).show();
      } else {
        $(value).hide();
      }
  });
});

function myFunction(){}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="orasul tau..">

<ul id="myUL">
    <li>Bucuresti</li>
    <li>Cluj</li>
    <li>Timisoara</li>
</ul>


问:
Centering the navbar links
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

答:
Try this code for :

```<code> .navbar-nav {
    width: 100%;
    text-align: center;
    > li {
      float: none;
      display: inline-block;
    }
  }
</code>```

for center align the whole inner link

Title: Centering the navbar links

Body:
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Home

About

Education

Contact

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

Body:
Try this code for :

 .navbar-nav {
    width: 100%;
    text-align: center;
    > li {
      float: none;
      display: inline-block;
    }
  }

for center align the whole inner link


问:
WCF Diagnostics "logEntireMessage" left on in deployed environment
I have a WCF service exposed (.net 3.5).

I am using diagnostics to log messages and activities when required. Here is my code:

The following defines which messages to log:

```<code><system.serviceModel>
    <diagnostics>
      <messageLogging
         logEntireMessage="true"
         logMalformedMessages="true"
         logMessagesAtServiceLevel="true"
         logMessagesAtTransportLevel="true"
         maxMessagesToLog="3000000"
         maxSizeOfMessageToLog="20000000"/>
    </diagnostics>
</system.serviceModel>
</code>```

The following specifies where to log to:

```<code><system.diagnostics>
    <trace autoflush="true" indentsize="4" />
    <sources>
      <!-- Source for tracing WCF activities. -->
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing">
        <listeners>
          <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="ActivityLog.svclog" />
        </listeners>
      </source>

      <!-- Source for tracing WCF messages (content). -->
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messageListner" type="System.Diagnostics.XmlWriterTraceListener"
            initializeData="MessageLog.svclog" />
        </listeners>
      </source>

    </sources>
</system.diagnostics>
</code>```

When I comment the sources out, it does not log to the files (obviously).

My question is can I leave the diagnostics element in there or should I comment it out (will it affect performance/anything when deployed)?

答: I don't think it will make a difference as it needs to build the listeners before any diagnostics takes place.</p>

Body:
I have a WCF service exposed (.net 3.5).

I am using diagnostics to log messages and activities when required. Here is my code:

The following defines which messages to log:

<system.serviceModel>
    <diagnostics>
      <messageLogging
         logEntireMessage="true"
         logMalformedMessages="true"
         logMessagesAtServiceLevel="true"
         logMessagesAtTransportLevel="true"
         maxMessagesToLog="3000000"
         maxSizeOfMessageToLog="20000000"/>
    </diagnostics>
</system.serviceModel>

The following specifies where to log to:

<system.diagnostics>
    <trace autoflush="true" indentsize="4" />
    <sources>

      <source name="System.ServiceModel" switchValue="Information, ActivityTracing">
        <listeners>
          <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="ActivityLog.svclog" />
        </listeners>
      </source>

      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messageListner" type="System.Diagnostics.XmlWriterTraceListener"
            initializeData="MessageLog.svclog" />
        </listeners>
      </source>

    </sources>
</system.diagnostics>

When I comment the sources out, it does not log to the files (obviously).

My question is can I leave the diagnostics element in there or should I comment it out (will it affect performance/anything when deployed)?


问:
What is the Vuex "context" object?
I am trying to get better understanding of what the "context" object is in Vuex.

The context object is referred to numerous times in the Vuex documentation.  For example, in https://vuex.vuejs.org/en/actions.html, we have:

Action handlers receive a context object which exposes the same set of
  methods/properties on the store instance, so you can call
  context.commit to commit a mutation...

I understand how to use it, and also that we can use destructuring if we only want to use the "commit" from the context object, but was hoping for a little more depth, just so I can better understand what is going on.

As a start, I found a couple ~8.5 year old posts on the "context object" as a  pattern:
what is context object design pattern? and
Can you explain the Context design pattern?

However, specifically to Vuex, I'd love a better understanding of:

What is the context object / what is its purpose?

What are all the properties/methods that it is making available to use in Vuex?

Thank you!

答:
As a start, I found a couple ~8.5 year old posts on the "context object" as a pattern ...

I think you're reading into it too much.

I don't think the Vuex docs is referring to some specific kind of "context object" that is known and defined elsewhere, they just mean that the object that is passed to action handlers (and in other situations as described in the docs) is a custom object which they refer to as a "context" object by their own definition.

The reason why they provide this object is because it contains properties that are specific to the module for that particular action handler.

Title: What is the Vuex "context" object?


问:
HTML Input - Remove leading Character
I have an HTML form showing a table where the user can scan a product barcode to enter the serial number into a text input field like this:

```<code><td id="9856623"><input type="text" class="form-control serialNumber" placeholder="Serial #" name="serialNumber" autocomplete="off" value=""></td>
</code>```

When the cursor is in the input field the user scans a barcode to insert the barcode value into this input field, which then triggers a script that runs in the background to do a database update via PHP. We need to check if the first characters in the serial number that is scanned is an 'S' and if so then remove this. We handle this in PHP like this:

```<code>$serialNumber = 'STRQWEF412421';

$serialFirstChar = substr( $serialNumber , 0, 1);

if ($serialFirstChar == 'S') {
    $serialNumber = substr($serialNumber, 1);
}
</code>```

but I now need to do the same in Javascript to update the entered serial number in the text input field so also remove the leading 'S' character if present. Here's the current script that runs when the Serial Number is entered:

```<code>$(document).ready(function() {
  $(".form-control.serialNumber").change(function() {
    //$("input[type='text']").change(function(){
    //alert( "Handler for .change() called." );
    var parent = $(this).parents('tr');
    var recid = $(this).closest('td').attr('id');
    var serialNumber = $(this).val();
    // Create a reference to $(this) here:
    $this = $(this);
    $.post('updateAsset.php', {
      type: 'updateDatabase',
      recid: recid,
      serialNumber: serialNumber
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Serial Number - ' + ajaxError + '. Please contact the Helpdesk';
        $this.closest('td').addClass("has-error");
        //display AJAX error details
        $("#serialNumberErrorMessage").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        var dateReceived = (data.dateReceived);
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
        $this.closest('tr').children('.DateReceived').html(dateReceived);
        // if you want to show a success alert enable the following
        // $("#ajaxAlert").addClass("alert alert-success").html(data.text);
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Serial Number - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Helpdesk';
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberErrorMessage").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});
</code>```

```

I have no idea how to go about this at this point, and whether I can update my existing script to also update the entered serial number and remove any leading 'S' character?

答:
You can use string#charAt() and string#substring(), like this:

var serialNumber = 'STRQWEF412421';
if (serialNumber.charAt(0) === 'S') {
    serialNumber = serialNumber.substr(1);
}
console.log(serialNumber);```
</div>
</div>
</p>

<p><strong>Edit:</strong></p>

<p>So to apply this code for your <code>input</code> you need to add it in the <code>change</code> event handler like this:</p>

```$(".form-control.serialNumber").change(function() {

  var serialNumber = $(this).val();
  if (serialNumber.charAt(0) === 'S') {
    $(this).val(serialNumber.substr(1));
  }
  //Rest of the code
});
```

Title: HTML Input - Remove leading Character

Body:
I have an HTML form showing a table where the user can scan a product barcode to enter the serial number into a text input field like this:

<input type="text" class="form-control serialNumber" placeholder="Serial #" name="serialNumber" autocomplete="off" value="">

When the cursor is in the input field the user scans a barcode to insert the barcode value into this input field, which then triggers a script that runs in the background to do a database update via PHP. We need to check if the first characters in the serial number that is scanned is an 'S' and if so then remove this. We handle this in PHP like this:

$serialNumber = 'STRQWEF412421';

$serialFirstChar = substr( $serialNumber , 0, 1);

if ($serialFirstChar == 'S') {
    $serialNumber = substr($serialNumber, 1);
}

but I now need to do the same in Javascript to update the entered serial number in the text input field so also remove the leading 'S' character if present. Here's the current script that runs when the Serial Number is entered:

$(document).ready(function() {
  $(".form-control.serialNumber").change(function() {
    //$("input[type='text']").change(function(){
    //alert( "Handler for .change() called." );
    var parent = $(this).parents('tr');
    var recid = $(this).closest('td').attr('id');
    var serialNumber = $(this).val();
    // Create a reference to $(this) here:
    $this = $(this);
    $.post('updateAsset.php', {
      type: 'updateDatabase',
      recid: recid,
      serialNumber: serialNumber
    }, function(data) {
      data = JSON.parse(data);
      if (data.error) {
        var ajaxError = (data.text);
        var errorAlert = 'There was an error updating the Serial Number - ' + ajaxError + '. Please contact the Helpdesk';
        $this.closest('td').addClass("has-error");
        //display AJAX error details
        $("#serialNumberErrorMessage").html(errorAlert);
        $("#serialNumberError").show();
        return; // stop executing this function any further
      } else {
        var dateReceived = (data.dateReceived);
        $this.closest('td').addClass("has-success")
        $this.closest('td').removeClass("has-error");
        $this.closest('tr').children('.DateReceived').html(dateReceived);
        // if you want to show a success alert enable the following
        // $("#ajaxAlert").addClass("alert alert-success").html(data.text);
      }

    }).fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an error updating the Serial Number - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Helpdesk';
      $this.closest('td').addClass("has-error");
      //display AJAX error details
      $("#serialNumberErrorMessage").html(ajaxError);
      $("#serialNumberError").show();
    });
  });
});

I have no idea how to go about this at this point, and whether I can update my existing script to also update the entered serial number and remove any leading 'S' character?

Body:
You can use string#charAt() and string#substring(), like this:

var serialNumber = 'STRQWEF412421';
if (serialNumber.charAt(0) === 'S') {
    serialNumber = serialNumber.substr(1);
}
console.log(serialNumber);

Edit:

So to apply this code for your input you need to add it in the change event handler like this:

$(".form-control.serialNumber").change(function() {

  var serialNumber = $(this).val();
  if (serialNumber.charAt(0) === 'S') {
    $(this).val(serialNumber.substr(1));
  }
  //Rest of the code
});


答:
You can use Javascript's startsWith. If the first charactes is S, remove it from the string:

// for debugging
serialNumber = 'STRQWEF412421';

if (serialNumber.startsWith('S'))
    serialNumber = serialNumber.substring(1);

console.log(serialNumber);```

Title: HTML Input - Remove leading Character


问:
Identity Framework UserLockoutEnabledByDefault works with oAuth Token
I'm trying to implement lockout feature in Identity Framework in my webapi. I'm using oAuth token https://myapi.com/Token
When a user authentication fails when logging in and getting a Token, it doesn't seem to affect the AccessFailedCount field in the database.  Googled and found that I need to use the SigninManager for the feature to work. Is there a way to implement it when issuing a Token?

Thanks for your help

答:
You need to explicitly call 2.AccessFailedAsync(1)" rel="nofollow noreferrer">AccessFailedAsync on the UserManager:

```<code>if (userManager.SupportsUserLockout)
    await userManager.AccessFailedAsync(user);
</code>```

For example, in an OpenIdConnectServerProvider.HandleTokenRequest context, this may look like:

```<code>var userManager =
    context.HttpContext.RequestServices.GetRequiredService<UserManager<User>>();

var user = await userManager.FindByNameAsync(context.Request.Username);

if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user))
{
    context.Reject(
        error: OpenIdConnectConstants.Errors.InvalidGrant,
        description: "User locked out due to too many failed attempts. Try again later.");

    return;
}

if (!await userManager.CheckPasswordAsync(user, context.Request.Password))
{
    // If lockout is supported, increment access failed count
    if (userManager.SupportsUserLockout)
        await userManager.AccessFailedAsync(user);

    context.Reject(
        error: OpenIdConnectConstants.Errors.InvalidGrant,
        description: "The username or password was invalid");

    return;
}
</code>```

Body:
You need to explicitly call AccessFailedAsync on the UserManager:

if (userManager.SupportsUserLockout)
    await userManager.AccessFailedAsync(user);

For example, in an OpenIdConnectServerProvider.HandleTokenRequest context, this may look like:

var userManager =
    context.HttpContext.RequestServices.GetRequiredService<UserManager<User>>();

var user = await userManager.FindByNameAsync(context.Request.Username);

if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user))
{
    context.Reject(
        error: OpenIdConnectConstants.Errors.InvalidGrant,
        description: "User locked out due to too many failed attempts. Try again later.");

    return;
}

if (!await userManager.CheckPasswordAsync(user, context.Request.Password))
{
    // If lockout is supported, increment access failed count
    if (userManager.SupportsUserLockout)
        await userManager.AccessFailedAsync(user);

    context.Reject(
        error: OpenIdConnectConstants.Errors.InvalidGrant,
        description: "The username or password was invalid");

    return;
}


问:
remove specific lines of file using bash
I have to file suppost 1.txt and 2.txt
1.txt has a number in each line indicate the itemID. for example

```<code>43
345
65
</code>```

the second file is csv and has the following pattern
userID,itemID,time

I want to remove from second file all lines which their itemID is in the first file
for this purpose I do the following

```<code>#!/bin/bash

while IFS= read -r var
do
 paste -sd '|' | xargs -I{} grep -v -E {} 2.txt
done < "1.txt"
</code>```

I read the first file and create a regular expression, but don't know the argument of egrep to get the second filed(itemID)

答:
With awk

```<code>awk -F "," 'FNR==NR{a[$0]=1;next} a[$2]!=1{print}' 1.txt 2.txt
</code>```

a[$0] = 1 records item id that exists in 1.txt into an array a

a[$2] != 1 prints out lines from 2.txt that does not have the item id in array a

Body:
I have to file suppost 1.txt and 2.txt
1.txt has a number in each line indicate the itemID. for example

43
345
65

the second file is csv and has the following pattern
userID,itemID,time

I want to remove from second file all lines which their itemID is in the first file
for this purpose I do the following

#!/bin/bash

while IFS= read -r var
do
 paste -sd '|' | xargs -I{} grep -v -E {} 2.txt
done < "1.txt"

I read the first file and create a regular expression, but don't know the argument of egrep to get the second filed(itemID)

Body:
With awk

awk -F "," 'FNR==NR{a[$0]=1;next} a[$2]!=1{print}' 1.txt 2.txt

a[$0] = 1 records item id that exists in 1.txt into an array a

a[$2] != 1 prints out lines from 2.txt that does not have the item id in array a


问:
Create a template for general use
I have created a RadCartesianChart to plot a bar series. The xaml code is:

```<code><Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <telerik:RadCartesianChart x:Name="chart" Width="400" Height="300">
        <telerik:RadCartesianChart.VerticalAxis>
            <telerik:LinearAxis/>
        </telerik:RadCartesianChart.VerticalAxis>
        <telerik:RadCartesianChart.HorizontalAxis>
            <telerik:CategoricalAxis/>
        </telerik:RadCartesianChart.HorizontalAxis>
        <telerik:RadCartesianChart.Series>
            <telerik:BarSeries CategoryBinding="Category" ValueBinding="Value" ItemsSource="{Binding}">
                <telerik:BarSeries.DefaultVisualStyle>
                    <Style TargetType="Border">
                        <Setter Property="Background" Value="{Binding DataItem.Color}" />
                    </Style>
                </telerik:BarSeries.DefaultVisualStyle>
            </telerik:BarSeries>
        </telerik:RadCartesianChart.Series>
    </telerik:RadCartesianChart>
</Grid>
</code>```

And the code behind

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = GetData(12);
        }

        public static List<ChartData> GetData(int dataSize)
        {
            Random rnd = new Random();
            var result = new List<ChartData>();

            for (int i = 0; i < dataSize; i++)
            {
                result.Add(new ChartData()
                {
                    Category = i,
                    Value = rnd.Next(1, 100),
                    Color = new SolidColorBrush(
                        Color.FromArgb(255, (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256)))
                });
            }

            return result;
        }
    }

    public class ChartData : INotifyPropertyChanged
    {
        private int _category;
        public int Category
        {
            get { return this._category; }
            set { this._category = value;
this.OnPropertyChanged("Category"); }
        }

        private double _value;
        public double Value
        {
            get { return this._value; }
            set { this._value = value; this.OnPropertyChanged("Value"); }
        }

        private Brush _color;
        public Brush Color
        {
            get { return this._color; }
            set { this._color = value; this.OnPropertyChanged("Color"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</code>```

My question is how to use the user control as a template? The reason is that we have very similar cases to plot. Do we need to create many user control for each individual controls or we can create a template to reference it?

I am not strong on contentpresenter or ContentControl or ControlTemplate something like.

答:
You can use DataTemplate and define multiple data templates based on your requirement and switch the ContentTemplate of ContentControl based on Triggers.

Here let's say we have a XAML file with a ContentControl.

```<code><UserControl.Resources>
    <DataTemplate x:Key="DataTemplate1">
        <!-- your code for control goes here-->
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate2">
        <!-- your code for control goes here-->
    </DataTemplate>
    <Style x:Key="ContentControlStyle" TargetType="{x:Type ContentControl}">
      <!-- Default content for content control would be DataTemplate1 -->
      <Setter Property="ContentTemplate" Value="{StaticResource DataTemplate1}"/>
      <Style.Triggers>
         <DataTrigger Binding="{Binding SomePropertyInViewModel}" Value="YourValue">
            <!-- If SomePropertyInViewModel == YourValue in ViewModel DataTemplate2 will be applied.-->
            <Setter Property="ContentTemplate" Value="{StaticResource DataTemplate2}"/>
         </DataTrigger>
      </Style.Triggers>
    </Style>
</UserControl.Resources>
<ContentControl Style="{StaticResource ContentControlStyle}"/>
</code>```

Let me know for any further questions.

Title: Create a template for general use

Body:
I have created a RadCartesianChart to plot a bar series. The xaml code is:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <telerik:RadCartesianChart x:Name="chart" Width="400" Height="300">
        <telerik:RadCartesianChart.VerticalAxis>
            <telerik:LinearAxis/>
        </telerik:RadCartesianChart.VerticalAxis>
        <telerik:RadCartesianChart.HorizontalAxis>
            <telerik:CategoricalAxis/>
        </telerik:RadCartesianChart.HorizontalAxis>
        <telerik:RadCartesianChart.Series>
            <telerik:BarSeries CategoryBinding="Category" ValueBinding="Value" ItemsSource="{Binding}">
                <telerik:BarSeries.DefaultVisualStyle>

                </telerik:BarSeries.DefaultVisualStyle>
            </telerik:BarSeries>
        </telerik:RadCartesianChart.Series>
    </telerik:RadCartesianChart>
</Grid>

And the code behind

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = GetData(12);
        }

        public static List<ChartData> GetData(int dataSize)
        {
            Random rnd = new Random();
            var result = new List<ChartData>();

            for (int i = 0; i < dataSize; i++)
            {
                result.Add(new ChartData()
                {
                    Category = i,
                    Value = rnd.Next(1, 100),
                    Color = new SolidColorBrush(
                        Color.FromArgb(255, (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256)))
                });
            }

            return result;
        }
    }

    public class ChartData : INotifyPropertyChanged
    {
        private int _category;
        public int Category
        {
            get { return this._category; }
            set { this._category = value;
this.OnPropertyChanged("Category"); }
        }

        private double _value;
        public double Value
        {
            get { return this._value; }
            set { this._value = value; this.OnPropertyChanged("Value"); }
        }

        private Brush _color;
        public Brush Color
        {
            get { return this._color; }
            set { this._color = value; this.OnPropertyChanged("Color"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

My question is how to use the user control as a template? The reason is that we have very similar cases to plot. Do we need to create many user control for each individual controls or we can create a template to reference it?

I am not strong on contentpresenter or ContentControl or ControlTemplate something like.

Body:
You can use DataTemplate and define multiple data templates based on your requirement and switch the ContentTemplate of ContentControl based on Triggers.

Here let's say we have a XAML file with a ContentControl.

<UserControl.Resources>
    <DataTemplate x:Key="DataTemplate1">
        <!-- your code for control goes here-->
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate2">
        <!-- your code for control goes here-->
    </DataTemplate>
    <Style x:Key="ContentControlStyle" TargetType="{x:Type ContentControl}">
      <!-- Default content for content control would be DataTemplate1 -->
      <Setter Property="ContentTemplate" Value="{StaticResource DataTemplate1}"/>
      <Style.Triggers>
         <DataTrigger Binding="{Binding SomePropertyInViewModel}" Value="YourValue">
            <!-- If SomePropertyInViewModel == YourValue in ViewModel DataTemplate2 will be applied.-->
            <Setter Property="ContentTemplate" Value="{StaticResource DataTemplate2}"/>
         </DataTrigger>
      </Style.Triggers>
    </Style>
</UserControl.Resources>
<ContentControl Style="{StaticResource ContentControlStyle}"/>

Let me know for any further questions.


问:
How do I create arrays within an array in C without a predefined size?
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

```<code>{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }
</code>```

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?

答:
Use pointer instead of array and allocates the memory of that pointer dynamically using malloc or calloc function.

Like this:

```<code>int *a;

a = malloc((sizeof(int)*noOfItems);
</code>```

Body:
I would like to create arrays within an array in C without a pre-defined number of characters or input in the array.
The following is my code:

{
    int noOfStudents,noOfItems;
    int *grades;
    int i;
    char a[];
    printf("Please enter number of students\n");
    scanf("%d", &noOfStudents);
    printf("Please enter number of items\n");
    scanf("%d", &noOfItems);

    for (i = 0; i < noOfStudents; i++)
    {
        a[i] = (int *)malloc((sizeof(int))*noOfItems);
    }

I've been thrown an error

c(2133): 'a': unknown size

How do I successfully create arrays within an array by means of malloc?

Body:
Use pointer instead of array and allocates the memory of that pointer dynamically using malloc or calloc function.

Like this:

int *a;

a = malloc((sizeof(int)*noOfItems);


问:
ChartJS: Translate Month Time Axis to Dutch
I'm having difficulties in finding out how to change the language for the time axis. I'm using 'MMM' for month so I get a short description of the month but I can't seem to get it to Dutch. What am I doing wrong?

So instead of May there should be Mei.

This is the scrip I'm using:

```<code>moment.locale('nl');

var lvlC = document.getElementById("levelChart").getContext("2d");
var levelChart = new Chart(lvlC, {
  type: "line",
  data: {
    datasets: [
      {
        label: "Levels",
        data: [
          {
            x: '2017-01-01',
            y: 10
          },
          {
            x: '2017-02-15',
            y: 20
          },
          {
            x: '2017-06-01',
            y: 30
          },
          {
            x: '2018-10-01',
            y: 40
          }
        ],
        backgroundColor: ["rgba(0, 197, 161, 0)"],
        borderColor: ["rgba(0,197,161,1)"],
        borderWidth: 1,
        steppedLine: true
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    elements: {
      point: {
        radius: 0
      }
    },
    scales: {
      xAxes: [
        {
          type: "time",
          distribution: 'series',
          time: {
            unit: "month",
            displayFormats: {
              month: "MMM"
            },
          },
          scaleLabel: {
            display: false,
            labelString: "Date"
          },
          gridLines: {
            drawBorder: false
          },
          ticks: {
        autoSkip: true,
        maxTicksLimit: 6
    }
        }
      ],
      yAxes: [
        {
          ticks: {
            display: false,
            beginAtZero: true
          },
          gridLines: {
            drawBorder: false,
            display: false
          }
        }
      ]
    }
  }
});
</code>```

I'm working on this on codepen so all the information can be found here:
https://codepen.io/anon/pen/JObzZZ?editors=0010

答:
You can use

```<code>ticks: {
    callback: function(value, index){
        return moment.monthsShort(index % 12, "MMM");
    }
}
</code>```

as the ticks callback option.

Body:
I'm having difficulties in finding out how to change the language for the time axis. I'm using 'MMM' for month so I get a short description of the month but I can't seem to get it to Dutch. What am I doing wrong?

So instead of May there should be Mei.

This is the scrip I'm using:

moment.locale('nl');

var lvlC = document.getElementById("levelChart").getContext("2d");
var levelChart = new Chart(lvlC, {
  type: "line",
  data: {
    datasets: [
      {
        label: "Levels",
        data: [
          {
            x: '2017-01-01',
            y: 10
          },
          {
            x: '2017-02-15',
            y: 20
          },
          {
            x: '2017-06-01',
            y: 30
          },
          {
            x: '2018-10-01',
            y: 40
          }
        ],
        backgroundColor: ["rgba(0, 197, 161, 0)"],
        borderColor: ["rgba(0,197,161,1)"],
        borderWidth: 1,
        steppedLine: true
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    elements: {
      point: {
        radius: 0
      }
    },
    scales: {
      xAxes: [
        {
          type: "time",
          distribution: 'series',
          time: {
            unit: "month",
            displayFormats: {
              month: "MMM"
            },
          },
          scaleLabel: {
            display: false,
            labelString: "Date"
          },
          gridLines: {
            drawBorder: false
          },
          ticks: {
        autoSkip: true,
        maxTicksLimit: 6
    }
        }
      ],
      yAxes: [
        {
          ticks: {
            display: false,
            beginAtZero: true
          },
          gridLines: {
            drawBorder: false,
            display: false
          }
        }
      ]
    }
  }
});

I'm working on this on codepen so all the information can be found here:
https://codepen.io/anon/pen/JObzZZ?editors=0010

Body:
You can use

ticks: {
    callback: function(value, index){
        return moment.monthsShort(index % 12, "MMM");
    }
}

as the ticks callback option.


问:
Why is this showing driver is not defined
Im trying to get this part of my script to upload an image from folder " zip code pics" which has subfolders named by optional zip codes

When i get to the image upload page it gives me the error driver is not defined..

What am i missing here ?

```<code>def picturetime():
    zipcode = get_zipcode()
    while True:
          try:
            pics = []
            for each in os.listdir(os.path.join(os.curdir, 'ZIP CODE PICS', zipcode[0])):
                name = os.path.splitext(each)
                picture_name = os.path.join(os.curdir, 'ZIP CODE PICS',zipcode[0] , each)
                picture_name = os.path.abspath(picture_name)
                pics.append(picture_name)
            if pics:
                picture_name = random.choice(pics)
                driver.find_element_by_id('plupload').send_keys(picture_name)
                print('[zip code image] clicking on save_link after picture')
                sleep(10)
</code>```

答:
```<code>def picturetime():
    global drive
    zipcode = get_zipcode()
.......
.......
</code>```

Body:
Im trying to get this part of my script to upload an image from folder " zip code pics" which has subfolders named by optional zip codes

When i get to the image upload page it gives me the error driver is not defined..

What am i missing here ?

def picturetime():
    zipcode = get_zipcode()
    while True:
          try:
            pics = []
            for each in os.listdir(os.path.join(os.curdir, 'ZIP CODE PICS', zipcode[0])):
                name = os.path.splitext(each)
                picture_name = os.path.join(os.curdir, 'ZIP CODE PICS',zipcode[0] , each)
                picture_name = os.path.abspath(picture_name)
                pics.append(picture_name)
            if pics:
                picture_name = random.choice(pics)
                driver.find_element_by_id('plupload').send_keys(picture_name)
                print('[zip code image] clicking on save_link after picture')
                sleep(10)


问:
How to use findDrawableByLayerId in android?
I want to use setBounds() to a specific item in layer-list, which is used as a background for a button. But I am not able to get the LayerDrawable object to call findDrawableByLayerId().

Can anybody help to solve this ?

答: if you want to use findDrawableByLayerId(int id), you should do setId(int index, int id) at first, if not the id is always -1.


问:
django rest framework: prefetch an initial data in serializer
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer.

However, the problem come when I want to use the serializer to create my model
for example:

```<code>class CompanySerializer(serializer.serializers):
    employee_set = serializers.JSONField()
    class Meta:
        model = Company
        fields = ('id', 'employee_set')
    def create(self, validated_data):
        employee_set = validated_data.pop('employee_set')
        for employee in employee_set:
            serializer = EmployeeSerializer(data=employee)
            serializer.is_valid(raise_exception=True)
            serializer.save()

class EmployeeSerializer(serializer.serializers):
    card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all())
    class Meta:
        model = Employee
        fields = ('id', 'name', 'card')
    def validate(self, obj):
        if card.employee_set.all().count() > 3:
            raise serializers.ValidationError({'_error': 'invalid})
        return data
</code>```

For example, I want to create a company with multiple employee like:

request.POST:

```<code>{
    employee_set: [
        { name: 'tim', card: 1 },
        { name: 'bob', card: 1 },
        { name: 'jimmy', card: 2},
    ]
}
</code>```

then I can use CompanySerializer(request.POST), right?

However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related?

thanks

答:
You can send extra information into your serializer, via context

```<code># use select_related or prefetech_related to get this value
card_counters = {'card_id1': 1, 'card_id2': 3, ...}

for employee in employee_set:
    serializer = EmployeeSerializer(
        data=employee,
        context={'card_counter': card_counters.get(employee['card_id'], 0)}
    )
    ...
</code>```

And then use it when doing the validation:

```<code>def validate(self, obj):
    if self.context['card_counter'] > 3:
        raise serializers.ValidationError({'_error': 'invalid})
    return data
</code>```

Body:
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer.

However, the problem come when I want to use the serializer to create my model
for example:

class CompanySerializer(serializer.serializers):
    employee_set = serializers.JSONField()
    class Meta:
        model = Company
        fields = ('id', 'employee_set')
    def create(self, validated_data):
        employee_set = validated_data.pop('employee_set')
        for employee in employee_set:
            serializer = EmployeeSerializer(data=employee)
            serializer.is_valid(raise_exception=True)
            serializer.save()

class EmployeeSerializer(serializer.serializers):
    card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all())
    class Meta:
        model = Employee
        fields = ('id', 'name', 'card')
    def validate(self, obj):
        if card.employee_set.all().count() > 3:
            raise serializers.ValidationError({'_error': 'invalid})
        return data

For example, I want to create a company with multiple employee like:

request.POST:

{
    employee_set: [
        { name: 'tim', card: 1 },
        { name: 'bob', card: 1 },
        { name: 'jimmy', card: 2},
    ]
}

then I can use CompanySerializer(request.POST), right?

However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related?

thanks

Body:
You can send extra information into your serializer, via context

# use select_related or prefetech_related to get this value
card_counters = {'card_id1': 1, 'card_id2': 3, ...}

for employee in employee_set:
    serializer = EmployeeSerializer(
        data=employee,
        context={'card_counter': card_counters.get(employee['card_id'], 0)}
    )
    ...

And then use it when doing the validation:

def validate(self, obj):
    if self.context['card_counter'] > 3:
        raise serializers.ValidationError({'_error': 'invalid})
    return data


问:
Port a Ruby/Rails application to PHP 5
I have a very large Ruby on Rails application that I would like to port to PHP 5.2 or maybe PHP 5.3 (if 5.3 ever gets released).

I've been looking for a some way of automatically converting the simple stuff like simple classes and the ERB templates. I would expect that I'd have to do the more complicated stuff myself in cases where the languages are just too dissimilar.

Can anyone suggest an approach for doing this? Or a script that can automate some of it?

EDIT:

There is a business case for doing this. Whether it is a sound business case is another issue which I don't care to discuss here. We have a framework that is similar enough to Rails - the real issue is conversion from Ruby to PHP rather than Rails to PHP. I'm not really looking for something that will magically do all the work, just something simple that will give a headstart. Even if all it did was change:

```<code>def somemethod somearg
  some.ruby.code
end
</code>```

to:

```<code>public function somemethod($somearg) {
  // some.ruby.code
}
</code>```

and left the innards as ruby in php comments that would still make the job easier.

Ideally there would be something out there that does this or similar already. Otherwise I might have to the write tool myself.

答:
I completely agree with troelskn, this is a massive undertaking and I think that you'll have very little luck finding any form of automated process for porting the app.

Your best bet is finding a framework that is very similar in design and porting all the classes one by one.

The most tedious thing here will be where the database is involved. As far as I know, there is still no ORM solution for PHP that comes even close to Rails' ActiveRecord. You'll have to write a lot of the database code glue code yourself, and write all the model findersm, etc yourself. There may have been some improvements in this area since last time I checked, but PHP by nature has some problems with the ActiveRecord design pattern.

Again, I have to echo what I am sure a lot of people are thinking... why on Earth would you want to port an app from RoR to PHP. It sounds like an expensive thing to consider, both in time and money, with no clear advantage -- unless of course you've hit a wall with Ruby where it simply can not do something PHP can do. And I find this hard to believe.

OwnerDisplayName: Joel

Title: Port a Ruby/Rails application to PHP 5

Body:
I have a very large Ruby on Rails application that I would like to port to PHP 5.2 or maybe PHP 5.3 (if 5.3 ever gets released).

I've been looking for a some way of automatically converting the simple stuff like simple classes and the ERB templates. I would expect that I'd have to do the more complicated stuff myself in cases where the languages are just too dissimilar.

Can anyone suggest an approach for doing this? Or a script that can automate some of it?

EDIT:

There is a business case for doing this. Whether it is a sound business case is another issue which I don't care to discuss here. We have a framework that is similar enough to Rails - the real issue is conversion from Ruby to PHP rather than Rails to PHP. I'm not really looking for something that will magically do all the work, just something simple that will give a headstart. Even if all it did was change:

def somemethod somearg
  some.ruby.code
end

to:

public function somemethod($somearg) {
  // some.ruby.code
}

and left the innards as ruby in php comments that would still make the job easier.

Ideally there would be something out there that does this or similar already. Otherwise I might have to the write tool myself.

LastEditorDisplayName: Joel

OwnerDisplayName: bjeanes


问:
Ajax requests are aborted when they are sent too fast using the AjaxControlToolkit AutoCompleteExtender
I'm using the sample AutoCompleteExtender on the asp.net ajax site and am running into unwated behavior.  First let me just say the sample from the asp.net site is just too dang slow.  The 1 second CompletionInterval is too long for my taste.  So I lower it to 300 ms and now I get these request aborted messages.  Firebug shows me this:

POST http://localhost:49539/AutoComplete.asmx/GetCompletionList  Aborted

When the request is aborted, it obviously fails to retrieve the new list and thus not displaying the list of options which makes for a poor user experience.  If I type slowly, then the requests go through fine and I get the list of options.  It seems like I need every request to complete to give the user the best experience, but note sure...

Does anyone know what I need to do to always make the list pop up within 100-400 ms of typing a letter?

Note: It looks like IE and Chrome are not aborting the requests and thus I get a much better response time and the list pops up right away.  This may be a fluke and work differently on another computer - I don't know.

Also note: My GetCompletionList() function is very basic and only returns hard coded values (no DB requests), so it's very fast.

Here's the aspx

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>
        <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
            TargetControlID="TextBox1"
            ServicePath="~/AutoComplete.asmx"
            ServiceMethod="GetCompletionList"
            MinimumPrefixLength="1"
            CompletionInterval="200"
            CompletionSetCount="12"
            EnableCaching="true">
        </ajaxToolkit:AutoCompleteExtender>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

答:
Since nobody has answered my question for weeks now, I'll give it a shot.

I'm not 100% sure this was my problem, but I'm inclined to think it was caused by the web server that ships with visual studio.  I had a similar problem with another project but it was hosted on the local IIS server (change the project properties under the web tab) and the requests weren't getting aborted.

The reason I'm not 100% sure is the project was using a jquery library that was getting abort requests when using the visual studio built in web server, but not so when using the local IIS server.

Body:
I'm using the sample AutoCompleteExtender on the asp.net ajax site and am running into unwated behavior.  First let me just say the sample from the asp.net site is just too dang slow.  The 1 second CompletionInterval is too long for my taste.  So I lower it to 300 ms and now I get these request aborted messages.  Firebug shows me this:

POST http://localhost:49539/AutoComplete.asmx/GetCompletionList  Aborted

When the request is aborted, it obviously fails to retrieve the new list and thus not displaying the list of options which makes for a poor user experience.  If I type slowly, then the requests go through fine and I get the list of options.  It seems like I need every request to complete to give the user the best experience, but note sure...

Does anyone know what I need to do to always make the list pop up within 100-400 ms of typing a letter?

Note: It looks like IE and Chrome are not aborting the requests and thus I get a much better response time and the list pops up right away.  This may be a fluke and work differently on another computer - I don't know.

Also note: My GetCompletionList() function is very basic and only returns hard coded values (no DB requests), so it's very fast.

Here's the aspx

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>
        <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
            TargetControlID="TextBox1"
            ServicePath="~/AutoComplete.asmx"
            ServiceMethod="GetCompletionList"
            MinimumPrefixLength="1"
            CompletionInterval="200"
            CompletionSetCount="12"
            EnableCaching="true">
        </ajaxToolkit:AutoCompleteExtender>
    </ContentTemplate>
</asp:UpdatePanel>


问:
Nested Case Statement for multiple condition
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

```<code> COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )
</code>```

but not working.

Result after putting  ELSE NULL

答:
Try this, COALESCE is used for First Not NULL Value, if you give EMPTY('') in the else part, it consider the column has some value.

So you have to use NULL instead of ''.

```<code>COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE NULL END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE NULL END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END
                )
</code>```

IF we want Empty in the NULL columns, we have to use like below:

```<code>ISNULL(COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE NULL END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE NULL END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END
                ),'')
</code>```

Hope this is what you need:

```<code>SELECT ISNULL(CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes'
        ELSE
         CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes'
         ELSE
          CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END END  END
,'')
</code>```

Body:
I have a data set like bellow image.
I need in the data set

Grade Red is present then in OpenSegment=yes if not but
Grade Amber is present then in OpenSegment=yes if not but
Grade Blue is present then in OpenSegment=yes

for that I write

 COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE '' END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE '' END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE '' END
                )

but not working.

Result after putting  ELSE NULL

Body:
Try this, COALESCE is used for First Not NULL Value, if you give EMPTY('') in the else part, it consider the column has some value.

So you have to use NULL instead of ''.

COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE NULL END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE NULL END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END
                )

IF we want Empty in the NULL columns, we have to use like below:

ISNULL(COALESCE(
                  CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes' ELSE NULL END,
                  CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes' ELSE NULL END,
                 CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END
                ),'')

Hope this is what you need:

SELECT ISNULL(CASE WHEN airag.FK_MasterRAGRatingID=1 THEN 'yes'
        ELSE
         CASE WHEN airag.FK_MasterRAGRatingID=2 THEN 'yes'
         ELSE
          CASE WHEN airag.FK_MasterRAGRatingID=4 THEN 'yes' ELSE NULL END END  END
,'')