问:
Unable to Open .DBF Files in Windows 7 That Had Worked Under XP
I have a VB.NET application that will let me preview .DBF files that come in from some of our clients. The application then attempts to spit out a CSV from this file that we can then use in our various environments.
This application worked under Windows XP 32 bit. Our company recently upgraded most of us to Windows 7 x64 which has caused this application to fail. I verified that the target build for this application is x86 and not "any CPU" and rebuilt the app but same issues occur.

It originally used System.Data.Odbc and connection.ConnectionString = "Driver={Microsoft dBASE VFP Driver (*.dbf)};SourceType = DBF;SourceDB=" & dbfSourcePath & ";Exclusive=No; Collate=Machine;BACKGROUNDFETCH=NO;".
The location of the failure is at connection.Open(). The error given is: "ERROR [IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function".

I noticed that the drivers for VFP were not installed and that the Access DBF drivers did not work similar to the post here. The fix listed there is to install VFPro SP2, however, we do not have any FoxPro installs to install a service pack on top of. I then tried to install the OLEDB driver for VFP 9.0 and am now using System.Data.OleDb and connection.ConnectionString = "Provider=VFPOLEDB.1;SourceDB=" & dbfSourcePath & ";" but it now tells me that the connection.Open() line has this error: "Feature is not available".

I am at a complete loss as to how to get this application to work under Windows 7 x64.
Below are the 2 variants of the code with the file open path removed for readability (I have verified the path and file exist):

ODBC version:

```<code>Imports System.Data.Odbc
Dim strSelect As String
strSelect = "SELECT * FROM " & dbfSourceName
Dim connection As New Odbc.OdbcConnection
Dim adp As New Data.Odbc.OdbcDataAdapter
connection.ConnectionString = "Driver={Microsoft dBASE VFP Driver (*.dbf)};SourceType = DBF;SourceDB=" & dbfSourcePath & ";Exclusive=No; Collate=Machine;BACKGROUNDFETCH=NO;"
Dim command As New OdbcCommand(strSelect, connection)
connection.Open()          ' Here is where it throws the error.
</code>```

OLEDB version:

```<code>Imports System.Data.OleDb
Dim strSelect As String
strSelect = "SELECT * FROM " & dbfSourceName
Dim connection As OleDbConnection = New OleDbConnection()
Dim adp As New Data.OleDb.OleDbDataAdapter
connection.ConnectionString = "Provider=VFPOLEDB.1;SourceDB=" & dbfSourcePath & ";"
Dim Command As New OleDbCommand(strSelect, connection)
connection.Open()          'Error occurs here.
</code>```

How can I use either an OLEDB or ODBC connection to open these .DBF files under Windows 7 x64?

答:
Have you tried a few alternate connection strings? Take a look at www.connectionstrings.com/dbf-foxpro

```<code>connection.ConnectionString = _
  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
  dbfSourcePath & ";Extended Properties=dBASE IV;"
</code>```

Also see the note on using Jet for Access on 64 bit systems

Update:
As an alternative to using the Jet driver, you can access the DBF directly, fortunately the file format is relatively simple. Here is an existing Code Project solution that demonstrates this direct access.

http://www.codeproject.com/KB/bugs/LoadDBF.aspx

Body:
I have a VB.NET application that will let me preview .DBF files that come in from some of our clients. The application then attempts to spit out a CSV from this file that we can then use in our various environments.
This application worked under Windows XP 32 bit. Our company recently upgraded most of us to Windows 7 x64 which has caused this application to fail. I verified that the target build for this application is x86 and not "any CPU" and rebuilt the app but same issues occur.

It originally used System.Data.Odbc and connection.ConnectionString = "Driver={Microsoft dBASE VFP Driver (*.dbf)};SourceType = DBF;SourceDB=" & dbfSourcePath & ";Exclusive=No; Collate=Machine;BACKGROUNDFETCH=NO;".
The location of the failure is at connection.Open(). The error given is: "ERROR [IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function".

I noticed that the drivers for VFP were not installed and that the Access DBF drivers did not work similar to the post here. The fix listed there is to install VFPro SP2, however, we do not have any FoxPro installs to install a service pack on top of. I then tried to install the OLEDB driver for VFP 9.0 and am now using System.Data.OleDb and connection.ConnectionString = "Provider=VFPOLEDB.1;SourceDB=" & dbfSourcePath & ";" but it now tells me that the connection.Open() line has this error: "Feature is not available".

I am at a complete loss as to how to get this application to work under Windows 7 x64.
Below are the 2 variants of the code with the file open path removed for readability (I have verified the path and file exist):

ODBC version:

Imports System.Data.Odbc
Dim strSelect As String
strSelect = "SELECT * FROM " & dbfSourceName
Dim connection As New Odbc.OdbcConnection
Dim adp As New Data.Odbc.OdbcDataAdapter
connection.ConnectionString = "Driver={Microsoft dBASE VFP Driver (*.dbf)};SourceType = DBF;SourceDB=" & dbfSourcePath & ";Exclusive=No; Collate=Machine;BACKGROUNDFETCH=NO;"
Dim command As New OdbcCommand(strSelect, connection)
connection.Open()          ' Here is where it throws the error.

OLEDB version:

Imports System.Data.OleDb
Dim strSelect As String
strSelect = "SELECT * FROM " & dbfSourceName
Dim connection As OleDbConnection = New OleDbConnection()
Dim adp As New Data.OleDb.OleDbDataAdapter
connection.ConnectionString = "Provider=VFPOLEDB.1;SourceDB=" & dbfSourcePath & ";"
Dim Command As New OleDbCommand(strSelect, connection)
connection.Open()          'Error occurs here.

How can I use either an OLEDB or ODBC connection to open these .DBF files under Windows 7 x64?

Body:
Have you tried a few alternate connection strings? Take a look at www.connectionstrings.com/dbf-foxpro

connection.ConnectionString = _
  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
  dbfSourcePath & ";Extended Properties=dBASE IV;"

Also see the note on using Jet for Access on 64 bit systems

Update:
As an alternative to using the Jet driver, you can access the DBF directly, fortunately the file format is relatively simple. Here is an existing Code Project solution that demonstrates this direct access.

http://www.codeproject.com/KB/bugs/LoadDBF.aspx


来源: stackexchange

问:
Need help finding what's wrong with my date range creation
I use Lodash and Momentjs to create a JSON date range with this structure :
{"days":[], "months": []}

Problem is :

At the moment dates are created but they are created more than necessary there is a lot of duplicates

Problem applies for months array and days array

Was like 2 days on this method but can't find why it doesn't work.

```<code>var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');

while (currDate.add(1, 'days').diff(lastDate) < 0) {
  var month = {};
  month.name = currDate.clone().format('MMMM');
  month.year = currDate.clone().format('YYYY');
  var currentMonthDaysInTotal = moment(month.year + "-" + moment().month(currDate), "YYYY-MM").daysInMonth();
  var daysIndex = 1;
  while (daysIndex <= currentMonthDaysInTotal) {
    var newDateForList = moment([month.year, moment().month(month.name).format('M'), daysIndex]);
    if (newDateForList >= startDate && newDateForList <= endDate) {
      range.days.push(newDateForList);
    }
    daysIndex++;
  }
  if (months.length === 0) {
    months.push(month);
  }
  //regarder avec mitch
  if (_.findIndex(range.months, function(o) {
      return o.name !== month.name;
    }) === -1) {
    range.months.push(month);
  }
}
console.log(range);
</code>```

Here is a JSFiddle with my code for what I'm trying to do :
https://jsfiddle.net/Keldarne/LdLc6u0t/

答:
Is this along the right lines of what you wanted?

var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');

var monthYear = undefined;
while (currDate.add(1, 'days').diff(lastDate) < 0) {
  range.days.push(currDate.clone());
  var month = currDate.clone().format('MMMM'),
      year = currDate.clone().format('YYYY');
  if( month.concat( year ) !== monthYear ){
    range.months.push({
      name: month,
      year: year
    });
  }
  monthYear = month.concat( year );
}
console.log(range);```

ContentLicense: CC BY-SA 3.0

Body:
I use Lodash and Momentjs to create a JSON date range with this structure :
{"days":[], "months": []}

Problem is :

At the moment dates are created but they are created more than necessary there is a lot of duplicates

Problem applies for months array and days array

Was like 2 days on this method but can't find why it doesn't work.

var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');

while (currDate.add(1, 'days').diff(lastDate) < 0) {
  var month = {};
  month.name = currDate.clone().format('MMMM');
  month.year = currDate.clone().format('YYYY');
  var currentMonthDaysInTotal = moment(month.year + "-" + moment().month(currDate), "YYYY-MM").daysInMonth();
  var daysIndex = 1;
  while (daysIndex <= currentMonthDaysInTotal) {
    var newDateForList = moment([month.year, moment().month(month.name).format('M'), daysIndex]);
    if (newDateForList >= startDate && newDateForList <= endDate) {
      range.days.push(newDateForList);
    }
    daysIndex++;
  }
  if (months.length === 0) {
    months.push(month);
  }
  //regarder avec mitch
  if (_.findIndex(range.months, function(o) {
      return o.name !== month.name;
    }) === -1) {
    range.months.push(month);
  }
}
console.log(range);

Here is a JSFiddle with my code for what I'm trying to do :
https://jsfiddle.net/Keldarne/LdLc6u0t/


问:
How use dynamic scheduler in spring framework?
I'm using Spring Security 4.2. I want to block user for 15 minutes after 3 login failure. For blocking user, change user status to BLOCK. I want to return it to ACTIVE after 15 minutes.

I need a dynamic task scheduler that run after 15 minutes and change user status.

Important: I don't want to run method every 15 minutes, I want to run method after 15 minutes if needed.

How do I implement it?

答:
I have some approach. I guess that you should use User class like following:

```<code>class User {
    // ...
    private Status status;
    private LocalDateTime lastUpdated;
    // ...
}
</code>```

So that, you should update status and lastUpdated fields during a user blocking.

```<code>@Service
public class UserService {

    private UserRepository userRepository;

