问:
How to check if textboxes are empty in UWP, using MVVM, and give the user a UI-validation
I'm making a simple sign-in page in UWP, using MVVM, and want to check if each of the textboxes are empty. Next to each textbox, there is a textblock with fontfamily "Wingdings 2".

If the field is empty, I want the textblock to show a red cross (" &#x4F ;"), and if the textbox contains text the textblock should update to show a green check-mark (" &#x50 ;").

(Note: There are no spaces in the words for the icons, but I had to put the spaces in there, to stop StackOverFlow from formatting the text).

All textblocks display a red cross by default (when the page is navigated to).

Here is an example picture of how I want it:

Here is my code in the ViewModel:

```<code>public string FirstName {
    get{
        return _firstName;
    }
    set{
        if (_firstName == null){
            _firstName = value;
            RaisePropertyChanged(nameof(FirstName));
        }
    }
}

public string LastName{
    get{
        return _lastName;
    }
    set{
        if (_lastName == null){
            _lastName = value;
            RaisePropertyChanged(nameof(LastName));
        }
    }
}
</code>```

How should I bind the textboxes to update icons in the textblocks next to them, when the user starts typing in each field?

答:
Well as it turns out I had worked on a project like a form validator for someone on stackoverflow itself.

I had uploaded the sample project for the same on Git as FormValidatorDemoStack. It's exactly what you need.

About the Project:

It contains two approaches, one without MVVM called the QuickAndDirty and the second one using MVVM and UserControls called the Recommended. You can see it from the splitview on the right side.

References:

The link to the old question is this and the follow up question for extending the validation to multiple inputs in a single field is this.

I hope this helps, if you have any questions feel free to use the
  comments section.

Body:
I'm making a simple sign-in page in UWP, using MVVM, and want to check if each of the textboxes are empty. Next to each textbox, there is a textblock with fontfamily "Wingdings 2".

If the field is empty, I want the textblock to show a red cross (" &#x4F ;"), and if the textbox contains text the textblock should update to show a green check-mark (" &#x50 ;").

(Note: There are no spaces in the words for the icons, but I had to put the spaces in there, to stop StackOverFlow from formatting the text).

All textblocks display a red cross by default (when the page is navigated to).

Here is an example picture of how I want it:

Here is my code in the ViewModel:

public string FirstName {
    get{
        return _firstName;
    }
    set{
        if (_firstName == null){
            _firstName = value;
            RaisePropertyChanged(nameof(FirstName));
        }
    }
}

public string LastName{
    get{
        return _lastName;
    }
    set{
        if (_lastName == null){
            _lastName = value;
            RaisePropertyChanged(nameof(LastName));
        }
    }
}

How should I bind the textboxes to update icons in the textblocks next to them, when the user starts typing in each field?


来源: stackexchange

问:
How do I find a "gap" in running counter with SQL?
I'd like to find the first "gap" in a counter column in an SQL table. For example, if there are values 1,2,4 and 5 I'd like to find out 3.

I can of course get the values in order and go through it manually, but I'd like to know if there would be a way to do it in SQL.

In addition, it should be quite standard SQL, working with different DBMSes.

答:
If You use Firebird 3 this is most elegant and simple:</p>

```<code>select RowID
  from (
    select `ID_Column`, Row_Number() over(order by `ID_Column`) as RowID
      from `Your_Table`
        order by `ID_Column`)
    where `ID_Column` <> RowID
    rows 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If You use Firebird 3 this is most elegant and simple:

select RowID
  from (
    select `ID_Column`, Row_Number() over(order by `ID_Column`) as RowID
      from `Your_Table`
        order by `ID_Column`)
    where `ID_Column` <> RowID
    rows 1


问:
Changing axis ticks in seaborn stripplotwhere x-value is a time stamp.
Fellow data nerds,

I want to plot data from a dataframe, using seaborn functionality and alter the x-axis ticks.

I read in the data as such

```<code>import pandas as pd

with open(f) as fi:
    df = pd.read_csv(fi, delimiter=';', parse_dates = ['date'])
df.date = df.date.apply(lambda x: x.date())#removing time, only date remains
</code>```

dataframe has three columns that are of importance for this issue:
df.date, df.sedimentation and df.label

the df.date has format yyyy-mm-dd
and is date object is of type: datetime.date

the df.sedimentation is of type: numpy.float64

the df.label is of type: str

I plot the data as following:

```<code>import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(figsize = figsize)

sns.set_style( "darkgrid")

ax.set_title(title)
ax = sns.stripplot(data = df, x = 'date', y = 'sedimentation', hue = 'label')
ax.set_ylim([-90,100])

plt.legend(ncol = 3, bbox_to_anchor=(1, 1), loc="upper left")

plt.show()
</code>```

This gives the following image:

However, the ticks on the x-axis only shows the values as given in the dataframe df. I want to have a continues x-axis showing all the months per year. With the data points of df.sedimentation showing at the correct points of the x-axis.

So I add the following:

```<code>import matplotlib.dates as mdates

years = mdates.YearLocator()   # set yearly ticker
months = mdates.MonthLocator()  # set monthly ticker
yearsFmt = mdates.DateFormatter('\n\n%Y') # set format for year
monthsFmt = mdates.DateFormatter('%b') # set format for month

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)

datemin = dt.date(df.date.min().year, 1, 1)
datemax = dt.date(df.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)
</code>```

But here is were some weird mojo happens that I do not understand, I get this image:

I get a beautiful x-axis ticker, but my data is not showing...

So I thought, maybe there are two different axes-objects. One here:

fig, ax = plt.subplots(figsize = figsize) and one here:

ax = sns.stripplot(data = df, x = 'date', y = 'sedimentation', hue = 'label')

So I thought I would add the axes object ax to this:

ax = sns.stripplot(data = df, ax = ax, x = 'date', y = 'sedimentation', hue = 'label')

But this did not work. I found a work around by not using seaborn at all, and just using matplotliband pandas``groupby functionality. But I want to use seaborn, since i am especially interested in the hue functionality.

My question is thus: Why is the data not showing when I alter the xaxis ticks?and How can I get my data to show on the axes object with still having the ticks that I want?

答:
A stripplot is a categorical plot. As the documentation says:

Draw a scatterplot where one variable is categorical.

Your dates are hence shown as categories (i.e. one date per integer number, the axis ranges from 0 to len(categories)-1). Your first category is "2016-01-29", which will be shown at position 0 on the axis. Your second category is "2016-05-18", which is shown at position 1 on the axis, and so on.

In order to have the real dates on the axis, don't use any categorical plot. Instead plt.scatter might be an option.

```<code>from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rd = lambda : datetime(2017,np.random.randint(1,13),np.random.randint(1,29))
cats = ["Category {}".format(i) for i  in list("ABCD")]
df = pd.DataFrame({"date" : [rd() for i in range(29)],
                   "y" : np.random.rand(29),
                   "category" : np.random.choice(cats,size=29)})

dates = [d.to_pydatetime() for d in df["date"]]
u, c = np.unique(df["category"], return_inverse=True)

sc = plt.scatter(dates, df["y"], c=plt.cm.tab10(c))

scmap = lambda i: plt.plot([],[], marker="o",ls="none", c=plt.cm.tab10(i))[0]
plt.legend(handles=[scmap(i) for i in range(len(u))],
           labels=list(u))
plt.gcf().autofmt_xdate()
plt.show()
</code>```

Alternatively using seaborn, you can use a FacetGrid to map to a plt.scatter plot, such the hue argument can be used.

```<code>from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

rd = lambda : datetime(2017,np.random.randint(1,13),np.random.randint(1,29))
cats = ["Category {}".format(i) for i  in list("ABCD")]
df = pd.DataFrame({"date" : pd.Series([rd() for i in range(29)], dtype=object),
                   "y" : np.random.rand(29),
                   "category" : np.random.choice(cats,size=29)})

g = sns.FacetGrid(df, hue="category", size=3, aspect=2)
g.map(plt.scatter, "date", "y").add_legend()

plt.show()
</code>```

Body:
Fellow data nerds,

I want to plot data from a dataframe, using seaborn functionality and alter the x-axis ticks.

I read in the data as such

import pandas as pd

with open(f) as fi:
    df = pd.read_csv(fi, delimiter=';', parse_dates = ['date'])
df.date = df.date.apply(lambda x: x.date())#removing time, only date remains

dataframe has three columns that are of importance for this issue:
df.date, df.sedimentation and df.label

the df.date has format yyyy-mm-dd
and is date object is of type: datetime.date

the df.sedimentation is of type: numpy.float64

the df.label is of type: str

I plot the data as following:

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(figsize = figsize)

sns.set_style( "darkgrid")

ax.set_title(title)
ax = sns.stripplot(data = df, x = 'date', y = 'sedimentation', hue = 'label')
ax.set_ylim([-90,100])

plt.legend(ncol = 3, bbox_to_anchor=(1, 1), loc="upper left")

plt.show()

This gives the following image:

However, the ticks on the x-axis only shows the values as given in the dataframe df. I want to have a continues x-axis showing all the months per year. With the data points of df.sedimentation showing at the correct points of the x-axis.

So I add the following:

import matplotlib.dates as mdates

years = mdates.YearLocator()   # set yearly ticker
months = mdates.MonthLocator()  # set monthly ticker
yearsFmt = mdates.DateFormatter('\n\n%Y') # set format for year
monthsFmt = mdates.DateFormatter('%b') # set format for month

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)

datemin = dt.date(df.date.min().year, 1, 1)
datemax = dt.date(df.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)

But here is were some weird mojo happens that I do not understand, I get this image:

I get a beautiful x-axis ticker, but my data is not showing...

So I thought, maybe there are two different axes-objects. One here:

fig, ax = plt.subplots(figsize = figsize) and one here:

ax = sns.stripplot(data = df, x = 'date', y = 'sedimentation', hue = 'label')

So I thought I would add the axes object ax to this:

ax = sns.stripplot(data = df, ax = ax, x = 'date', y = 'sedimentation', hue = 'label')

But this did not work. I found a work around by not using seaborn at all, and just using matplotliband pandas``groupby functionality. But I want to use seaborn, since i am especially interested in the hue functionality.

My question is thus: Why is the data not showing when I alter the xaxis ticks?and How can I get my data to show on the axes object with still having the ticks that I want?

Body:
A stripplot is a categorical plot. As the documentation says:

Draw a scatterplot where one variable is categorical.

Your dates are hence shown as categories (i.e. one date per integer number, the axis ranges from 0 to len(categories)-1). Your first category is "2016-01-29", which will be shown at position 0 on the axis. Your second category is "2016-05-18", which is shown at position 1 on the axis, and so on.

In order to have the real dates on the axis, don't use any categorical plot. Instead plt.scatter might be an option.

from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rd = lambda : datetime(2017,np.random.randint(1,13),np.random.randint(1,29))
cats = ["Category {}".format(i) for i  in list("ABCD")]
df = pd.DataFrame({"date" : [rd() for i in range(29)],
                   "y" : np.random.rand(29),
                   "category" : np.random.choice(cats,size=29)})

dates = [d.to_pydatetime() for d in df["date"]]
u, c = np.unique(df["category"], return_inverse=True)

sc = plt.scatter(dates, df["y"], c=plt.cm.tab10(c))

scmap = lambda i: plt.plot([],[], marker="o",ls="none", c=plt.cm.tab10(i))[0]
plt.legend(handles=[scmap(i) for i in range(len(u))],
           labels=list(u))
plt.gcf().autofmt_xdate()
plt.show()

Alternatively using seaborn, you can use a FacetGrid to map to a plt.scatter plot, such the hue argument can be used.

from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

rd = lambda : datetime(2017,np.random.randint(1,13),np.random.randint(1,29))
cats = ["Category {}".format(i) for i  in list("ABCD")]
df = pd.DataFrame({"date" : pd.Series([rd() for i in range(29)], dtype=object),
                   "y" : np.random.rand(29),
                   "category" : np.random.choice(cats,size=29)})

g = sns.FacetGrid(df, hue="category", size=3, aspect=2)
g.map(plt.scatter, "date", "y").add_legend()

plt.show()


问:
typeof 90/'hi' is NaN while typeof (90/'hi') is number. Why so?
I was playing around the NaN of JavaScript and found some strange behavior while using typeof operator on a result of number/string.
why so?</p>

答:
typeof 90/"hi" is executed as (typeof 90)/"hi" which becomes "number"/"hi" => NaN

typeof (90/"hi") => typeof NaN => "number"


问:
Method in child class doesn't get called by virtual function in parent class
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

```<code>int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}
</code>```

ChildReader1.h

```<code>class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };
</code>```

ParentReader.h

```<code>class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };
</code>```

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?

答:
As said by others, you should not call virtual function in constructor. The reason is quite simple if you think about what is happening:

call of ChildConstructor -> call of ParentConstructor -> creation of Parent -> call of getData -> creation of Child

At the call of getData the only existing object is the Parent therefore it can't possibly call the getData of the Child.

Body:
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}

ChildReader1.h

class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };

ParentReader.h

class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?


问:
How to implement can_typecast(type, value) in python?
I need to write a function that has following signature:

can_typecast(value, type)

Both type and value are of type string. Function should return True if value can be casted to type and False otherwise.

For example:

can_typecast('abc', 'float64') should return False

can_typecast('12', 'str') should return True

Is there a way to achieve this without using if/else for each type?

答:
This is using exec, so you need to be very careful with the values that you allow the user to input into value and type:

```<code>def can_typecast(value, type):
    try:
        exec("{}('{}')".format(type, value))
    except ValueError:
        return False
    return True

print(can_typecast('12', 'int'))
# True
print(can_typecast('12', 'str'))
# True
print(can_typecast('a', 'int'))
# False
</code>```

If you are allowed to pass the type as type and not as a string, you don't need to rely on exec, you just try the conversion:

```<code>def can_typecast(value, type):
    try:
        type(value)
    except ValueError:
        return False
    return True

print(can_typecast('12', int))
# True
print(can_typecast('12', str))
# True
print(can_typecast('a', int))
# False
</code>```

Body:
This is using exec, so you need to be very careful with the values that you allow the user to input into value and type:

def can_typecast(value, type):
    try:
        exec("{}('{}')".format(type, value))
    except ValueError:
        return False
    return True

print(can_typecast('12', 'int'))
# True
print(can_typecast('12', 'str'))
# True
print(can_typecast('a', 'int'))
# False

If you are allowed to pass the type as type and not as a string, you don't need to rely on exec, you just try the conversion:

def can_typecast(value, type):
    try:
        type(value)
    except ValueError:
        return False
    return True

print(can_typecast('12', int))
# True
print(can_typecast('12', str))
# True
print(can_typecast('a', int))
# False


问:
template class operator overloading problem
I'm trying to port some Visual C++ (VS2005) code so that it will compile under both VS2005 and C++ Builder XE.  The code that follows compiles fine under VS2005 but under C++ Builder XE, I get the following error:

[BCC32 Error] time_stamp.h(49): E2327 Operators may not have default argument values

Here is the code in question: (time_stamp.h)

```<code>template<typename counter_type>
class time_stamp
{
typedef time_span<counter_type>                     time_span_type;
typedef typename counter_type::value_type   value_type;

public:

/* some code removed for sake of this post, next line is the one causing the error */

friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}

private:

value_type m_stamp;

}
</code>```

The time_span template is as follows (time_span.h):

```<code>template<typename counter_type>
class time_span
{
public:
// TYPES
  typedef counter_type          counter_type;
  typedef typename counter_type::value_type value_type;

/* rest removed for sake of this post */
}
</code>```

The C++ Builder compiler appears to not like the line:
friend time_span operator-(const time_stamp &first, const time_stamp &second)

I'm new to templates and this syntax escapes me or at least the compiler error I can't make sense of.  It appears, to me, that there are no default argument values despite the compiler saying so.  I'm interpreting the error message as saying const time_stamp & is a default value when it looks to me like a passed reference of type time_stamp.

Thanks for reading & replying.  Help understanding as well as fixing is most appreciated.

--- EDIT:

If I re-structure the call above as follows:

```<code>friend time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) );
</code>```

and outside the class definition, I describe the function:

```<code>template<typename counter_type>
time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) )
{
return time_span<counter_type>(first.m_stamp-second.m_stamp);
}
</code>```

I then get this error:

[BCC32 Error] time_stamp.hpp(56): E2082 '-(int (*)(const time_stamp &,const time_stamp &))' must be a member function or have a parameter of class type

答:
[Replacing my previous answer!]

This is probably related to http://www.parashift.com/c++-faq/templates.html#faq-35.16 .

Since the function you want to define is in fact a template function (it depends on counter_type), you should declare it before the friend declaration, and then declare a function template instantiation to be the friend:

```<code>// time_stamp.h
#include "time_span.h"
template<typename counter_type> class time_stamp;
template<typename counter_type> time_span<counter_type> operator-(
    const time_stamp<counter_type>&, const time_stamp<counter_type>& );

template<typename counter_type>
class time_stamp
{
  //...
    friend time_span<counter_type> operator- <> (
        const time_stamp<counter_type>&, const time_stamp<counter_type>&);
};