    @Transactional
    public void block(User user) {
        user.setStatus(Status.BLOCKED);
        user.setLastUpdated(LocalDateTime.now());
        userRepository.save(user);
    }
}
</code>```

After that you can use Spring Scheduler which run every minute and finds users that were blocked 15 minutes ago and sets status to ACTIVE.

```<code>@Component
public class UserActivator {

    private boolean activateUsers = false;

    @Scheduled("0 * * * * *")
    public void activateUsers() {
        if (activateUsers) {
            // find users that were deactivated 15 minutes ago and change status to active
        }
    }
}
</code>```

Do not forget to add @EnableScheduling to your Spring config.

Body:
I have some approach. I guess that you should use User class like following:

class User {
    // ...
    private Status status;
    private LocalDateTime lastUpdated;
    // ...
}

So that, you should update status and lastUpdated fields during a user blocking.

@Service
public class UserService {

    private UserRepository userRepository;

    @Transactional
    public void block(User user) {
        user.setStatus(Status.BLOCKED);
        user.setLastUpdated(LocalDateTime.now());
        userRepository.save(user);
    }
}

After that you can use Spring Scheduler which run every minute and finds users that were blocked 15 minutes ago and sets status to ACTIVE.

@Component
public class UserActivator {

    private boolean activateUsers = false;

    @Scheduled("0 * * * * *")
    public void activateUsers() {
        if (activateUsers) {
            // find users that were deactivated 15 minutes ago and change status to active
        }
    }
}

Do not forget to add @EnableScheduling to your Spring config.


问:
Turning a car field into a factor, in the right order
I have a column that looks like this:

```<code> $ Stage     : chr  "final" "final" "final" "final" ...
</code>```

The values are final, first, resub.

I want to convert it into a factor, specifically ordered like this:

```<code>first, resub, final
</code>```

Why that order? Because I use it in a ggplot later and they are displaying in the wrong order.

答:
As far as I know you can also convert to factor and order as you want in one of the layers in ggplot() function but it can be done earlier. Everything is easier with dplyr.

```<code>>str(mydf$anim3) # one column from my df
 chr [1:5] "A" "A" "B" "C" "C"

>mydf <- mydf %>% mutate_if(is.character,as.factor)
>str(mydf$anim3)
 Factor w/ 3 levels "A","B","C": 1 1 2 3 3

>levels(mydf3$anim3) #order of our levels
 [1] "A" "B" "C"

>str(factor(mydf$anim3,levels(mydf3$anim3)[c(3,1,2)])) #you can order levels whatever you want using this
 Factor w/ 3 levels "C","A","B": 2 2 3 1 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column that looks like this:

 $ Stage     : chr  "final" "final" "final" "final" ...

The values are final, first, resub.

I want to convert it into a factor, specifically ordered like this:

first, resub, final

Why that order? Because I use it in a ggplot later and they are displaying in the wrong order.

Body:
As far as I know you can also convert to factor and order as you want in one of the layers in ggplot() function but it can be done earlier. Everything is easier with dplyr.

>str(mydf$anim3) # one column from my df
 chr [1:5] "A" "A" "B" "C" "C"

>mydf <- mydf %>% mutate_if(is.character,as.factor)
>str(mydf$anim3)
 Factor w/ 3 levels "A","B","C": 1 1 2 3 3

>levels(mydf3$anim3) #order of our levels
 [1] "A" "B" "C"

>str(factor(mydf$anim3,levels(mydf3$anim3)[c(3,1,2)])) #you can order levels whatever you want using this
 Factor w/ 3 levels "C","A","B": 2 2 3 1 1


问:
How to convert an IOrderedEnumerable<char> to string in c#?
I need to sort a string alphabetically. The most common solution I have found is to use linq:

```<code>var sortedString = unsortedString.OrderBy(c => c);
</code>```

The problem I have with this solution is that the result is not a string. The result is an IOrderedEnumerable< char > which needs to be converted. This does not work:

```<code>var sortedString = unsortedString.OrderBy(c => c).ToString();
</code>```

答:
Another way is String.Concat which uses a StringBuilder:

```<code>string sortedString = String.Concat(unsortedString.OrderBy(c => c));
</code>```

or String.Join (i prefer Concat without a delimiter):

```<code>string sortedString = String.Join("", unsortedString.OrderBy(c => c));
</code>```

Body:
I need to sort a string alphabetically. The most common solution I have found is to use linq:

var sortedString = unsortedString.OrderBy(c => c);

The problem I have with this solution is that the result is not a string. The result is an IOrderedEnumerable< char > which needs to be converted. This does not work:

var sortedString = unsortedString.OrderBy(c => c).ToString();

Body:
Another way is String.Concat which uses a StringBuilder:

string sortedString = String.Concat(unsortedString.OrderBy(c => c));

or String.Join (i prefer Concat without a delimiter):

string sortedString = String.Join("", unsortedString.OrderBy(c => c));


问:
How to convert text fields into numeric/vector space for a SVM in R Studio?
I am attempting to train a Support Vector Machine to aid in the detection of similarity between strings. My training data consists of two text fields and a third field that contains 0 or 1 to indicate similarity. This last field was calculated with the help of an edit distance operation. I know that I need to convert the two text fields to numeric values before continuing. I am hoping to find out what is the best method to achieve this?

The training data looks like:

```<code>ID          MAKTX_Keyword       PH_Level_04_Keyword   Result
266325638   AMLODIPINE          AMLODIPINE              0
724712821   IRBESARTANHCTZ      IRBESARTANHCTZ          0
567428641   RABEPRAZOLE         RABEPRAZOLE             0
137472217   MIRTAZAPINE         MIRTAZAPINE             0
175827784   FONDAPARINUX        ARIXTRA                 1
456372747   VANCOMYCIN          VANCOMYCIN              0
653832438   BRUFEN              IBUPROFEN               1
917575539   POTASSIUM           POTASSIUM               0
222949123   DIOSMINHESPERIDIN   DIOSMINHESPERIDIN       0
892725684   IBUPROFEN           IBUPROFEN               0
</code>```

I have been experimenting with the text2vec library, using this useful vignette as a guide. In doing so, I can presumably represent one of the fields in vector space.

But how can I use this library to manage both text fields at the same time?

Should I concatenate the two string fields into a single field?

Is text2vec the best approach to take?

The code that will be used to manage one of the fields:

```<code>library(text2vec)
library(data.table)

preproc_func = tolower
token_func = word_tokenizer

it_train = itoken(Train_PRDHA_String.df$MAKTX_Keyword,
                  preprocessor = preproc_func,
                  tokenizer = token_func,
                  ids = Train_PRDHA_String.df$ID,
                  progressbar = TRUE)
vocab = create_vocabulary(it_train)

vectorizer = vocab_vectorizer(vocab)
t1 = Sys.time()
dtm_train = create_dtm(it_train, vectorizer)
print(difftime(Sys.time(), t1, units = 'sec'))

dim(dtm_train)
identical(rownames(dtm_train), Train_PRDHA_String.df$id)
</code>```

答:
One way to embed docs into the same space is to learn vocabulary from both columns:

```<code>preproc_func = tolower
token_func = word_tokenizer
union_txt = c(Train_PRDHA_String.df$MAKTX_Keyword, Train_PRDHA_String.df$PH_Level_04_Keyword)
it_train = itoken(union_txt,
                  preprocessor = preproc_func,
                  tokenizer = token_func,
                  ids = Train_PRDHA_String.df$ID,
                  progressbar = TRUE)
vocab = create_vocabulary(it_train)
vectorizer = vocab_vectorizer(vocab)

it1 = itoken(Train_PRDHA_String.df$MAKTX_Keyword, preproc_func,
             token_func, ids = Train_PRDHA_String.df$ID)
dtm_train_1 = create_dtm(it1, vectorizer)

it2 = itoken(Train_PRDHA_String.df$PH_Level_04_Keyword, preproc_func,
             token_func, ids = Train_PRDHA_String.df$ID)
dtm_train_2 = create_dtm(it2, vectorizer)
</code>```

And after that you can combine them into a single matrix:

```<code>dtm_train = cbind(dtm_train_1, dtm_train_2)
</code>```

However if you want to solve problem of duplicate detection I suggest to use char_tokenizer with ngram > 1 (say ngram = c(3, 3)). And check great stringdist package. I suppose you received Result with some manual human work. Because if it is just edit distance, algorithm will learn at most how edit distance works.

Body:
I am attempting to train a Support Vector Machine to aid in the detection of similarity between strings. My training data consists of two text fields and a third field that contains 0 or 1 to indicate similarity. This last field was calculated with the help of an edit distance operation. I know that I need to convert the two text fields to numeric values before continuing. I am hoping to find out what is the best method to achieve this?

The training data looks like:

ID          MAKTX_Keyword       PH_Level_04_Keyword   Result
266325638   AMLODIPINE          AMLODIPINE              0
724712821   IRBESARTANHCTZ      IRBESARTANHCTZ          0
567428641   RABEPRAZOLE         RABEPRAZOLE             0
137472217   MIRTAZAPINE         MIRTAZAPINE             0
175827784   FONDAPARINUX        ARIXTRA                 1
456372747   VANCOMYCIN          VANCOMYCIN              0
653832438   BRUFEN              IBUPROFEN               1
917575539   POTASSIUM           POTASSIUM               0
222949123   DIOSMINHESPERIDIN   DIOSMINHESPERIDIN       0
892725684   IBUPROFEN           IBUPROFEN               0

I have been experimenting with the text2vec library, using this useful vignette as a guide. In doing so, I can presumably represent one of the fields in vector space.

But how can I use this library to manage both text fields at the same time?

Should I concatenate the two string fields into a single field?

Is text2vec the best approach to take?

The code that will be used to manage one of the fields:

library(text2vec)
library(data.table)

preproc_func = tolower
token_func = word_tokenizer

it_train = itoken(Train_PRDHA_String.df$MAKTX_Keyword,
                  preprocessor = preproc_func,
                  tokenizer = token_func,
                  ids = Train_PRDHA_String.df$ID,
                  progressbar = TRUE)
vocab = create_vocabulary(it_train)

vectorizer = vocab_vectorizer(vocab)
t1 = Sys.time()
dtm_train = create_dtm(it_train, vectorizer)
print(difftime(Sys.time(), t1, units = 'sec'))

dim(dtm_train)
identical(rownames(dtm_train), Train_PRDHA_String.df$id)

Body:
One way to embed docs into the same space is to learn vocabulary from both columns:

preproc_func = tolower
token_func = word_tokenizer
union_txt = c(Train_PRDHA_String.df$MAKTX_Keyword, Train_PRDHA_String.df$PH_Level_04_Keyword)
it_train = itoken(union_txt,
                  preprocessor = preproc_func,
                  tokenizer = token_func,
                  ids = Train_PRDHA_String.df$ID,
                  progressbar = TRUE)
vocab = create_vocabulary(it_train)
vectorizer = vocab_vectorizer(vocab)

it1 = itoken(Train_PRDHA_String.df$MAKTX_Keyword, preproc_func,
             token_func, ids = Train_PRDHA_String.df$ID)
dtm_train_1 = create_dtm(it1, vectorizer)

it2 = itoken(Train_PRDHA_String.df$PH_Level_04_Keyword, preproc_func,
             token_func, ids = Train_PRDHA_String.df$ID)
dtm_train_2 = create_dtm(it2, vectorizer)

And after that you can combine them into a single matrix:

dtm_train = cbind(dtm_train_1, dtm_train_2)

However if you want to solve problem of duplicate detection I suggest to use char_tokenizer with ngram > 1 (say ngram = c(3, 3)). And check great stringdist package. I suppose you received Result with some manual human work. Because if it is just edit distance, algorithm will learn at most how edit distance works.


问:
ROS ERROR : 0 , FRM-10044 : Cannot create file
In oracle forms builder 11g,if i add new field and save the forms builder, then the above error is showing and its not allowing me to save the form.