template<typename counter_type>
inline time_span<counter_type> operator-(
    const time_stamp<counter_type>& first, const time_stamp<counter_type>& second)
{
    return time_span<counter_type>(first.m_stamp - second.m_stamp);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to port some Visual C++ (VS2005) code so that it will compile under both VS2005 and C++ Builder XE.  The code that follows compiles fine under VS2005 but under C++ Builder XE, I get the following error:

[BCC32 Error] time_stamp.h(49): E2327 Operators may not have default argument values

Here is the code in question: (time_stamp.h)

template<typename counter_type>
class time_stamp
{
typedef time_span<counter_type>                     time_span_type;
typedef typename counter_type::value_type   value_type;

public:

/* some code removed for sake of this post, next line is the one causing the error */

friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second)
{
  return time_span<counter_type>(first.m_stamp - second.m_stamp);
}

private:

value_type m_stamp;

}

The time_span template is as follows (time_span.h):

template<typename counter_type>
class time_span
{
public:
// TYPES
  typedef counter_type          counter_type;
  typedef typename counter_type::value_type value_type;

/* rest removed for sake of this post */
}

The C++ Builder compiler appears to not like the line:
friend time_span operator-(const time_stamp &first, const time_stamp &second)

I'm new to templates and this syntax escapes me or at least the compiler error I can't make sense of.  It appears, to me, that there are no default argument values despite the compiler saying so.  I'm interpreting the error message as saying const time_stamp & is a default value when it looks to me like a passed reference of type time_stamp.

Thanks for reading & replying.  Help understanding as well as fixing is most appreciated.

--- EDIT:

If I re-structure the call above as follows:

friend time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) );

and outside the class definition, I describe the function:

template<typename counter_type>
time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) )
{
return time_span<counter_type>(first.m_stamp-second.m_stamp);
}

I then get this error:

[BCC32 Error] time_stamp.hpp(56): E2082 '-(int (*)(const time_stamp &,const time_stamp &))' must be a member function or have a parameter of class type

Body:
[Replacing my previous answer!]

This is probably related to http://www.parashift.com/c++-faq/templates.html#faq-35.16 .

Since the function you want to define is in fact a template function (it depends on counter_type), you should declare it before the friend declaration, and then declare a function template instantiation to be the friend:

// time_stamp.h
#include "time_span.h"
template<typename counter_type> class time_stamp;
template<typename counter_type> time_span<counter_type> operator-(
    const time_stamp<counter_type>&, const time_stamp<counter_type>& );

template<typename counter_type>
class time_stamp
{
  //...
    friend time_span<counter_type> operator- <> (
        const time_stamp<counter_type>&, const time_stamp<counter_type>&);
};

template<typename counter_type>
inline time_span<counter_type> operator-(
    const time_stamp<counter_type>& first, const time_stamp<counter_type>& second)
{
    return time_span<counter_type>(first.m_stamp - second.m_stamp);
}


问:
How to set Hint font to italic with TextInputLayout?
How to set Hint font to italic with TextInputLayout in android.
With normal edit strong text text

" Name "

this will work if we set as hint, but not with TextInputLayout.

答:
In this way you can set the typeface to hint of any edit text:

in layout.xml :

```<code> <android.support.design.widget.TextInputLayout
            android:id="@+id/text_input1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <EditText
                android:id="@+id/edt_user"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/username"/>
        </android.support.design.widget.TextInputLayout>
</code>```

and in java class :

```<code>public class MainActivity extends AppCompatActivity {

EditText editText;
TextInputLayout textInputLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Typeface font_yekan= Typeface.createFromAsset(getAssets(), "fonts/italic.ttf");
        textInputLayout= (TextInputLayout) findViewById(R.id.text_input1);
    textInputLayout.setTypeface(font_yekan);
      }
 }
</code>```

Body:
In this way you can set the typeface to hint of any edit text:

in layout.xml :

 <android.support.design.widget.TextInputLayout
            android:id="@+id/text_input1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <EditText
                android:id="@+id/edt_user"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/username"/>
        </android.support.design.widget.TextInputLayout>

and in java class :

public class MainActivity extends AppCompatActivity {

EditText editText;
TextInputLayout textInputLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Typeface font_yekan= Typeface.createFromAsset(getAssets(), "fonts/italic.ttf");
        textInputLayout= (TextInputLayout) findViewById(R.id.text_input1);
    textInputLayout.setTypeface(font_yekan);
      }
 }


问:
Plugin in dokuwiki causes wiki to block images
I have written an own plugin.
Everything works fine except for the mediamanager.

If i open the mediamanager i cannot see any of the thumbnails.
If i try to upload some new pictures, apache crashs.

After some experimenting around, i figured out that this code snippet causes the error:

If you place this under

```<code>/lib/plugins/lfs/action.php
</code>```

And open the mediamanager and upload a new picture to wiki:

Could someone please test this? And does someone see my mistake?
Thanks

```<code><?php
/**
 * Example Action Plugin: Inserts a button into the toolbar
 *
 */
if (!defined('DOKU_INC')) die();

class action_plugin_lfs extends DokuWiki_Action_Plugin {
    // Register the eventhandlers
    function register(Doku_Event_Handler $controller) {
        $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'insert_button', array ());
    }

    public function insert_button(Doku_Event $event, $param) {

        $event->data[] = array (
            'type'   => 'mediapopup',
            'title'  => 'Link zu Dateien auf dem Netzlaufwerk',
            'icon'   => '../../plugins/lfs/buttonlink.png',
            'url'    => '../lib/plugins/lfs/browser.php?useless=',
            'name'   => 'winsharelink',
            'options'=> 'width=750,height=500,left=20,top=20,scrollbars=yes,resizable=yes',
            'block'  => false,
        );

    }
}
?>
</code>```

UPDATE 1:

Used Server: xampp 3.2.2 under Win10 (local)
PHP: 7.1.10 Apache: 2.4.28.0 WIN32

Today apache did not crash after i tried to load the thumbnail of the uploaded picture or the picture itself.

But it is still not working.

Here a picture WITH action.php in place under lib/plugins/lfs/

And then, just moved action.php out of the lfs folder and deleted and reuploaded logo3.png:

UPDATE 2:

No i tested it with EasyPHP. Still the same result.

UPDATE 3:

```<code>Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/dokuwiki/lib/plugins/lfs/action.php:1) in /var/www/html/dokuwiki/inc/actions.php on line 210

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/dokuwiki/lib/plugins/lfs/action.php:1) in /var/www/html/dokuwiki/lib/tpl/dokuwiki/main.php on line 12
</code>```

答:
Problem Solved!!!

You should never!!!! Have idents in your code-file:

```<code>|
|  <?php....
|
</code>```

is not the same than

```<code>|
|<?php...
|
</code>```

is!!!

There are some spaces which are sent to the browser. Therefore the "header already sent error appears!"

Damn! such a stupid error delays the developemnt many days and weeks...

Body:
I have written an own plugin.
Everything works fine except for the mediamanager.

If i open the mediamanager i cannot see any of the thumbnails.
If i try to upload some new pictures, apache crashs.

After some experimenting around, i figured out that this code snippet causes the error:

If you place this under

/lib/plugins/lfs/action.php

And open the mediamanager and upload a new picture to wiki:

Could someone please test this? And does someone see my mistake?
Thanks

<?php
/**
 * Example Action Plugin: Inserts a button into the toolbar
 *
 */
if (!defined('DOKU_INC')) die();

class action_plugin_lfs extends DokuWiki_Action_Plugin {
    // Register the eventhandlers
    function register(Doku_Event_Handler $controller) {
        $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'insert_button', array ());
    }

    public function insert_button(Doku_Event $event, $param) {

        $event->data[] = array (
            'type'   => 'mediapopup',
            'title'  => 'Link zu Dateien auf dem Netzlaufwerk',
            'icon'   => '../../plugins/lfs/buttonlink.png',
            'url'    => '../lib/plugins/lfs/browser.php?useless=',
            'name'   => 'winsharelink',
            'options'=> 'width=750,height=500,left=20,top=20,scrollbars=yes,resizable=yes',
            'block'  => false,
        );

    }
}
?>

UPDATE 1:

Used Server: xampp 3.2.2 under Win10 (local)
PHP: 7.1.10 Apache: 2.4.28.0 WIN32

Today apache did not crash after i tried to load the thumbnail of the uploaded picture or the picture itself.

But it is still not working.

Here a picture WITH action.php in place under lib/plugins/lfs/

And then, just moved action.php out of the lfs folder and deleted and reuploaded logo3.png:

UPDATE 2:

No i tested it with EasyPHP. Still the same result.

UPDATE 3:

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/dokuwiki/lib/plugins/lfs/action.php:1) in /var/www/html/dokuwiki/inc/actions.php on line 210

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/dokuwiki/lib/plugins/lfs/action.php:1) in /var/www/html/dokuwiki/lib/tpl/dokuwiki/main.php on line 12

Body:
Problem Solved!!!

You should never!!!! Have idents in your code-file:

|
|  <?php....
|

is not the same than

|
|<?php...
|

is!!!

There are some spaces which are sent to the browser. Therefore the "header already sent error appears!"

Damn! such a stupid error delays the developemnt many days and weeks...


问:
Rails - accepts_nested_attributes_for and presence validation
In my application I have a simple relationship where a user that has many events:

```<code>class User < ApplicationRecord
  has_many :events, foreign_key: 'created_by', dependent: :destroy
  accepts_nested_attributes_for :events
end

class Event < ApplicationRecord
  belongs_to :user, foreign_key: 'created_by', inverse_of: :events
  validates :created_by, presence: true
end
</code>```

When I am trying to create a user alongside with some events I am getting a validation error "Companies.created by can't be blank".

My params hash looks like that:

```<code>{"user"=>{"events_attributes"=>[{"name"=>"disney show"}]}}
</code>```

When I remove validates :created_by, presence: true everything works as expected. Any help would be appreciated!

答:
Try to specify explicitly bi-directional associations in your User model using inverse_of: :

```<code>class User < ApplicationRecord
    has_many :events, foreign_key: 'created_by', inverse_of: :user, dependent: :destroy
    accepts_nested_attributes_for :events
end
</code>```

And your Event record will be created with present foreign key pointing to User.

Body:
In my application I have a simple relationship where a user that has many events:

class User < ApplicationRecord
  has_many :events, foreign_key: 'created_by', dependent: :destroy
  accepts_nested_attributes_for :events
end

class Event < ApplicationRecord
  belongs_to :user, foreign_key: 'created_by', inverse_of: :events
  validates :created_by, presence: true
end

When I am trying to create a user alongside with some events I am getting a validation error "Companies.created by can't be blank".

My params hash looks like that:

{"user"=>{"events_attributes"=>[{"name"=>"disney show"}]}}

When I remove validates :created_by, presence: true everything works as expected. Any help would be appreciated!

Body:
Try to specify explicitly bi-directional associations in your User model using inverse_of: :

class User < ApplicationRecord
    has_many :events, foreign_key: 'created_by', inverse_of: :user, dependent: :destroy
    accepts_nested_attributes_for :events
end

And your Event record will be created with present foreign key pointing to User.


问:
How to resolve Php Error occur after update wordpress
I update the wordpress. After that some issue were seen.

Warning: include(images/LayerSlider_v5.3.2.png): failed to open stream: No such
file or directory in
/home/cloudbed/public_html/druits.com/wp-content/plugins/LayerSlider/layerslider.php
on line 202

Warning: include(images/LayerSlider_v5.3.2.png): failed to open
stream: No such file or directory in
/home/cloudbed/public_html/druits.com/wp-content/plugins/LayerSlider/layerslider.php
on line 202

Warning: include(): Failed opening 'images/LayerSlider_v5.3.2.png'
for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/cloudbed/public_html/druits.com/wp-content/plugins/LayerSlider/layerslider.php
on line 202

Warning: Cannot modify header information - headers already sent by
(output started at
/home/cloudbed/public_html/druits.com/wp-content/plugins/LayerSlider/layerslider.php:202)
in /home/cloudbed/public_html/druits.com/wp-includes/pluggable.php on
line 1174

答:
You can disable LayerSlider plugin and your site should go online without errors.
Then delete the plugin via FTP and try to install it again.
Something has gone wrong during the update.</p>


问:
How to pass access token to Alamofire?
I am trying to pass access token in Alamofire but getting confuse in various methods around web.

Below are methods which we need to use.

```<code>let todosEndpoint: String = "https:url......."

let headers = [
            "Authorization": "Bearer \(token!)",
            "Content-Type": "application/X-Access-Token"
        ]
        let Auth_header    = [ "Authorization" : tokenString! ]

        Alamofire.request(todosEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Auth_header)
            .responseJSON { response in
                print("response.request \(response.request)")  // original URL request
                print("response.response \(response.response)") // HTTP URL response
                print("response.data \(response.data)")     // server data
                print("response.result \(response.result)")

                print("response \(response)")

        }

    }
</code>```

OR

```<code>let aManager = SessionManager()
        aManager.session.configuration.httpAdditionalHeaders = [
            "Authorization": "Bearer tokenString"]
</code>```

OR

```<code>let headerss = [
            "Authorization": tokenString]
</code>```

OR

```<code>let aManager = SessionManager()
            aManager.session.configuration.httpAdditionalHeaders = [
                "Authorization": "Basic tokenString"]
</code>```

What is proper way to pass access token?

答:
It can be done by using Alamofire in following way:</p>

```<code>    let url: String = "https:url......."
    var request = URLRequest(url:  NSURL(string: url)! as URL)

    // Your request method type Get or post etc according to your requirement
    request.httpMethod = "POST"

    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // Your required parameter in case of Post request
    let parameters: [String: Any] = ["paramter1": "vaue1"]

    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters )

    Alamofire.request(request).responseJSON { (responseObject) -> Void in

      // Your required functionality here

    }
</code>```

Title: How to pass access token to Alamofire?

Body:
I am trying to pass access token in Alamofire but getting confuse in various methods around web.

Below are methods which we need to use.

let todosEndpoint: String = "https:url......."

let headers = [
            "Authorization": "Bearer \(token!)",
            "Content-Type": "application/X-Access-Token"
        ]
        let Auth_header    = [ "Authorization" : tokenString! ]

        Alamofire.request(todosEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Auth_header)
            .responseJSON { response in
                print("response.request \(response.request)")  // original URL request
                print("response.response \(response.response)") // HTTP URL response
                print("response.data \(response.data)")     // server data
                print("response.result \(response.result)")

                print("response \(response)")

        }

    }

OR

let aManager = SessionManager()
        aManager.session.configuration.httpAdditionalHeaders = [
            "Authorization": "Bearer tokenString"]

OR

let headerss = [
            "Authorization": tokenString]

OR

let aManager = SessionManager()
            aManager.session.configuration.httpAdditionalHeaders = [
                "Authorization": "Basic tokenString"]

What is proper way to pass access token?

Body:
It can be done by using Alamofire in following way:

    let url: String = "https:url......."
    var request = URLRequest(url:  NSURL(string: url)! as URL)

    // Your request method type Get or post etc according to your requirement
    request.httpMethod = "POST"

    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // Your required parameter in case of Post request
    let parameters: [String: Any] = ["paramter1": "vaue1"]

    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters )

    Alamofire.request(request).responseJSON { (responseObject) -> Void in

      // Your required functionality here

    }


问:
Save canvas img with droidscript
OK so I am aware of the traditional HTML5 ways of saving a canvas img as a png, however my project is a DroidScript app and window location doesn't work and there is no server side to post process the img on a server and download it.

My question is how would one get the img to save using the DroidScript api probably using app.WriteFile.

I've tried generating the img with var img = app.CreateImage and then saving it with img.Save but the img isn't successfully generated, I've also tried converting it to a blob using canvas.toBlob and using app.WriteFile but the png is broken... same with canvas.toDataURL as well.

Both conversions fail with app.WriteFile and app.CreateFile which are the only solutions that seem to actually save the file at all. I've also tried using JavaScript's FileReader to do the conversions with no success...

I believe I am simply doing the order of operations incorrectly or using the wrong properties.

I don't have all of the versions of code that I've tried but here is the latest version that is generating a broken png.

```<code>app.toImage = function(){
            var reader = new FileReader();
            reader.onload = function readSuccess(e) {
    var img = e.target.result;
    var file = app.CreateFile('/sdcard/Download/t.png', "rw");

        uint8ArrayNew = new Uint8Array(img);
    file.WriteData(uint8ArrayNew, "Bytes");
    file.Close();
        };
        win.canvas.toBlob(function(b) {
            reader.readAsDataURL(b);
        });
}
    }
</code>```

EDIT... this code saves the base64 data url inside of the file as a string which can be validated to show the correct image, however the file still appears as broken in a file browser

```<code>app.toImage = function(){

        var img = win.canvas.toDataURL("image/png;base64;");

        var reader  = new FileReader();

          reader.addEventListener("load", function (e) {
            // preview.src = reader.result;
            app.WriteFile('/sdcard/Download/t.png', reader.result);
          }, false);
                win.canvas.toBlob(function(b) {
                    reader.readAsDataURL(b);
                });
 }
    }
</code>```