答: No other option left, other than re-creating a new form again. I have faced a similar case and it worked for me by copying the entire objects to a new form (Data Block, Trigger, Program Units, LOV's, et...). It worked well.</p>


问:
Passing data From ListView Item to next Form
I know how to send data from an Entry, Label to the next Form , but how can i do this with a ListView.
I want a simple direct approach.

My XAML code :

```<code><ListView x:Name="MyClientslistView" HasUnevenRows="true"  ItemTapped="OnSalesReport">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                            <StackLayout Orientation="Vertical" VerticalOptions="Center"  Margin="5" >
                                <Label Text="{Binding client_name}" TextColor="#A7A392" />
                                <Label Text="{Binding client_address}" TextColor="Black" />
                                <Label Text="{Binding client_phone}"  TextColor="Black" />
                                <Label Text="{Binding client_email}"  TextColor="Black" />
                                <Label Text="{Binding AssignStatus}"  TextColor="Black" />
                                <Label Text="{Binding assignmentComments}"  TextColor="Black" />
                            </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

I already have loaded data from JSON to the ListView , now currently i want to move each ID on he Item to the Next Form , how can i tackle that ?

答:
You can get the item from ItemTapped listener. In your case use below solution.

```<code>void OnSalesReport(object sender, Xamarin.Forms.ItemTappedEventArgs e)
    {
        YourItemModel item = (YourItemModel)((ListView)sender).SelectedItem;
        ((ListView)sender).SelectedItem = null;
        Navigation.PushAsync(new NextPage(item));
    }
</code>```

Body:
I know how to send data from an Entry, Label to the next Form , but how can i do this with a ListView.
I want a simple direct approach.

My XAML code :

<ListView x:Name="MyClientslistView" HasUnevenRows="true"  ItemTapped="OnSalesReport">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>

                            <StackLayout Orientation="Vertical" VerticalOptions="Center"  Margin="5" >

                            </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

I already have loaded data from JSON to the ListView , now currently i want to move each ID on he Item to the Next Form , how can i tackle that ?

Body:
You can get the item from ItemTapped listener. In your case use below solution.

void OnSalesReport(object sender, Xamarin.Forms.ItemTappedEventArgs e)
    {
        YourItemModel item = (YourItemModel)((ListView)sender).SelectedItem;
        ((ListView)sender).SelectedItem = null;
        Navigation.PushAsync(new NextPage(item));
    }


问:
How define a couple of setIntervals and clear them with delay
I need to randomly change characters of a text and after some delay fix them.

There is my code:

SOME TEXT

```

It seems i have no a good understanding of how setInterval work! :(

EDIT:

With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.

Can someone guide me?

答:
Related to this question problem was wrong way to passing arguments to setInterval().the callback function i passed to setInterval() maintains a reference to "i" rather than the snapshot value of "i" as it existed during each particular iteration...

SOME TEXT

```

Body:
I need to randomly change characters of a text and after some delay fix them.

There is my code:

SOME TEXT

It seems i have no a good understanding of how setInterval work! :(

EDIT:

With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.

Can someone guide me?

Body:
Related to this question problem was wrong way to passing arguments to setInterval().the callback function i passed to setInterval() maintains a reference to "i" rather than the snapshot value of "i" as it existed during each particular iteration...

<h1 id="text" style="margin-top:100px;">SOME TEXT</h1>

<script>
    var text = document.getElementById("text").innerHTML.split("");
    var myArr = document.getElementById("text").innerHTML.split("");
    for (i = 0; i < text.length; i++) {
        var handle = setInterval(function (k) { xyz(k) }, 100,i);

        setTimeout(function (handle, i) {
            console.log(i);
            console.log(text[i]);
            myArr[i] = text[i];
            clearInterval(handle);
        }, (i) * 1000,handle,i);
    }
    function xyz(index) {
        myArr[index] = String.fromCharCode(Math.random() * 26 + 65);
        document.getElementById("text").innerHTML = myArr.toString();
    }
</script>


问:
Upload HTML catalogs for a content type
We have a couple of product catalogs which are interactive. This means that a vendor took our pages and created a nice "turn the page with the cursor" type of digital pager.

They sent this in a form of a static HTML page with index.html as an entry point and a lot of subdirectories. We have to host these static pages.

This kind of catalog digitalization might happen in the future and I created a new Content Type for it so maintainers of the site won't bother me to upload these things manually via FTP.

My problem is that this is a complete folder structure and not just 1 file.

My question: How can I "attach" a complete static HTML page structure in just one field of a Content Type? If it's not possible, how would you do it?

答:
Add one file field for uploading compressed set of files (archive) there. Then use i.e. hook_node_update()

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_update/7.x

to place your code which would unzip the archive in appropriate dir when ever node in your content type is updated.

http://php.net/manual/en/ziparchive.extractto.php

or call shell command to unzip the archive...

Title: Upload HTML catalogs for a content type


问:
How to search same fiile and compare in pandas
I have some directory and files

```<code>Directory1

file1
file2
file3

Directory2

file1
file2
file3
</code>```

I would like to compare each file in each directory.

I tried

```<code>'glob.glob'
</code>```

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?

答:
You can generate a md5 checksum of the file content in a dict and search for equals checksums.</p>

```<code>import glob
import hashlib

example = dict(('%s' % _, hashlib.md5(open('%s' % _, 'rb').read()).hexdigest()) for _ in glob.glob('*'))

{'file1': 'b026324c6904b2a9cb4b88d6d61c81d1', 'file2': '26ab0db90d72e28ad0ba1e22ee510510', 'file3': '26ab0db90d72e28ad0ba1e22ee510510', 'file4': '48a24b70a0b376535542b996af517398'}
</code>```

Body:
I have some directory and files

Directory1

file1
file2
file3

Directory2

file1
file2
file3

I would like to compare each file in each directory.

I tried

'glob.glob'

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?

Body:
You can generate a md5 checksum of the file content in a dict and search for equals checksums.

import glob
import hashlib

example = dict(('%s' % _, hashlib.md5(open('%s' % _, 'rb').read()).hexdigest()) for _ in glob.glob('*'))

{'file1': 'b026324c6904b2a9cb4b88d6d61c81d1', 'file2': '26ab0db90d72e28ad0ba1e22ee510510', 'file3': '26ab0db90d72e28ad0ba1e22ee510510', 'file4': '48a24b70a0b376535542b996af517398'}


问:
Kubernetes application running on master - DaemonSet
is there any way to avoid execution of an application deployed as DaemonSet on master?

I have seen that this is the expected behavior, but I would like to avoid execution in some way.

Regular pods will not schedule on master but DaemonSet pods do.

If yes, is it possible to set this information in the yml file (parameter..etc??)?

```<code> kubectl create -f mydaemon.yml

logspri-4zwl4              1/1       Running           0          <invalid>   X.X.X.X   k8s-master-e7c355e2-0
logspri-kld2w              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-0
logspri-lksrh              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-1
</code>```

I would like to avoid my pod is running on k8s-master-e7c355e2-0

I have tried :

```<code>annotations:
          scheduler.alpha.kubernetes.io/affinity: >
            {
              "nodeAffinity": {
                "requiredDuringSchedulingRequiredDuringExecution": {
                  "nodeSelectorTerms": [
                    {
                      "matchExpressions": [
                        {
                          "key": "kubernetes.io/role",
                          "operator": "NotIn",
                          "values": ["master"]
                        }
                      ]
                    }
                  ]
                }
              }
            }
</code>```

Trying also to apply the following role  (as suggested) but it doesn't work :

```<code>kubectl get nodes
NAME                    STATUS                     AGE       VERSION
k8s-agent-e7c355e2-0    Ready                      49d       v1.5.3
k8s-agent-e7c355e2-1    Ready                      49d       v1.5.3
k8s-master-e7c355e2-0   Ready,SchedulingDisabled   49d       v1.5.3
</code>```

Shall I perform:

```<code>VirtualBox:~/elk/logspout$ kubectl taint node k8s-master-e7c355e2-0 k8s-master-e7c355e2-0/ismaster=:NoSchedule
node "k8s-master-e7c355e2-0" tainted
</code>```

Even if it seems that the master is tainted I see that the application is always on master.

```<code>Role:
Labels:         beta.kubernetes.io/arch=amd64
            beta.kubernetes.io/instance-type=Standard_D2
            beta.kubernetes.io/os=linux
            failure-domain.beta.kubernetes.io/region=northeurope
            failure-domain.beta.kubernetes.io/zone=0
            kubernetes.io/hostname=k8s-master-e7c355e2-0
Annotations:        volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:         <none>
CreationTimestamp:  Wed, 17 May 2017 14:38:06 +0200
Phase:
Conditions:
</code>```

What is wrong?
Could you give me the right command to perform?

same problem reported here without an apparent solution by :

```<code>kubectl taint nodes nameofmaster dedicated=master:NoSchedule
</code>```

Thanks
Prisco

答:
From https://github.com/kubernetes/kubernetes/issues/29108, you can add a taint flag to your Master node kubelet, so the even the pods in the DaemonSet are not scheduled there

```<code>   --register-with-taints=node.alpha.kubernetes.io/ismaster=:NoSchedule
</code>```

You will need to restart kubelet in your node

Body:
is there any way to avoid execution of an application deployed as DaemonSet on master?

I have seen that this is the expected behavior, but I would like to avoid execution in some way.

Regular pods will not schedule on master but DaemonSet pods do.

If yes, is it possible to set this information in the yml file (parameter..etc??)?

 kubectl create -f mydaemon.yml

logspri-4zwl4              1/1       Running           0          <invalid>   X.X.X.X   k8s-master-e7c355e2-0
logspri-kld2w              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-0
logspri-lksrh              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-1

I would like to avoid my pod is running on k8s-master-e7c355e2-0

I have tried :

annotations:
          scheduler.alpha.kubernetes.io/affinity: >
            {
              "nodeAffinity": {
                "requiredDuringSchedulingRequiredDuringExecution": {
                  "nodeSelectorTerms": [
                    {
                      "matchExpressions": [
                        {
                          "key": "kubernetes.io/role",
                          "operator": "NotIn",
                          "values": ["master"]
                        }
                      ]
                    }
                  ]
                }
              }
            }

Trying also to apply the following role  (as suggested) but it doesn't work :

kubectl get nodes
NAME                    STATUS                     AGE       VERSION
k8s-agent-e7c355e2-0    Ready                      49d       v1.5.3
k8s-agent-e7c355e2-1    Ready                      49d       v1.5.3
k8s-master-e7c355e2-0   Ready,SchedulingDisabled   49d       v1.5.3

Shall I perform:

VirtualBox:~/elk/logspout$ kubectl taint node k8s-master-e7c355e2-0 k8s-master-e7c355e2-0/ismaster=:NoSchedule
node "k8s-master-e7c355e2-0" tainted

Even if it seems that the master is tainted I see that the application is always on master.

Role:
Labels:         beta.kubernetes.io/arch=amd64
            beta.kubernetes.io/instance-type=Standard_D2
            beta.kubernetes.io/os=linux
            failure-domain.beta.kubernetes.io/region=northeurope
            failure-domain.beta.kubernetes.io/zone=0
            kubernetes.io/hostname=k8s-master-e7c355e2-0
Annotations:        volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:         <none>
CreationTimestamp:  Wed, 17 May 2017 14:38:06 +0200
Phase:
Conditions:

What is wrong?
Could you give me the right command to perform?

same problem reported here without an apparent solution by :

kubectl taint nodes nameofmaster dedicated=master:NoSchedule

Thanks
Prisco

Body:
From https://github.com/kubernetes/kubernetes/issues/29108, you can add a taint flag to your Master node kubelet, so the even the pods in the DaemonSet are not scheduled there

   --register-with-taints=node.alpha.kubernetes.io/ismaster=:NoSchedule

You will need to restart kubelet in your node


问:
Verify if a String is JSON in python?
I have a string in Python, I want to know if it is valid JSON.

json.loads(mystring)  will raise an error if the string is not JSON but I don't want to catch an exception.

I want something like this, but it doesn't work:

```<code>if type(mysrting) == dict:
    myStrAfterLoading = json.loads(mystring)
else:
    print "invalid json passed"
</code>```

Do I have to catch that ValueError to see if my string is JSON?

答:
why parsing when you can use types as follows:</p>

```<code>def is_json(myjson):
    return type(myjson) == type({})

def is_json_arr(myjson):
    return type(myjson) == type([{}])
</code>```

Title: Verify if a String is JSON in python?

Body:
I have a string in Python, I want to know if it is valid JSON.

json.loads(mystring)  will raise an error if the string is not JSON but I don't want to catch an exception.

I want something like this, but it doesn't work:

if type(mysrting) == dict:
    myStrAfterLoading = json.loads(mystring)
else:
    print "invalid json passed"

Do I have to catch that ValueError to see if my string is JSON?

Body:
why parsing when you can use types as follows:

def is_json(myjson):
    return type(myjson) == type({})

def is_json_arr(myjson):
    return type(myjson) == type([{}])


问:
Responsive html layout height 100% is not according to parent div
I'm really new in html

This is my code

```<code><div class="w3-row">
    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>VISION</b></br></br>
        To become the best foundation that is able to nurture holistic global leaders</p>
    </div>

    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>MISSION</b></br></br>
        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values</p>
    </div>
</div>
</code>```

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?

答:
Thats the problem of responsive layouts.

Add the orange background-color to the w3-row.

To prevent the different hights you have to add some hight values to your .w3-containers.

Body:
I'm really new in html

This is my code

 OUR VISION

        To become the best foundation that is able to nurture holistic global leaders

 OUR MISSION

        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?


问:
Vue.js checkboxes not working with model that uses Laravel SparkForm
I have the following checkboxes set up:

```<code><label v-for="service in team.services">
    <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/>
</label>
</code>```

These are displayed correctly but when checking one checkbox they all get checked as the form.services model gets set to false / true.

However, when changing the model to another data attribute e.g. 'services' everything works as expected. Any reason why this isn't working within SparkForm?

Example data:

```<code>data: function() {
        return {
            form: new SparkForm({
                userId: null,
                services: [] // always only gets set as true / false
            }),
            services: [], // works fine
        }
    },
</code>```

答:
new Vue({
    el: '#app',
    data(){
      return {
        form : {
           services : []
        },
      team : {
        services : [
         {
         "name" : "Service name #1",
         "id" : 1
         },
         {
         "name" : "Service name #2",
         "id" : 2
         }
        ]
      }
     }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <label v-for="service in team.services">
    <input type="checkbox" v-model="form.services" :value="service.id"/>{{service.name}}
  </label>
{{form.services}}
</div></code>```

Body:
I have the following checkboxes set up:

    <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/>

These are displayed correctly but when checking one checkbox they all get checked as the form.services model gets set to false / true.

However, when changing the model to another data attribute e.g. 'services' everything works as expected. Any reason why this isn't working within SparkForm?

Example data:

data: function() {
        return {
            form: new SparkForm({
                userId: null,
                services: [] // always only gets set as true / false
            }),
            services: [], // works fine
        }
    },

Body:
new Vue({
    el: '#app',
    data(){
      return {
        form : {
           services : []
        },
      team : {
        services : [
         {
         "name" : "Service name #1",
         "id" : 1
         },
         {
         "name" : "Service name #2",
         "id" : 2
         }
        ]
      }
     }
    }
});

<div id="app">
  <label v-for="service in team.services">
    <input type="checkbox" v-model="form.services" :value="service.id"/>{{service.name}}
  </label>
{{form.services}}
</div>


问:
How to install packages in Python 2.7 without internet connections in Windows machine?
I have a machine which is a Windows server, where installation by downloading packages from internet is prohibited. Before that I tried to set up Python 2.7 on my windows machine with internet.I have downloaded and installed pysftp, paramiko, bcrypt, cryptography, pyasn, PyNaCl etc. and also have installed Microsoft visual c++ which was required for pyasn. I have updated pip to 9.0.1 as well. But when I tried to set up on another Windows machine with the help of all packages (unzipped and copied to that machine),installation failed always.
I have tried with
    python setup.py install
and
    pip install

So can we install packages without internet connection?

Please help me on this.

Thanks and regards,
Shreeram

答:
To answer the specific question "Can you install packages withou tthe internet" then asnwer is yes.

For example, armed with a wheel somewhere the machine can see, and pip

```<code>pip install some-dir/some-file.whl
</code>```

or

```<code>python -m pip install some-dir/some-file.whl
</code>```

There are other options than wheels, however, the same idea applies.

Body:
To answer the specific question "Can you install packages withou tthe internet" then asnwer is yes.

For example, armed with a wheel somewhere the machine can see, and pip

pip install some-dir/some-file.whl

or

python -m pip install some-dir/some-file.whl

There are other options than wheels, however, the same idea applies.


问:
How to deserialise a JSON where the corresponding Haskell type is available during runtime as a value?
I'm trying to implement a port of DelayedJob (from the Rails world) in Haskell.

Here's the typeclass I have which represents a DelayedJob

```<code>class (FromJSON j, ToJSON j, FromJSON r, ToJSON r) => DelayedJob j r | j -> r where
  serialise :: j -> Value
  serialise = toJSON

  deserialise :: Value -> Either String j
  deserialise = parseEither parseJSON

  runJob :: j -> AppM r
</code>```

Here's how I plan to use it:

```<code>createJob :: (DelayedJob j r) => j -> AppM JobId
</code>```

I'm getting stuck with writing a fairly general invokeJob function which will read a row from the jobs table, look at the jobs.jobtype column and invoke the correct version of the runJob version (i.e. the runJob function belonging to the correct type-class instance).

I have the following, but it is full of boilerplate:

```<code>data JobType = SyncContacts | SendEmail | SendSms deriving (Eq, Show, Generic)

invokeJob :: JobId -> AppM ()
invokeJob jid = do
  job <- fetchJob jid
  case (job ^. jobtype) of
     SyncContacts -> case (deserialise (job ^. jobdata) :: Either String SynContactsJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendEmail -> case (deserialise (job ^. jobdata) :: Either String SendEmailJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendSms -> case (deserialise (job ^. jobdata) :: Either String SendSms) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
</code>```

Essentially, is there a way to constrain the concrete type of the deserialise function dynamically during runtime without having to write so much boilerplate?

答:
I am loath to suggest it, but IMHO the "right" thing to do here is to forego type safety with a little runtime polymorphism. Instead of a type class, have an opaque Handler of sorts, in your case it'd probably be something like Value -> AppM ().

Just put these in a Map Type Handler or something along those lines, which you can update dynamically; whereby Type is what you use to distinguish your job types (i.e. some sum type or, for minimum type safety, just a String). When you pull out a job you can just look up the appropriate handler in the list; The handler is opaque and knows which types it is responsible for, so the user end doesn't need to know how to deserialize values.

This isn't very clever but should work nevertheless.

Body:
I'm trying to implement a port of DelayedJob (from the Rails world) in Haskell.

Here's the typeclass I have which represents a DelayedJob

class (FromJSON j, ToJSON j, FromJSON r, ToJSON r) => DelayedJob j r | j -> r where
  serialise :: j -> Value
  serialise = toJSON

  deserialise :: Value -> Either String j
  deserialise = parseEither parseJSON

  runJob :: j -> AppM r

Here's how I plan to use it:

createJob :: (DelayedJob j r) => j -> AppM JobId

I'm getting stuck with writing a fairly general invokeJob function which will read a row from the jobs table, look at the jobs.jobtype column and invoke the correct version of the runJob version (i.e. the runJob function belonging to the correct type-class instance).

I have the following, but it is full of boilerplate:

data JobType = SyncContacts | SendEmail | SendSms deriving (Eq, Show, Generic)

invokeJob :: JobId -> AppM ()
invokeJob jid = do
  job <- fetchJob jid
  case (job ^. jobtype) of
     SyncContacts -> case (deserialise (job ^. jobdata) :: Either String SynContactsJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendEmail -> case (deserialise (job ^. jobdata) :: Either String SendEmailJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendSms -> case (deserialise (job ^. jobdata) :: Either String SendSms) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j

Essentially, is there a way to constrain the concrete type of the deserialise function dynamically during runtime without having to write so much boilerplate?


问:
reStructuredText Multilevel
How can I get such a structur with reStructuredText? Is it even possible? </p>

```<code>1. Title
    1.1 Subtitle
         1.1.2 SubSubtitle
             1.1.2.1 SubSubtitle
    1.2 2ndSubtitle
         1.2.1 2ndSubSubtitle
</code>```

答:
So I found the answer here:

```<code>Title
=====
   Subtitle
   --------
     ___________
     SubSubtitle
     ___________

        SubSubSubtitle 1
        ________________

        SubSubSubtitle 2
        ________________

     _____________
     SubSubtitle 2
     _____________

Title 2
=======
</code>```

The Output would be (if numbered doctree):

```<code>1. Title
   1.1 Subtitle
       1.1.1 SubSubtitle
             1.1.1.1 SubSubSubtitle 1
             1.1.1.2 SubSubSubtitle 2
       1.1.2 SubSubtitle 2
2. Title 2
</code>```

For more information check out: http://docutils.sourceforge.net/docs/user/rst/quickstart.html#sections

Title: reStructuredText Multilevel

Body:
How can I get such a structur with reStructuredText? Is it even possible?

1. Title
    1.1 Subtitle
         1.1.2 SubSubtitle
             1.1.2.1 SubSubtitle
    1.2 2ndSubtitle
         1.2.1 2ndSubSubtitle

Body:
So I found the answer here:

Title
=====
   Subtitle
   --------
     ___________
     SubSubtitle
     ___________

        SubSubSubtitle 1
        ________________

        SubSubSubtitle 2
        ________________

     _____________
     SubSubtitle 2
     _____________

Title 2
=======

The Output would be (if numbered doctree):

1. Title
   1.1 Subtitle
       1.1.1 SubSubtitle
             1.1.1.1 SubSubSubtitle 1
             1.1.1.2 SubSubSubtitle 2
       1.1.2 SubSubtitle 2
2. Title 2

For more information check out: http://docutils.sourceforge.net/docs/user/rst/quickstart.html#sections


问:
Vue 2 - child components are not rendered
I can't wrap my head around this issue at the moment. Main parent component isn't rendering the child components. No error is thrown when the page is loaded.

I have this code so far:

HTML:

```<code><td class="countries-visible-filter">

    <visible-filters>
        <show-query-filter :selected ="true" query="all" name="All | "></show-query-filter>
        <show-query-filter query="true" name="Visible | "></show-query-filter>
        <show-query-filter query="false" name="Hidden"></show-query-filter>
    </visible-filters>
</code>```

Parent component:

```<code>Vue.component('visible-filters', {
    template: `
        <div>
            <span v-for="filter in queryFilters"
                :class="{'text-muted' : !filter.isSelected}"
                @mouseenter="changeClassMouseenter($event)"
                @mouseout="changeClassMouseout($event)"
                @click="countryTest(filter)"
            >
                {{filter.name}}
            </span>
        </div>
    `,

    methods: {
        countryTest(filter) {

            this.filters.forEach(singleFilter => {
                console.log(singleFilter);
            });

            Event.$emit('country-filter', filter);
        }
    },

    created() {
        console.log(this);
        this.queryFilters = this.$children;
    },

    data() {
        return {
            queryFilters: []
        }
    }
});
</code>```

Child component:

```<code>Vue.component('show-query-filter', {
    template: `
        <div><slot></slot></div>
    `,

    props: {
        query: '',
        selected: false,
        name: {required: true}
    },

    mounted() {
        this.isSelected = this.selected;
    },

    methods: {

        changeClassMouseenter(event) {
            if(!this.selected)
                event.target.classList.remove('text-muted')
        },

        changeClassMouseout(event) {
            if(!this.selected)
                event.target.classList.add('text-muted')
        }
    },

    data() {
        return {
            isSelected: false
        }
    }

});
</code>```

What am I doing wrong here?

答:
This construction:

```<code><visible-filters>
    <show-query-filter :selected ="true" query="all" name="All | "></show-query-filter>
    <show-query-filter query="true" name="Visible | "></show-query-filter>
    <show-query-filter query="false" name="Hidden"></show-query-filter>
</visible-filters>
</code>```

indicates that the three instances of show-query-filter are being used as the contents of a slot, but visible-filters is not defined with a slot in its template.

You have defined show-query-filter to have a slot, but you don't supply any content for it. It isn't clear what your intended result is. Note that slot contents are not children of the component whose slot they are put into.

Slot scoping rules

Body:
I can't wrap my head around this issue at the moment. Main parent component isn't rendering the child components. No error is thrown when the page is loaded.

I have this code so far:

HTML:

    <visible-filters>
        <show-query-filter :selected ="true" query="all" name="All | "></show-query-filter>
        <show-query-filter query="true" name="Visible | "></show-query-filter>
        <show-query-filter query="false" name="Hidden"></show-query-filter>
    </visible-filters>

Parent component:

Vue.component('visible-filters', {
    template: `

                {{filter.name}}

    `,

    methods: {
        countryTest(filter) {

            this.filters.forEach(singleFilter => {
                console.log(singleFilter);
            });

            Event.$emit('country-filter', filter);
        }
    },

    created() {
        console.log(this);
        this.queryFilters = this.$children;
    },

    data() {
        return {
            queryFilters: []
        }
    }
});

Child component:

Vue.component('show-query-filter', {
    template: `

<slot></slot>

    `,

    props: {
        query: '',
        selected: false,
        name: {required: true}
    },

    mounted() {
        this.isSelected = this.selected;
    },

    methods: {

        changeClassMouseenter(event) {
            if(!this.selected)
                event.target.classList.remove('text-muted')
        },

        changeClassMouseout(event) {
            if(!this.selected)
                event.target.classList.add('text-muted')
        }
    },

    data() {
        return {
            isSelected: false
        }
    }

});

What am I doing wrong here?

Body:
This construction:

<visible-filters>
    <show-query-filter :selected ="true" query="all" name="All | "></show-query-filter>
    <show-query-filter query="true" name="Visible | "></show-query-filter>
    <show-query-filter query="false" name="Hidden"></show-query-filter>
</visible-filters>

indicates that the three instances of show-query-filter are being used as the contents of a slot, but visible-filters is not defined with a slot in its template.

You have defined show-query-filter to have a slot, but you don't supply any content for it. It isn't clear what your intended result is. Note that slot contents are not children of the component whose slot they are put into.

Slot scoping rules


问:
convert elements after xml to array
I have an XML with products and I converted it to Array from XML using this function http://www.bin-co.com/php/scripts/xml2array/
I have a problem when I have only one attribute in XML file and I'm trying to convert first array into multidimensional.

```<code>[attributes] => Array
    (
        [attribute] => Array
            (
                [name] => 44
                [quantity] => 1
                [availability] => 1
            )

    )
</code>```

to

```<code>    [attributes] => Array
        (
            [attribute] => Array
                (
                    [0] => Array
                        (
                            [name] => 40
                            [quantity] => 1
                            [availability] => 1
                        )
                )
        )
</code>```

I need a multidimensional array for a loop

```<code>foreach($products["attributes"]["attribute"] as $attr) {
    echo $attr["name"]
}
</code>```

XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>
</code>```

答:
I think this is what you might be looking for:</p>

```<code>foreach($products["attributes"] as $product) {
    foreach($product["attribute"] as $attr) {
        echo $attr["name"]
    }
}
</code>```

Title: convert elements after xml to array

Body:
I have an XML with products and I converted it to Array from XML using this function http://www.bin-co.com/php/scripts/xml2array/
I have a problem when I have only one attribute in XML file and I'm trying to convert first array into multidimensional.

[attributes] => Array
    (
        [attribute] => Array
            (
                [name] => 44
                [quantity] => 1
                [availability] => 1
            )

    )

to

    [attributes] => Array
        (
            [attribute] => Array
                (
                    [0] => Array
                        (
                            [name] => 40
                            [quantity] => 1
                            [availability] => 1
                        )
                )
        )

I need a multidimensional array for a loop

foreach($products["attributes"]["attribute"] as $attr) {
    echo $attr["name"]
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1006</id>
        <sku>360116 05</sku>
        <attributes>
            <attribute>
                <name>44</name>
                <quantity>1</quantity>
                <availability>1</availability>
            </attribute>
        </attributes>
    </product>
    <product>
        <id>2501</id>
        <sku>AQ4040</sku>
        <attributes>
            <attribute>
                <name>42.5</name>
                <quantity>13</quantity>
                <availability>2</availability>
            </attribute>
            <attribute>
                <name>44</name>
                <quantity>18</quantity>
                <availability>2</availability>
            </attribute>
        </attributes>
    </product>
</products>

Body:
I think this is what you might be looking for:

foreach($products["attributes"] as $product) {
    foreach($product["attribute"] as $attr) {
        echo $attr["name"]
    }
}


问:
How to check for nil value? App crashes even though nil values are accounted for. Swift
I am creating a simple guessing game on Xcode where the user has to correctly guess the number (between 0 and 5). I thought that I had checked for a nil value for my textFieldIntto ensure the app does not crash if no value is submitted. Unfortunately this does not seem to be the case and I am not sure where my fault lies.

If I do not enter a value and press the button, I receive the following error message:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have had this issue before and managed to solve it by correctly checking the right optional for nil. Though now it seems to still have 'unexpectedly found nil' even though a nil value has been accounted for.

```<code>@IBOutlet var textField: UITextField!

@IBOutlet var label: UILabel!

@IBAction func buttonTapped(_ sender: Any) {
    let textFieldInt: UInt32 = UInt32(textField.text!)!
    let number = arc4random_uniform(6)

    if textFieldInt != nil {
        if textFieldInt != number {
            label.text = "Wrong! It was \(number)"
        }
        else if textFieldInt == number {
            label.text = "You're right!"
        }

    else {
        label.text = "Please enter a number!"
    }
}
}
</code>```

答:
I believe the error occurs at

```<code>let textFieldInt: UInt32 = UInt32(textField.text!)!
</code>```

If the textField is empty then textField.text will be nil and textField.text! will cause the crash.

You can use like

```<code>        @IBAction func buttonTapped(_ sender: Any) {
            if textField.text != nil {
         let textFieldInt: UInt32 = UInt32(textField.text!)!
            let number = arc4random_uniform(6)

            if textFieldInt != nil {
                if textFieldInt != number {
                    label.text = "Wrong! It was \(number)"
                }
                else if textFieldInt == number {
                    label.text = "You're right!"
                }

            else {
                label.text = "Please enter a number!"
            }
        }
      }
              else {
              label.text = "Please enter a number!"
        }
  }
</code>```

Body:
I am creating a simple guessing game on Xcode where the user has to correctly guess the number (between 0 and 5). I thought that I had checked for a nil value for my textFieldIntto ensure the app does not crash if no value is submitted. Unfortunately this does not seem to be the case and I am not sure where my fault lies.

If I do not enter a value and press the button, I receive the following error message:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have had this issue before and managed to solve it by correctly checking the right optional for nil. Though now it seems to still have 'unexpectedly found nil' even though a nil value has been accounted for.

@IBOutlet var textField: UITextField!

@IBOutlet var label: UILabel!

@IBAction func buttonTapped(_ sender: Any) {
    let textFieldInt: UInt32 = UInt32(textField.text!)!
    let number = arc4random_uniform(6)

    if textFieldInt != nil {
        if textFieldInt != number {
            label.text = "Wrong! It was \(number)"
        }
        else if textFieldInt == number {
            label.text = "You're right!"
        }

    else {
        label.text = "Please enter a number!"
    }
}
}

Body:
I believe the error occurs at

let textFieldInt: UInt32 = UInt32(textField.text!)!

If the textField is empty then textField.text will be nil and textField.text! will cause the crash.

You can use like

        @IBAction func buttonTapped(_ sender: Any) {
            if textField.text != nil {
         let textFieldInt: UInt32 = UInt32(textField.text!)!
            let number = arc4random_uniform(6)

            if textFieldInt != nil {
                if textFieldInt != number {
                    label.text = "Wrong! It was \(number)"
                }
                else if textFieldInt == number {
                    label.text = "You're right!"
                }

            else {
                label.text = "Please enter a number!"
            }
        }
      }
              else {
              label.text = "Please enter a number!"
        }
  }


问:
querying memcached to get part of a key data
Working on a caching modal for a small project i am working on. I've implemented memcached for the cache technology.

I am trying to save roughly around 750kb of data in a formatted array in a single key. the problem is, on each request, i only need 5% of the data, so getting all the data in a single call is a waste of network resources. I know i can create multiple keys with specific data set but i am trying to minimize the number of connections to the memcached server.

Question is. is there a way i can query memcached to just get part of the key value?

答:
Typically how you divide your data in one key or multiple keys it is depends on use case.

But as you mentioned you required only 5% of data, then it will be good you divide your data into multiple keys.
Memcache connects time and network latency you can reduce by using local Memcache.

local Memcache means Memcache will be on the same machine where your web server and each web server has its own small instance of Memcache locally. It will reduce to network latency. Because all communication has done at 127.0.0.1 (locally)

At that information required shared across the web server like session, you can keep it Global Memcache. it will improve you website scalability and at the same time cache segregation.


问:
Embedded Web Server
We currently have a web application which should be accessible from multiple sub-domains and from multiple actual domains. E.g. clients sign up and if they want to they can use their own domains. As far as I know this would be achieved by them pointing that domains A record at us and then our web server, which would have to be embedded so we can update at run-time, adding a virtual host dynamically.

Our web application is written in PHP (although playing around with HipHop to convert to C++) with static HTML and CSS. This web application communicates with a back-end Java API that uses the Restlet framework.

Does anyone know of a web server that could be embedded that will work with PHP (and would work with HipHop if we used that)? I have had a look at AppWeb but I wondered if there were any others.

I wonder if maybe I would be better moving my web app to something like Java and using Jetty?

Thanks,

答:
This can be done by accepting wildcard subdomains in apache, and dispatching based on the server name in PHP.

An example apache configuration can be found here.

ContentLicense: CC BY-SA 2.5

Title: Embedded Web Server


问:
AureliaJS - Call child function from parent
I'm using AureliaJS to build a dynamic forms scenario, where I have a parent form with the gross operations needed and multiple child's form's, that change based on user input.

These child's form's have only two specific things themselves. Their model and the validation rules for their model.

So my question is, how can the parent form call the validation rules from the current child form? From child I know that is possible call parent's view model. But from parent, how can I invoke any function from the child?

The scenario is similar off having one base class, that has one method and this method could be overriding on the child classes.

Any suggestion? I'm glad to change the approach if needed.

Here's an example: https://gist.run?id=1865041a15af60600cb7b538018bdccd

app.html

<template>
  This is an APP

  <compose view-model.bind="'parentForm'"></compose>
</template>
```

<p><strong>app.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class App {

}
</code>```

childForm1.html

<template>
   Price :
  <input value.bind="model.data.price">

   VAT :
  <input value.bind="model.data.vat">

</template>
```

<p><strong>childForm1.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm1 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

     if(this.model.data.price != '' && this.model.data.vat == '' )
      this.model.validateMessage = 'VAT is mandatory';
 }
}
</code>```

childForm2.html

<template>
  Address :
  <input value.bind="model.data.address">

  Phone :
  <input value.bind="model.data.phone">

</template>
```

<p><strong>childForm2.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm2 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

   if(this.model.data.phone != '' && this.model.data.address == '' )
      this.model.validateMessage = 'Address is mandatory';
 }
}
</code>```

index.html

<!doctype html>

    <title>Aurelia</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

Loading...

```

<p><strong>parentForm.html</strong></p>

<pre class="lang-html prettyprint-override"><code><template>
  <button click.delegate="changeChildForm1()">Change Child Form 1</button>
  <button click.delegate="changeChildForm2()">Change Child Form 2</button>
  <p/>
  <p/>
  <form>
    <label>User : </label>
    <input value.bind="model.data.user">
    <p/>
    <compose view-model.bind="childFormVM" model.bind="model"></compose>
    <button click.delegate="save()">Save</button>
    <p/>
    <span> Validation Message :  ${model.validateMessage}</span>
  </form>
   <p/>
  <span>Price : ${model.data.price}</span><p/>
  <span>Vat : ${model.data.vat}</span><p/>
  <span>Phone : ${model.data.phone}</span><p/>
  <span>Address : ${model.data.address}</span><p/>
</template>
</code>```

parentForm.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ParentForm {
  model = {
   validateMessage : '',
   data : {
    user : 'My Name'
   }
 };

 childFormVM = 'childForm1';

 validateMessage = '';

 changeChildForm1() {

   this.childFormVM = 'childForm1';
 }

  changeChildForm2() {

   this.childFormVM = 'childForm2';
 }

 save(){
   this.validateRules();
   // How to call the validation rules from child ?
 }

 validateRules (){

   this.model.validateMessage = 'Validate by parent';
 }
}
```