This is the file contents

```data:image/png;base64,[encoded data, 25832 characters]
```

Paste into this tool and i get the correct image

http://codebeautify.org/base64-to-image-converter

How do i save it as an actual png

答:
The DroidScript Image control allows you to set the pixel data using a base64 string, so you could send the data to a hidden or visible image control and then use the img.Save() method to save it as a jpeg or png.

This is the prototype for the img.SetPixelData method:-

SetPixelData( data, width, height, options )

It can handle with or without mime type header and you can leave out the width, height and options params if you like

ContentLicense: CC BY-SA 4.0

Title: Save canvas img with droidscript

Body:
OK so I am aware of the traditional HTML5 ways of saving a canvas img as a png, however my project is a DroidScript app and window location doesn't work and there is no server side to post process the img on a server and download it.

My question is how would one get the img to save using the DroidScript api probably using app.WriteFile.

I've tried generating the img with var img = app.CreateImage and then saving it with img.Save but the img isn't successfully generated, I've also tried converting it to a blob using canvas.toBlob and using app.WriteFile but the png is broken... same with canvas.toDataURL as well.

Both conversions fail with app.WriteFile and app.CreateFile which are the only solutions that seem to actually save the file at all. I've also tried using JavaScript's FileReader to do the conversions with no success...

I believe I am simply doing the order of operations incorrectly or using the wrong properties.

I don't have all of the versions of code that I've tried but here is the latest version that is generating a broken png.

app.toImage = function(){
            var reader = new FileReader();
            reader.onload = function readSuccess(e) {
    var img = e.target.result;
    var file = app.CreateFile('/sdcard/Download/t.png', "rw");

        uint8ArrayNew = new Uint8Array(img);
    file.WriteData(uint8ArrayNew, "Bytes");
    file.Close();
        };
        win.canvas.toBlob(function(b) {
            reader.readAsDataURL(b);
        });
}
    }

EDIT... this code saves the base64 data url inside of the file as a string which can be validated to show the correct image, however the file still appears as broken in a file browser

app.toImage = function(){

        var img = win.canvas.toDataURL("image/png;base64;");

        var reader  = new FileReader();

          reader.addEventListener("load", function (e) {
            // preview.src = reader.result;
            app.WriteFile('/sdcard/Download/t.png', reader.result);
          }, false);
                win.canvas.toBlob(function(b) {
                    reader.readAsDataURL(b);
                });
 }
    }

This is the file contents

data:image/png;base64,[encoded data, 25832 characters]

Paste into this tool and i get the correct image

http://codebeautify.org/base64-to-image-converter

How do i save it as an actual png


问:
Injecting the repository classes in a Custom Action Filter
I have a custom action filter attribute that checks if the user has it's service active and if not the filter automatically redirect the user to a renew page.

Recently we did a re-enginering of our code and we introduced the repository pattern. Before of this we used the repository classes directly in the custom action filter like

```<code>private OrderRepository _orderRepository = new OrderRepository();
</code>```

I am guessing which is the right way to inject repository classes inside the custom action filter now that we are using this pattern.

Thanks a lot

答:
Brad Wilson shares how to do this:

http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html

Body:
I have a custom action filter attribute that checks if the user has it's service active and if not the filter automatically redirect the user to a renew page.

Recently we did a re-enginering of our code and we introduced the repository pattern. Before of this we used the repository classes directly in the custom action filter like

private OrderRepository _orderRepository = new OrderRepository();

I am guessing which is the right way to inject repository classes inside the custom action filter now that we are using this pattern.

Thanks a lot


问:
How to wrap text to next cell in tableview component?
I need to fill a text from database in cell, but when the cell is full, the text should continue in the next cell, down this.

I have one idea how implement it:

```<code> Text theText = new Text(jFXTextFieldSearch.getText());
    theText.setFont(jFXTextFieldSearch.getFont());
    double width = theText.getBoundsInLocal().getWidth();
    System.out.println(width);
</code>```

How good is this method, or is there another way to do it?
The database is large enough, and table has 50 pages.

答:
Try this:

```<code>@FXML
private TableView<String> table;

@FXML
private TableColumn<String, String> column;

...

String string =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt " +
        "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " +
        "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " +
        "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " +
        "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

AttributedString attributedString = new AttributedString(string);
attributedString.addAttribute(TextAttribute.FONT, new Font("Arial", Font.BOLD, 16));

AttributedCharacterIterator iterator = attributedString.getIterator();
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);

ObservableList<String> list = FXCollections.observableArrayList();
while (measurer.getPosition() < iterator.getEndIndex()) {
    TextLayout layout = measurer.nextLayout((float) column.getWidth());
    list.add(string.substring(measurer.getPosition() - layout.getCharacterCount(), measurer.getPosition()));
}

table.setItems(list);
</code>```

The font to be submit to the attributedString should be the same as that used for rendering in the desired column.

Body:
I need to fill a text from database in cell, but when the cell is full, the text should continue in the next cell, down this.

I have one idea how implement it:

 Text theText = new Text(jFXTextFieldSearch.getText());
    theText.setFont(jFXTextFieldSearch.getFont());
    double width = theText.getBoundsInLocal().getWidth();
    System.out.println(width);

How good is this method, or is there another way to do it?
The database is large enough, and table has 50 pages.

Body:
Try this:

@FXML
private TableView<String> table;

@FXML
private TableColumn<String, String> column;

...

String string =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt " +
        "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " +
        "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " +
        "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " +
        "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

AttributedString attributedString = new AttributedString(string);
attributedString.addAttribute(TextAttribute.FONT, new Font("Arial", Font.BOLD, 16));

AttributedCharacterIterator iterator = attributedString.getIterator();
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);

ObservableList<String> list = FXCollections.observableArrayList();
while (measurer.getPosition() < iterator.getEndIndex()) {
    TextLayout layout = measurer.nextLayout((float) column.getWidth());
    list.add(string.substring(measurer.getPosition() - layout.getCharacterCount(), measurer.getPosition()));
}

table.setItems(list);

The font to be submit to the attributedString should be the same as that used for rendering in the desired column.


问:
What is the proper order for installing Microsoft software on a developer workstation?
I've done this a million times ... setting up a developer work station.

Is there a best practices, or installation checklist for installing Microsoft development software on a work station? What about applying updates and/or service packs?  Is there a specific order for doing this, in hopes of minimizing any install issues.

Our current software library consists of:

Visual Studio 2003

Visual Studio 2008

SQL Server 2005

Microsoft Office 2007

We do use some other tools, but I usually hold off on installing them once I get a good build from Microsoft ... whether a good build is possible or not is another topic! =)

Also, do you use any software like Ghost to create images of work station?  Some easy way to restore your work station.

答:
My recommendation is to start with the OS and its updates, then add Office if you need that and then install Virtual PC or VMWare.
This way you can separate the different versions (and betas) of all the development stuff into different VPC's.
Your real hardware will stay clean and you are able to switch between environments very smoothly.</p>

OwnerDisplayName: Matt Ruma

OwnerDisplayName: thijs


问:
Binding HyperLinks to GridView using AutoGenerateColumns
I have a DataTable which has columns that are generated dynamically at runtime. This DataTable is bound to a GridView that has AutoGenerateColumns set to true. I've run into a problem with this since some of the data in the DataTable are HyperLink objects, so instead of displaying the actual link in the table, it displays "System.Web.UI.WebControls.HyperLink".

Normally, I would just use a HyperLinkField in my GridView, but since the GridView's columns are generated automatically, I'm not sure how to do this. Any ideas?

答:
You can add a new column dynamically, you'll just have to hide the automatically generated columns also.

For this solution you can either store the hyperlink in 2 columns - 1 for the link and 1 for the text you want displayed, or if you want something generic displayed (like 'Click Here') you can just store the link (eg "http://example.com.au/Default.aspx").

```<code>protected void GridView1_RowBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //add new header
        TableCell tc = new TableCell();
        tc.Text = "Groovy Link";
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound - skip column we just added
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //create new tablecell
        TableCell tc = new TableCell();
        //do a check to see if the data is stored as a hyperlink in DB
        if (DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString().StartsWith("<a") == true)
        {
            //create hyperlink
            HyperLink hyp = new HyperLink();
            hyp.NavigateUrl = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString();
            hyp.Text = "click here";
            tc.Controls.Add(hyp);
        }
        else
        {
            //just text
            tc.Text = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString()
        }
        //add tablecell to row
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
}
</code>```