答:
Bind a function call to the child so that you have a handle to invoke it from the parent.  I usually prefer to directly bind the child components rather than using compose, but you can make it work with compose by passing a complex model object rather than only the model, and passing the binding function as one of the model properties.

Parent View-Model:

```<code>class Parent {
  model = {};
  child1Validate = null;

  changeChildForm1() {
    if (typeof this.child1Validate === 'function') {
      // the binding was successful; proceed with function call
      let result = this.child1Validate();
      console.log(result);
    }
  }
}
</code>```

Parent View:

```<code><my-child1 model="parentModel" go-validate="child1Validate"></my-child1>
</code>```

Child View-Model:

```<code>class MyChild1 {
  @bindable model;
  @bindable goValidate;
  bind() {
    // bind the child function to the parent that instantiates the child
    this.goValidate = this.runValidation.bind(this);
  }
  runValidation() {
    // do the validation and pass result to parent...
    return 'Success!';
  }
}
</code>```

Body:
I'm using AureliaJS to build a dynamic forms scenario, where I have a parent form with the gross operations needed and multiple child's form's, that change based on user input.

These child's form's have only two specific things themselves. Their model and the validation rules for their model.

So my question is, how can the parent form call the validation rules from the current child form? From child I know that is possible call parent's view model. But from parent, how can I invoke any function from the child?

The scenario is similar off having one base class, that has one method and this method could be overriding on the child classes.

Any suggestion? I'm glad to change the approach if needed.

Here's an example: https://gist.run?id=1865041a15af60600cb7b538018bdccd

app.html

<template>
  This is an APP

  <compose view-model.bind="'parentForm'"></compose>
</template>

app.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class App {

}

childForm1.html

<template>
   Price :
  <input value.bind="model.data.price">

   VAT :
  <input value.bind="model.data.vat">

</template>

childForm1.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm1 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

     if(this.model.data.price != '' && this.model.data.vat == '' )
      this.model.validateMessage = 'VAT is mandatory';
 }
}

childForm2.html

<template>
  Address :
  <input value.bind="model.data.address">

  Phone :
  <input value.bind="model.data.phone">

</template>

childForm2.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm2 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

   if(this.model.data.phone != '' && this.model.data.address == '' )
      this.model.validateMessage = 'Address is mandatory';
 }
}

index.html

<!doctype html>

    <title>Aurelia</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

Loading...

parentForm.html

<template>
  <button click.delegate="changeChildForm1()">Change Child Form 1</button>
  <button click.delegate="changeChildForm2()">Change Child Form 2</button>

  <form>
    User :
    <input value.bind="model.data.user">

    <compose view-model.bind="childFormVM" model.bind="model"></compose>
    <button click.delegate="save()">Save</button>

     Validation Message :  ${model.validateMessage}
  </form>

  Price : ${model.data.price}

  Vat : ${model.data.vat}

  Phone : ${model.data.phone}

  Address : ${model.data.address}

</template>

parentForm.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ParentForm {
  model = {
   validateMessage : '',
   data : {
    user : 'My Name'
   }
 };

 childFormVM = 'childForm1';

 validateMessage = '';

 changeChildForm1() {

   this.childFormVM = 'childForm1';
 }

  changeChildForm2() {

   this.childFormVM = 'childForm2';
 }

 save(){
   this.validateRules();
   // How to call the validation rules from child ?
 }

 validateRules (){

   this.model.validateMessage = 'Validate by parent';
 }
}

Body:
Bind a function call to the child so that you have a handle to invoke it from the parent.  I usually prefer to directly bind the child components rather than using compose, but you can make it work with compose by passing a complex model object rather than only the model, and passing the binding function as one of the model properties.

Parent View-Model:

class Parent {
  model = {};
  child1Validate = null;

  changeChildForm1() {
    if (typeof this.child1Validate === 'function') {
      // the binding was successful; proceed with function call
      let result = this.child1Validate();
      console.log(result);
    }
  }
}

Parent View:

<my-child1 model="parentModel" go-validate="child1Validate"></my-child1>

Child View-Model:

class MyChild1 {
  @bindable model;
  @bindable goValidate;
  bind() {
    // bind the child function to the parent that instantiates the child
    this.goValidate = this.runValidation.bind(this);
  }
  runValidation() {
    // do the validation and pass result to parent...
    return 'Success!';
  }
}


问:
Laravel sql server on mac
So i installed SQL serve with docker on mac and i can actually manage to access my local sql server database with datagrip, but when i want to do a php artisan migrate i get this error:

```<code>[Illuminate\Database\QueryException] could not find driver (SQL: select * from sysobjects where type = 'U' and name = migrations)
</code>```

and this error

```<code>[PDOException]could not find driver
</code>```

i search for some answer but they where mostly for linux.

答:
So i manage to installed al the necessary drivers just by installing this:
https://github.com/Microsoft/msphpsql/releases

php and Laravel worked perfectly after i installed those package and added this lines on my php.ini file:

```<code>extension=sqlsrv.so
extension=pdo_sqlsrv.so
</code>```

Title: Laravel sql server on mac

Body:
So i installed SQL serve with docker on mac and i can actually manage to access my local sql server database with datagrip, but when i want to do a php artisan migrate i get this error:

[Illuminate\Database\QueryException] could not find driver (SQL: select * from sysobjects where type = 'U' and name = migrations)

and this error

[PDOException]could not find driver

i search for some answer but they where mostly for linux.

Body:
So i manage to installed al the necessary drivers just by installing this:
https://github.com/Microsoft/msphpsql/releases

php and Laravel worked perfectly after i installed those package and added this lines on my php.ini file:

extension=sqlsrv.so
extension=pdo_sqlsrv.so


问:
how to format credit card expiry date in mm/yy when entered by user
I want to implement algorithm like this :

As soon as user starts entering numbers for "MM" , it should give "/" after the user enters two digits of "MM" and then , it should let only enter last two digits for "yy". How can I achieve this kind of functionality?

答:
```<code>android:maxLength="5"
</code>```

And set as phone to editText so that it can display "/"

```<code>android:inputType="phone"
</code>```

on the textWatcher do this .... I will validate later for the correct mm/yy month year to avoid users input data like 55/66 max should be 12/31 but it should be validated for months with less or 30 days...

```<code> @Override
    public void afterTextChanged(Editable editable) {

        if (editable.length() > 0 && (editable.length() % 3) == 0) {
            final char c = editable.charAt(editable.length() - 1);
            if ('/' == c) {
                editable.delete(editable.length() - 1, editable.length());
            }
        }
        if (editable.length() > 0 && (editable.length() % 3) == 0) {
            char c = editable.charAt(editable.length() - 1);
            if (Character.isDigit(c) && TextUtils.split(editable.toString(), String.valueOf("/")).length <= 2) {
                editable.insert(editable.length() - 1, String.valueOf("/"));
            }
        }
    }
</code>```

Body:
android:maxLength="5"

And set as phone to editText so that it can display "/"

android:inputType="phone"

on the textWatcher do this .... I will validate later for the correct mm/yy month year to avoid users input data like 55/66 max should be 12/31 but it should be validated for months with less or 30 days...

 @Override
    public void afterTextChanged(Editable editable) {

        if (editable.length() > 0 && (editable.length() % 3) == 0) {
            final char c = editable.charAt(editable.length() - 1);
            if ('/' == c) {
                editable.delete(editable.length() - 1, editable.length());
            }
        }
        if (editable.length() > 0 && (editable.length() % 3) == 0) {
            char c = editable.charAt(editable.length() - 1);
            if (Character.isDigit(c) && TextUtils.split(editable.toString(), String.valueOf("/")).length <= 2) {
                editable.insert(editable.length() - 1, String.valueOf("/"));
            }
        }
    }


问:
What input should I give to crc16 Method
This my Mod bus crc_16 embedded code. I have run this code in code block many Times. There is no error but I am not getting actual crc value. I should get crc 05C8 and I am getting 8512 right now.

I think I giving wrong input while calling CRC method. I am passing string and its length. So please help me.

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define POLY 0x8005
    unsigned int ModRTU_CRC(unsigned char * mod_data,unsigned int length)
    {
    unsigned int CRC16 = 0xFFFF;

    unsigned int pos=0,i=0;

    for(pos=0;pos<length;pos++)
    {
    CRC16 ^= (unsigned int) mod_data[pos];

    for(i=0;i<8;i++)
    {
        if((CRC16 & 0x0001)!=0)
        {
            CRC16 >>=1;
            CRC16^=0xA001;
        }
        else
        {
            CRC16 >>=1;
        }
    }

    }

   return CRC16;

    }

   int main()
   {

    //char *frame = "010600081388";
   //  char *frame = "010300080001";

   char frame[7];
        frame[0]=0x01;
       frame[1]=0x03;
       frame[2]=0x00;
       frame[3]=0x08;
       frame[4]=0x00;
       frame[5]=0x01;
       frame[6]='\0';

     printf("%x\n",frame);
     int len = strlen(frame);
     unsigned int  crcv = ModRTU_CRC(frame,len);
    printf("%x\n",crcv);
   return 0;
       }
</code>```

答:
The bug is that in your original code you used frame[2]=0x00; followed by strlen(), which will interpret this as the null terminator and give the wrong size 2 instead of 6. You cannot use strlen() on binary data.

In the "fixed" version you hard-code the size to 6 so the bug was removed by accident. It has nothing to do with uint8_t versus char (although it is always better to use uint8_t for binary data).

Body:
This my Mod bus crc_16 embedded code. I have run this code in code block many Times. There is no error but I am not getting actual crc value. I should get crc 05C8 and I am getting 8512 right now.

I think I giving wrong input while calling CRC method. I am passing string and its length. So please help me.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define POLY 0x8005
    unsigned int ModRTU_CRC(unsigned char * mod_data,unsigned int length)
    {
    unsigned int CRC16 = 0xFFFF;

    unsigned int pos=0,i=0;

    for(pos=0;pos<length;pos++)
    {
    CRC16 ^= (unsigned int) mod_data[pos];

    for(i=0;i<8;i++)
    {
        if((CRC16 & 0x0001)!=0)
        {
            CRC16 >>=1;
            CRC16^=0xA001;
        }
        else
        {
            CRC16 >>=1;
        }
    }

    }

   return CRC16;

    }

   int main()
   {

    //char *frame = "010600081388";
   //  char *frame = "010300080001";

   char frame[7];
        frame[0]=0x01;
       frame[1]=0x03;
       frame[2]=0x00;
       frame[3]=0x08;
       frame[4]=0x00;
       frame[5]=0x01;
       frame[6]='\0';

     printf("%x\n",frame);
     int len = strlen(frame);
     unsigned int  crcv = ModRTU_CRC(frame,len);
    printf("%x\n",crcv);
   return 0;
       }


问:
What's the valid way to include an image with no src?
I have an image that I will dynamically populate with a src later with javascript but for ease I want the image tag to exist at pageload but just not display anything. I know  is invalid so what's the best way to do this?

答:
```<code><img src="invis.gif" />
</code>```

Where invis.gif is a single pixel transparent gif. This won't break in future browser versions and has been working in legacy browsers since the '90s.

png should work too but in my tests, the gif was 43 bytes and the png was 167 bytes so the gif won.

p.s. don't forget an alt tag, validators like them too.

Body:
<img src="invis.gif" />

Where invis.gif is a single pixel transparent gif. This won't break in future browser versions and has been working in legacy browsers since the '90s.

png should work too but in my tests, the gif was 43 bytes and the png was 167 bytes so the gif won.

p.s. don't forget an alt tag, validators like them too.


问:
How to replace a particular string in js
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

```<code><img src="test" />
</code>```

To

```<code><amp-img src="test"></amp-img>
</code>```

But here I am getting the data of 100 records as an example I put

```<code> <img src="test" />
</code>```

But I am not sure what my img tag contains.So I van replace img with

```<code>replace('<img',<amp-img>);
</code>```

But how can I replace the end tag i.e

```<code>  ('/>','></amp-img>').
</code>```

Can any one please suggest me help.Thanks.

答:
You can use this method roughly;

```<code>$("amp-img").replaceWith("<img src=\"test\"/>");
</code>```

http://api.jquery.com/replacewith/

Body:
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

To

<amp-img src="test"></amp-img>

But here I am getting the data of 100 records as an example I put

But I am not sure what my img tag contains.So I van replace img with

replace('<img',<amp-img>);

But how can I replace the end tag i.e

  ('/>','></amp-img>').

Can any one please suggest me help.Thanks.

Body:
You can use this method roughly;

$("amp-img").replaceWith("<img src=\"test\"/>");

http://api.jquery.com/replacewith/


问:
Display WMS Layer Based on Zoom Level
I've been at this all day long and honestly I'm out of ideas.  I have some WMS layers that I would like to display/not display depending on the current zoom level.  Yes, I have went through the API docs and they seem to be clear as day, but I follow everything that is suggested and I'm not getting the results desired :(

This was one of the sources that I looked at:
http://trac.osgeo.org/openlayers/wiki/SettingZoomLevels

Then to make matters even worse I found out that if you have an Open Street Map base layer displaying on load it seems to limit your control over the map's numZoomLevels, just what I needed, since I DO want to use this as my loading base layer...

So my questions are:

What am I doing wrong?
Is it true that there really is no workaround on the control of zoom levels when using an Open Street Map base layer on load?  Or is there something I just don't know?

Here are some of my code attempts:
Take 1:  tib_villages layer should only show when the zoom level is 8-10, doesn't work!

```<code>var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: null, //setting the map's zoom levels to null
            allOverlays: false
        }