Body:
You can add a new column dynamically, you'll just have to hide the automatically generated columns also.

For this solution you can either store the hyperlink in 2 columns - 1 for the link and 1 for the text you want displayed, or if you want something generic displayed (like 'Click Here') you can just store the link (eg "http://example.com.au/Default.aspx").

protected void GridView1_RowBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //add new header
        TableCell tc = new TableCell();
        tc.Text = "Groovy Link";
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound - skip column we just added
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //create new tablecell
        TableCell tc = new TableCell();
        //do a check to see if the data is stored as a hyperlink in DB
        if (DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString().StartsWith("<a") == true)
        {
            //create hyperlink
            HyperLink hyp = new HyperLink();
            hyp.NavigateUrl = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString();
            hyp.Text = "click here";
            tc.Controls.Add(hyp);
        }
        else
        {
            //just text
            tc.Text = DataBinder.Eval(e.Row.DataItem, "AutoGeneratedColumnName").ToString()
        }
        //add tablecell to row
        e.Row.Cells.Add(tc);
        //hide original column that has been autobound
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;
            if (field.DataField == "AutoGeneratedColumnName")
                field.Visible = false;
        }
    }
}


问:
Select, default value in AngularJS
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

```<code><div ng-app="select" ng-controller="checking">
  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>
</div>
</code>```

JavaScript

```<code>var app = angular.module('select', []);

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});
</code>```

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

答:
I think you just need to assign the ng-model like this.

```<code> $scope.lala = $scope.arrayName[0];
</code>```

Here is your codepen link

Title: Select, default value in AngularJS

Body:
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>

JavaScript

var app = angular.module('select', []);

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

Body:
I think you just need to assign the ng-model like this.

 $scope.lala = $scope.arrayName[0];

Here is your codepen link


问:
Get all values related to id (ASP.NET MVC)
I have two tables Patients and appointments.

Here is model of patients

```<code> public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}
</code>```

Here is Appointment model

```<code> public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}
</code>```

Also I have table to connect patient with appointments (because of one patient may have several appointments)

```<code>public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}
</code>```

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

```<code>  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });
</code>```

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

答:
You can try this.

```<code>var patient = ctx.Patients.Include(a => a.Appointments).FirstOrDefault(x => x.Id == patientId);
</code>```

This will give you the data of patient as well as its appointment which you can access in your view by iterating on appointments list (using patient.Appointments).

Body:
I have two tables Patients and appointments.

Here is model of patients

 public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}

Here is Appointment model

 public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}

Also I have table to connect patient with appointments (because of one patient may have several appointments)

public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

Body:
You can try this.

var patient = ctx.Patients.Include(a => a.Appointments).FirstOrDefault(x => x.Id == patientId);

This will give you the data of patient as well as its appointment which you can access in your view by iterating on appointments list (using patient.Appointments).


问:
Why aren't changes to header files accounted for in the Makefiles of mature C projects?
I have been reading up on make and looking at the Makefiles for popular C projects on GitHub to cement my understanding.

One thing I am struggling to understand is why none of the examples I've looked at (e.g. lz4, linux and FFmpeg) seem to account for header file dependencies.

For my own project, I have header files that contain:

Numeric and string constants

Macros

Short, inline functions

It would seem essential, therefore, to take any changes to these into account when determining whether to recompile.

I have discovered that gcc can automatically generate Makefile fragments from dependencies as in this SO answer but I haven't seen this used in any of the projects I've looked at.

Can you help me understand why these projects apparently ignore header file dependencies?

答:
I'll attempt to answer.

The source distros of some projects include a configure script which creates a makefile from a template/whatever.

So the end user which needs to recompile the package for his/her target just has to do:

```<code>$ configure --try-options-until-it-works
$ make
</code>```

Things can go wrong during the configure phase, but this has nothing to do with the makefile itself. User has to download stuff, adjust paths or configure switches and run again until makefile is successfully generated.

But once the makefile is generated, things should go pretty smooth from there for the user which only needs to build the product once to be able to use it.

A few portion of users will need to change some source code. In that case, they'll have to clean everything, because the makefile provided isn't the way the actual developpers manage their builds. They may use other systems (code::blocks, Ant, gprbuild...) , and just provide the makefile to automate production from scratch and avoid to depend on a complex production system. make is fairly standard even on Windows/MinGW.

Note that there are some filesystems which provide build audit (Clearcase) where the dependencies are automatically managed (clearmake).

If you see the makefile as a batch script to build all the sources, you don't need to bother adding a dependency system using

a template makefile

a gcc -MM command to append dependencies to it (which takes time)

Note that you can build it yourself with some extra work (adding a depend target to your makefile)

Body:
I'll attempt to answer.

The source distros of some projects include a configure script which creates a makefile from a template/whatever.

So the end user which needs to recompile the package for his/her target just has to do:

$ configure --try-options-until-it-works
$ make

Things can go wrong during the configure phase, but this has nothing to do with the makefile itself. User has to download stuff, adjust paths or configure switches and run again until makefile is successfully generated.

But once the makefile is generated, things should go pretty smooth from there for the user which only needs to build the product once to be able to use it.

A few portion of users will need to change some source code. In that case, they'll have to clean everything, because the makefile provided isn't the way the actual developpers manage their builds. They may use other systems (code::blocks, Ant, gprbuild...) , and just provide the makefile to automate production from scratch and avoid to depend on a complex production system. make is fairly standard even on Windows/MinGW.

Note that there are some filesystems which provide build audit (Clearcase) where the dependencies are automatically managed (clearmake).

If you see the makefile as a batch script to build all the sources, you don't need to bother adding a dependency system using

a template makefile

a gcc -MM command to append dependencies to it (which takes time)

Note that you can build it yourself with some extra work (adding a depend target to your makefile)


问:
Cannot get stripe charge work with app engine Golang
So here is my problem, i have been following the github readme for app engine users in order to implement stripe into my app but the thing is that i can’t make it work as it seems that the http.DefaultTransport and http.DefaultClient are not available in App Engine.

I have seen that in the readme you show us how to initialize the Stripe client with app engine but i cannot find any charge card example so this is why i have come to this implementation.

I am used to this problem, since i have been working with app engine for a long time but for some reason i still get this akward error :

cannot use stripe.BackendConfiguration literal (type stripe.BackendConfiguration) as type stripe.Backend in assignment: stripe.BackendConfiguration does not implement stripe.Backend (Call method has pointer receiver)

Here is the code :

```<code>func setStripeChargeClient(context context.Context, key string) *charge.Client {
    c := &charge.Client{}

    var b stripe.Backend
    b = stripe.BackendConfiguration{
        stripe.APIBackend,
        "https://api.stripe.com/v1",
        urlfetch.Client(context),
    }

    c.Key = key
    c.B = b

    return c
}
</code>```

Getting the error on that b assignation …

What i can’t figure it out is why this example seems to work all around the web and does not work in my app, if you could please enlighten me on this one, i would be in your debt hahaha

and then calling it this way

stripeClient := setStripeChargeClient(context, "sk_live_key »)

答:
Ok finally got the solution by doing so : </p>

```<code>func setStripeChargeClient(context context.Context, key string) *charge.Client {
       c := &charge.Client{}

       //SETTING THE CLIENT WITH URL FETCH PROPERLY
       fetch := &http.Client{
              Transport: &urlfetch.Transport{
              Context: context,
        },
       }

     //USE SetHTTPClient method to switch httpClient
     stripe.SetHTTPClient(fetch)

     var b stripe.Backend
     b = &stripe.BackendConfiguration{stripe.APIBackend,
     "https://api.stripe.com/v1",fetch}

     c.Key = key
     c.B = b

     return c
}
</code>```

Body:
So here is my problem, i have been following the github readme for app engine users in order to implement stripe into my app but the thing is that i can’t make it work as it seems that the http.DefaultTransport and http.DefaultClient are not available in App Engine.

I have seen that in the readme you show us how to initialize the Stripe client with app engine but i cannot find any charge card example so this is why i have come to this implementation.

I am used to this problem, since i have been working with app engine for a long time but for some reason i still get this akward error :

cannot use stripe.BackendConfiguration literal (type stripe.BackendConfiguration) as type stripe.Backend in assignment: stripe.BackendConfiguration does not implement stripe.Backend (Call method has pointer receiver)

Here is the code :

func setStripeChargeClient(context context.Context, key string) *charge.Client {
    c := &charge.Client{}

    var b stripe.Backend
    b = stripe.BackendConfiguration{
        stripe.APIBackend,
        "https://api.stripe.com/v1",
        urlfetch.Client(context),
    }

    c.Key = key
    c.B = b

    return c
}

Getting the error on that b assignation …

What i can’t figure it out is why this example seems to work all around the web and does not work in my app, if you could please enlighten me on this one, i would be in your debt hahaha

and then calling it this way

stripeClient := setStripeChargeClient(context, "sk_live_key »)

Body:
Ok finally got the solution by doing so :

func setStripeChargeClient(context context.Context, key string) *charge.Client {
       c := &charge.Client{}

       //SETTING THE CLIENT WITH URL FETCH PROPERLY
       fetch := &http.Client{
              Transport: &urlfetch.Transport{
              Context: context,
        },
       }

     //USE SetHTTPClient method to switch httpClient
     stripe.SetHTTPClient(fetch)

     var b stripe.Backend
     b = &stripe.BackendConfiguration{stripe.APIBackend,
     "https://api.stripe.com/v1",fetch}

     c.Key = key
     c.B = b

     return c
}


问:
typeof 90/'hi' is NaN while typeof (90/'hi') is number. Why so?
I was playing around the NaN of JavaScript and found some strange behavior while using typeof operator on a result of number/string.
why so?</p>

答:
Priority is the answer here:

typeof 90/'hi' becomes 'number'/'hi' that's because typeof 90 is 'number' which gives NaN as final result

You can check the priority table here


问:
Strange Problem with a .NET Windows Service
I have two Windows services written in C# following the same patterns and methodology.

Both services were development tested against a Windows 7 VM and QA tested on Windows Server 2008 VM. Both services have been installed and uninstalled many times under these test environments without issue, however upon installing in the production environment (Windows Server 2008) one of the two services refuses to start.

To install the services we are using InstallUtil.exe with ServiceInstaller and ServiceProcessInstaller components attached to the service.

By all appearances, the failing service installs successfully. InstallUtil.exe reports success and the service appears in the Services snapin. You can also locate the service in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Blah Blah. However, if you attempt to start the service you get the following:

net start blah.blah.exe
"The service name is invalid."

...or going through the Services snapin...
"Windows could not start the "Blah Blah" service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion."

I have added some event logging to the constructor of the service class failing service, but it does not appear to get called.

As this is a production box, there is no Visual Studio on the box and remote debugging is out of the question.

Is there any other way for me to gain debugging info on why the failing service isn't starting?

Is there any other obvious-ish reason that I might see this kind of issue?

Edit: I should have also mentioned.. The only other evidence of a problem in the Windows Event Viewer is two messages in the System log from the Service Control Manager:

"A timeout was reached (30000 milliseconds) while waiting for the Blah Blah service to connect.

"The Blah Blah service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion."

Edit: Resolved
The issue ended up being a combination of a configuration mistake and a bug that was hiding it. See my answer below for more details.

答:
It is possible for this error to occur when

your service is depending on another service/application

or due to invalid app.config configurations

Encountered the same issue when Entity Framework was unable to connect to the database server due to lack of permission.
Better to add a global level error logging mechanism to your application to debug the issue easily.Event Viewer might not reveal exact details in some scenarios.


问:
How to run same syntax on multiple spss files
I have 24 spss files in .sav format in a single folder. All these files have the same structure. I want to run the same syntax on all these files. Is it possible to write a code in spss for this?</p>

答:
If the Syntax you need to run is completely independent of the files then you can either use: INSERT FILE = 'Syntax.sps' or put the code in a macro e.g.

```<code>Define !Syntax ()
 * Put Syntax here
!EndDefine.
</code>```

You can then run either of these 'manually';

```<code>get file = 'file1.sav'.
insert file='syntax.sps'.
save outfile ='file1_v2.sav'.
</code>```

Or

```<code>get file = 'file1.sav'.
!Syntax.
save outfile ='file1_v2.sav'.
</code>```

Or if the files follow a reasonably strict naming structure you can embed either of the above in a simple bit of python;

```<code>Begin Program.
imports spss
for i in range(0, 24 + 1):
 syntax = "get file = 'file" + str(i) + ".sav.\n"
 syntax += "insert file='syntax.sps'.\n"
 syntax += "save outfile ='file1_v2.sav'.\n"
 print syntax
 spss.Submit(syntax)
End Program.
</code>```

Body:
If the Syntax you need to run is completely independent of the files then you can either use: INSERT FILE = 'Syntax.sps' or put the code in a macro e.g.

Define !Syntax ()
 * Put Syntax here
!EndDefine.

You can then run either of these 'manually';

get file = 'file1.sav'.
insert file='syntax.sps'.
save outfile ='file1_v2.sav'.

Or

get file = 'file1.sav'.
!Syntax.
save outfile ='file1_v2.sav'.

Or if the files follow a reasonably strict naming structure you can embed either of the above in a simple bit of python;

Begin Program.
imports spss
for i in range(0, 24 + 1):
 syntax = "get file = 'file" + str(i) + ".sav.\n"
 syntax += "insert file='syntax.sps'.\n"
 syntax += "save outfile ='file1_v2.sav'.\n"
 print syntax
 spss.Submit(syntax)
End Program.


问:
HTML input pattern that consists of 4 numbers and 2 letters at the end
Ive looked around for different validation patterns but didnt find any good examples that would help me create something like that. For example "5676AB".
Needs to have 4 numbers at the beginning, followed by 2 characters (can be uppercase and also lowercase).

If anyone would help me I would be very thankful!

答:
With just HTML you can validate input field  with require and pattern attributes.

Without require you will be able to submit an empty field

See the code snippet below

<!DOCTYPE html>

<form action="">
  Input field: <input type="text" name="country_code" pattern="[0-9]{4}[a-zA-Z]{2}" placeholder="4 digits, 2 letters: 1234AB" required />
  <input type="submit">
</form>

```

Body:
With just HTML you can validate input field  with require and pattern attributes.

Without require you will be able to submit an empty field

See the code snippet below

<!DOCTYPE html>
<html>
<body>

<form action="">
  Input field: <input type="text" name="country_code" pattern="[0-9]{4}[a-zA-Z]{2}" placeholder="4 digits, 2 letters: 1234AB" required />
  <input type="submit">
</form>

</body>
</html>


问:
How to convert an HTML content to PDF without losing the formatting using Java?
I have some HTML content (including formatting tags such as strong, images etc).In my Java code,  I want to convert this HTML content into a PDF document without losing the HTML formatting.

Is there anyway to do it in Java (using iText or any other library)?

答:
I would try DocRaptor.com. It converts html to pdf or html to xls in any language, and since it uses Prince XML (without making you pay the expensive license fee), the quality is a lot better than the other options out there. It's also a web app, so there's nothing to download. Easy way to get around long, frustrating coding.

Here are some examples:
https://docraptor.com/documentation#coding_examples


问:
How to retrieve the changed item in an ObservableList via ListChangeListener
There is ListChangeListener.Change.wasUpdated() which is used to detect changes within elements for ObservableLists created via ObservableList.observableArrayList(Callback<E,Observable[]> extractor).

How do I retrieve the exact item(s) that caused the change to be triggered?

Edit

Maybe the question isn't clear enough, I'll give an example.

```<code>class Foo {
    private StringProperty name = new SimpleStringProperty();
    public final StringProperty nameProperty() { return name; }
    public final String getName() { return name.get(); }
    public final void setName(String n) { name.set(n); }
    public Foo(String fooName) { setName(fooName); }
}

// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener(new ListChangeListener<Foo>() {
     public void onChanged(Change<Foo> c) {
         while (c.next()) {
            if (c.wasUpdated()) {
                // One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
            }
        }
    }
});

fooB.setName("Mickey");
</code>```

fooB.setName() will trigger a change in the ListChangeListener, which the wasUpdated() condition would return true. However, I have no way to know that it is fooB which has changed within the listener.

This may seem trivial, but I have a map application where the list stores the things which the map has to render. When one of the item changes its position (i.e. lat/long), I need to re-plot on the map. If I have no idea which item has changed location, I'll have to redraw everything that I already have.

答:
You can get the index(es) of the item(s) that were changed, which gives you some useful information:

```<code>import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;

public class ListUpdateTest {

    public static void main(String[] args) {

        ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
        Foo fooA = new Foo("Hello");
        Foo fooB = new Foo("Kitty");
        fooList.add(fooA);
        fooList.add(fooB);

        fooList.addListener((Change<? extends Foo> c) -> {
             while (c.next()) {
                if (c.wasUpdated()) {
                    int start = c.getFrom() ;
                    int end = c.getTo() ;
                    for (int i = start ; i < end ; i++) {
                        System.out.println("Element at position "+i+" was updated to: " +c.getList().get(i).getName() );
                    }
                }
            }
        });

        fooB.setName("Mickey");
    }