var osm = new OpenLayers.Layer.OSM(); //MY base layer

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: 10, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                );
</code>```

Take 2:  tib_villages layer should only show when the zoom level is 8-10, map should only have 10 zoom levels, but instead has 19 as the Open Street Map Layer enforces it to,  doesn't work!

```<code>var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: 10, //setting the map's zoom levels to 10 only
            allOverlays: false
        }

var osm = new OpenLayers.Layer.OSM(); //MY base layer

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: null, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                )
</code>```

;

Take 3:  After getting rid of the Open Street Map base layer on load, the map only has 10 zoom levels as specified, but tib_villages layer should only show when the zoom level is 8-10, doesn't work!

```<code>var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: 10, //setting the map's zoom levels to 10
            allOverlays: false
        }

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: 10, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                );
</code>```

All of your suggestions are sincerely appreciated!

elshae

答: I would recommend using the maxScale and minScale on the layers instead of resolution, but that maybe is a question of taste. :-) I can't relate to a resolution value, but a scale is easy to understand and to maintain in the longer run, when others look at your code.</p>

Title: Display WMS Layer Based on Zoom Level

Body:
I've been at this all day long and honestly I'm out of ideas.  I have some WMS layers that I would like to display/not display depending on the current zoom level.  Yes, I have went through the API docs and they seem to be clear as day, but I follow everything that is suggested and I'm not getting the results desired :(

This was one of the sources that I looked at:
http://trac.osgeo.org/openlayers/wiki/SettingZoomLevels

Then to make matters even worse I found out that if you have an Open Street Map base layer displaying on load it seems to limit your control over the map's numZoomLevels, just what I needed, since I DO want to use this as my loading base layer...

So my questions are:

What am I doing wrong?
Is it true that there really is no workaround on the control of zoom levels when using an Open Street Map base layer on load?  Or is there something I just don't know?

Here are some of my code attempts:
Take 1:  tib_villages layer should only show when the zoom level is 8-10, doesn't work!

var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: null, //setting the map's zoom levels to null
            allOverlays: false
        }

var osm = new OpenLayers.Layer.OSM(); //MY base layer

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: 10, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                );

Take 2:  tib_villages layer should only show when the zoom level is 8-10, map should only have 10 zoom levels, but instead has 19 as the Open Street Map Layer enforces it to,  doesn't work!

var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: 10, //setting the map's zoom levels to 10 only
            allOverlays: false
        }

var osm = new OpenLayers.Layer.OSM(); //MY base layer

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: null, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                )

;

Take 3:  After getting rid of the Open Street Map base layer on load, the map only has 10 zoom levels as specified, but tib_villages layer should only show when the zoom level is 8-10, doesn't work!

var options = {
                                        controls: [new OpenLayers.Control.Navigation()], //Needed to use GeoExt controls such as the zoomslider
            maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
            units: 'm',
            numZoomLevels: 10, //setting the map's zoom levels to 10
            allOverlays: false
        }

//MY overlay layer
var tib_villages = new OpenLayers.Layer.WMS(
                    "Villages", "http://localhost:8080/geoserver/wms", {layers: 'cite:tib_villages', transparent: true, numZoomLevels: 10, minZoomLevel: 8}, {isBaseLayer: false, displayInLayerSwitcher: true, visibility: true}
                );

All of your suggestions are sincerely appreciated!

elshae


问:
Regex to find a particular pattern in Excel
This is the text in cell H1

```<code><a class="stop-propagation" href="javascript:void(0);" data-link="/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra" id="map_link_27696295" onclick="stopPage=true; showPhotoMap('/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra');" style="outline: 1px solid blue;"><span class="icoMap"></span>Map</a>
</code>```

From above cell I'm trying to extract element of 1st occurrence of  lat and longt

This is what I have tried

```<code>=IF(LEFT(H1,2)="lat=",SUBSTITUTE(H1,"lat=",""),IF(RIGHT(H1,2)="lat=",SUBSTITUTE(H1,"lat=",""),H1))
</code>```

But it doesn't gives me proper output.

This is what I Expect

```<code>lat=19.2412011
longt=73.1290596
</code>```

Any help would be much appreciated.

Thanks

答:
For the lat=19.2412011,

```<code>=TRIM(LEFT(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&",REPT(" ",LEN(H1))), LEN(H1)))
</code>```

For the longt=73.1290596,

```<code>=TRIM(MID(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&",REPT(" ",LEN(H1))), LEN(H1), LEN(H1)))
</code>```

For the two together in a single cell with a line feed,

```<code>=TRIM(LEFT(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&",REPT(" ",LEN(H1))),LEN(H1)))&CHAR(10)&TRIM(MID(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&",REPT(" ",LEN(H1))),LEN(H1),LEN(H1)))
</code>```

Body:
This is the text in cell H1

<a class="stop-propagation" href="javascript:void(0);" data-link="/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra" id="map_link_27696295" onclick="stopPage=true; showPhotoMap('/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra');" style="outline: 1px solid blue;">Map

From above cell I'm trying to extract element of 1st occurrence of  lat and longt

This is what I have tried

=IF(LEFT(H1,2)="lat=",SUBSTITUTE(H1,"lat=",""),IF(RIGHT(H1,2)="lat=",SUBSTITUTE(H1,"lat=",""),H1))

But it doesn't gives me proper output.

This is what I Expect

lat=19.2412011
longt=73.1290596

Any help would be much appreciated.

Thanks

Body:
For the lat=19.2412011,

=TRIM(LEFT(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&amp;",REPT(" ",LEN(H1))), LEN(H1)))

For the longt=73.1290596,

=TRIM(MID(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&amp;",REPT(" ",LEN(H1))), LEN(H1), LEN(H1)))

For the two together in a single cell with a line feed,

=TRIM(LEFT(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&amp;",REPT(" ",LEN(H1))),LEN(H1)))&CHAR(10)&TRIM(MID(SUBSTITUTE(REPLACE(H1,1,FIND("?",H1),TEXT(,)),"&amp;",REPT(" ",LEN(H1))),LEN(H1),LEN(H1)))


问:
Why ButterKnife uses a DebouncingOnClickListener for @OnClick methods?
I was looking at the generated code of ButterKnife, and noticed that for @OnClick annotations it is using a DebouncingOnClickListener, implemented by the library.

What the DebouncingOnClickListener does it to avoid more than one click on any element using that listener on the same frame (to achieve this they use a static flag). You can see the implementation here.

I have tried to find an explanation on why they decided to use this for every on click event managed by the library, but could not find any.

So, why they use that?
Why have they decided that every user of ButterKnife need this?
Shouldn't be the user who decides to use that or not?
Why couple the view binding help it provides with this "feature"?
What happens if I want to receive more than one click on the same frame? I couldn't use ButterKnife for click events.

I don't pretend to be offensive, just want an explanation, maybe I am missing something.

答:
Why have they decided that every user of ButterKnife need this?

Assume you have a button and a click event on this button launches a new activity. Now what will happen, when user very quickly double taps the button? There is some chance, that the click listener would be fired two times, thus 2 activities would be launched, which you most possibly do not want.

What this DebouncingOnClickListener does is it assures, that no subsequent click listener would be regarded. As soon as the first click happens, subsequent clicks would be disregarded until next frame, when they would be switched on.

When you are performing an action with a view, you are posting an event on the MessageQueue. Now, when first click happens, you are posting an event - launch new activity. And you are immediately posting another event - enable click listener, on the next frame. The second event is guaranteed to happen after the first one, because is has been post()ed to the queue.

What happens if I want to receive more than one click on the same frame?

If it is acceptable for you to receive multiple subsequent click events, than you should use @OnTouch, because you are interested in touch event and not in click events.

Listen to @Piwai's clarification concerning the case at Fragmented Podcast #88 (starting from 38:20).


问:
Rails Multiple Validation
I have a model with two columns 'name' and 'size'. I am trying to validate the uniqueness of size only if name and size together doesn't exist in database.

For example.

Name = Shirt and Size = L are in database then Name = Shirt and Size = L shouldn't pass the unique validation rather Name = Pant and Size = L should pass the uniqueness.

答:
if you want to scope with single column then:

```<code>validates_uniqueness_of :name, :scope => :size, message: "should be unique"
</code>```

for multiple columns:

```<code>validates :name, uniqueness: {scope: [:size, :attr1, :attr2]}
</code>```

Title: Rails Multiple Validation

Body:
if you want to scope with single column then:

validates_uniqueness_of :name, :scope => :size, message: "should be unique"

for multiple columns:

validates :name, uniqueness: {scope: [:size, :attr1, :attr2]}