    public static class Foo {
        private StringProperty name = new SimpleStringProperty();
        public final StringProperty nameProperty() { return name; }
        public final String getName() { return name.get(); }
        public final void setName(String n) { name.set(n); }
        public Foo(String fooName) { setName(fooName); }
    }
}
</code>```

Note that you can't determine from the list change event the actual properties that changed in those list elements (so, if your extractor pointed to two or more properties, there's no way to find which of those properties changed), and there is no way to get the previous value. This may be enough for your use case, though.

Body:
There is ListChangeListener.Change.wasUpdated() which is used to detect changes within elements for ObservableLists created via ObservableList.observableArrayList(Callback<E,Observable[]> extractor).

How do I retrieve the exact item(s) that caused the change to be triggered?

Edit

Maybe the question isn't clear enough, I'll give an example.

class Foo {
    private StringProperty name = new SimpleStringProperty();
    public final StringProperty nameProperty() { return name; }
    public final String getName() { return name.get(); }
    public final void setName(String n) { name.set(n); }
    public Foo(String fooName) { setName(fooName); }
}

// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);

fooList.addListener(new ListChangeListener<Foo>() {
     public void onChanged(Change<Foo> c) {
         while (c.next()) {
            if (c.wasUpdated()) {
                // One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
            }
        }
    }
});

fooB.setName("Mickey");

fooB.setName() will trigger a change in the ListChangeListener, which the wasUpdated() condition would return true. However, I have no way to know that it is fooB which has changed within the listener.

This may seem trivial, but I have a map application where the list stores the things which the map has to render. When one of the item changes its position (i.e. lat/long), I need to re-plot on the map. If I have no idea which item has changed location, I'll have to redraw everything that I already have.

Body:
You can get the index(es) of the item(s) that were changed, which gives you some useful information:

import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;

public class ListUpdateTest {

    public static void main(String[] args) {

        ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
        Foo fooA = new Foo("Hello");
        Foo fooB = new Foo("Kitty");
        fooList.add(fooA);
        fooList.add(fooB);

        fooList.addListener((Change<? extends Foo> c) -> {
             while (c.next()) {
                if (c.wasUpdated()) {
                    int start = c.getFrom() ;
                    int end = c.getTo() ;
                    for (int i = start ; i < end ; i++) {
                        System.out.println("Element at position "+i+" was updated to: " +c.getList().get(i).getName() );
                    }
                }
            }
        });

        fooB.setName("Mickey");
    }

    public static class Foo {
        private StringProperty name = new SimpleStringProperty();
        public final StringProperty nameProperty() { return name; }
        public final String getName() { return name.get(); }
        public final void setName(String n) { name.set(n); }
        public Foo(String fooName) { setName(fooName); }
    }
}

Note that you can't determine from the list change event the actual properties that changed in those list elements (so, if your extractor pointed to two or more properties, there's no way to find which of those properties changed), and there is no way to get the previous value. This may be enough for your use case, though.


问:
PHP Securely include files + handle invalid parameters
I'm having a little problem. I want to securely include files based on the $_GET Parameter from a subdirectory + handle if the parameter is not valid.

```<code> <?php
if(isset($_GET['p']) && $_GET['p'] == 'fahrzeuge'){
        include 'includes/cars.php';
    }
  if(isset($_GET['p']) && $_GET['p'] == 'impressum'){
        include 'includes/impressum.php';
    }
    if(isset($_GET['p']) && $_GET['p'] == 'home'){
            include 'includes/home.php';
        }
      if(isset($_GET['p']) && $_GET['p'] == 'anfahrt'){
            include 'includes/anfahrt.php';
        }
        if(isset($_GET['p']) && $_GET['p'] == 'about'){
                include 'includes/about.php';
            }

?>
</code>```

This is my Code. Sorry I know it is a noob way of solving this. How can I improve it? Any Suggestions/Help would be highly appreciated

答:
I would use a ternary to set a variable that tells the page what to include.

This is very similar to Ofir Baruch's answer, except much shorter.

```<code>$pages = array('about','contact','home');

$p = isset($_GET['p']) && in_array($_GET['p'], $pages)? $_GET['p'] : 'home';
include "includes/{$p}.php";
</code>```

Basically, you have an array of pages that are possible. In the ternary, we check if $_GET['p'] is set (isset()), AND we check if the value it contains is in the array. If it is, we use $_GET['p'] as $p, if it is not, we set $p to home, this means that home will always be the default if $_GET['p'] is not set, or not a valid page as per the array.

Body:
I'm having a little problem. I want to securely include files based on the $_GET Parameter from a subdirectory + handle if the parameter is not valid.

 <?php
if(isset($_GET['p']) && $_GET['p'] == 'fahrzeuge'){
        include 'includes/cars.php';
    }
  if(isset($_GET['p']) && $_GET['p'] == 'impressum'){
        include 'includes/impressum.php';
    }
    if(isset($_GET['p']) && $_GET['p'] == 'home'){
            include 'includes/home.php';
        }
      if(isset($_GET['p']) && $_GET['p'] == 'anfahrt'){
            include 'includes/anfahrt.php';
        }
        if(isset($_GET['p']) && $_GET['p'] == 'about'){
                include 'includes/about.php';
            }

?>

This is my Code. Sorry I know it is a noob way of solving this. How can I improve it? Any Suggestions/Help would be highly appreciated

Body:
I would use a ternary to set a variable that tells the page what to include.

This is very similar to Ofir Baruch's answer, except much shorter.

$pages = array('about','contact','home');

$p = isset($_GET['p']) && in_array($_GET['p'], $pages)? $_GET['p'] : 'home';
include "includes/{$p}.php";

Basically, you have an array of pages that are possible. In the ternary, we check if $_GET['p'] is set (isset()), AND we check if the value it contains is in the array. If it is, we use $_GET['p'] as $p, if it is not, we set $p to home, this means that home will always be the default if $_GET['p'] is not set, or not a valid page as per the array.


问:
How to return multiple values from a function in Kotlin like we do in Swift?
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

```<code>func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}
</code>```

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

答:
There is no tuple in Kotlin. Alternatively, you can use data class with destructuring declaration.

```<code>data class Time(val hour: Int, val minute: Int, val second: Int)

func getTime(): Time {
    ...
    return Time(hour, minute, second)
}

//Usage
val time = getTime()
println("${time.hour}:${time.minute}:${time.second}")
//Or
val (hour, minute, second) = getTime()
println("${hour}:${minute}:${second}")
</code>```

If you don't want to create data class for each specific case, you may create some generic data classes and use typealias for clarity.

```<code>data class Two<A, B>(val a: A, val b: B)
data class Three<A, B, C>(val a: A, val b: B, val c: C)
data class Four<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
...

typealias Time = Three<Int, Int, Int>
</code>```

But, obviously, the disadvantage is that you must make use of destructuring declaration in order to give it a proper property name.

```<code>val time = getTime()
println("${time.a}:${time.b}:${time.c}")

val (hour, minute, second) = getTime()    //destructuring declaration
println("${hour}:${minute}:${second}")
</code>```

Body:
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

Body:
There is no tuple in Kotlin. Alternatively, you can use data class with destructuring declaration.

data class Time(val hour: Int, val minute: Int, val second: Int)

func getTime(): Time {
    ...
    return Time(hour, minute, second)
}

//Usage
val time = getTime()
println("${time.hour}:${time.minute}:${time.second}")
//Or
val (hour, minute, second) = getTime()
println("${hour}:${minute}:${second}")

If you don't want to create data class for each specific case, you may create some generic data classes and use typealias for clarity.

data class Two<A, B>(val a: A, val b: B)
data class Three<A, B, C>(val a: A, val b: B, val c: C)
data class Four<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
...

typealias Time = Three<Int, Int, Int>

But, obviously, the disadvantage is that you must make use of destructuring declaration in order to give it a proper property name.

val time = getTime()
println("${time.a}:${time.b}:${time.c}")

val (hour, minute, second) = getTime()    //destructuring declaration
println("${hour}:${minute}:${second}")


答: Take a look at the following blog post from the authoritative source: http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html</p>

Title: Injecting the repository classes in a Custom Action Filter

Body:
I have a custom action filter attribute that checks if the user has it's service active and if not the filter automatically redirect the user to a renew page.

Recently we did a re-enginering of our code and we introduced the repository pattern. Before of this we used the repository classes directly in the custom action filter like

private OrderRepository _orderRepository = new OrderRepository();

I am guessing which is the right way to inject repository classes inside the custom action filter now that we are using this pattern.

Thanks a lot