问:
Task.Run blocking main thread (frozen UI)
I'm trying to make an asynchronous call to load data to my grid. Problem is, operation is blocking the UI (running in the main thread) - and i don't know why. I'm trying to make it to fetch data in the background ... Here's the code:

Binding ViewModel class to DataContext of the main window:

```<code><Window.DataContext>
    <vm:MainWindowViewModel WindowTitle="MVVM" BtnLoadText="LOAD DATA"/>
</Window.DataContext>
</code>```

DataGrid with column binding to the collection property (PeopleList) in ViewModel class:

```<code>    <DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Path=PeopleList, Mode=TwoWay}" Margin="5">
        <DataGrid.Columns>
            <DataGridTextColumn Header="First name" Binding="{Binding Path=FirstName}"/>
            <DataGridTextColumn Header="Last name" Binding="{Binding Path=LastName}"/>
            <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="btn_LoadData" Margin="5" Grid.Row="1" Content="{Binding Path=BtnLoadText}" Click="btn_LoadData_Click"/>
</code>```

Code-Behind of the MainWindow - running asynchronous button click event:

```<code>public partial class MainWindow : Window
{
    private MainWindowViewModel mainWindowViewModel;
    public MainWindow()
    {
        InitializeComponent();
        mainWindowViewModel = (MainWindowViewModel)DataContext;
    }

    private async void btn_LoadData_Click(object sender, RoutedEventArgs e)
    {
        await mainWindowViewModel.LoadData();
    }
}
</code>```

ViewModel class responsible for MainWindow:

```<code>class MainWindowViewModel
{
    public string WindowTitle { get; set; }
    public string BtnLoadText { get; set; }

    public ObservableCollection<Person> PeopleList { get; set; }

    private Database database = new Database();

    public MainWindowViewModel()
    {
        PeopleList = new ObservableCollection<Person>();
    }

    public async Task LoadData()
    {
        PeopleList.Clear();

        var result = await database.GetPeopleListLongOperationAsync();

        PeopleList.Add(result.First());
    }
}
</code>```

As you see, i'm making an asynchronous call with LoadData method, which gets data from the database and adding it to ObservableCollection, which updates DataGrid (Binding from the DataGrid)

Database class, which "emulates" data fetching:

```<code>public class Database
{
    public IEnumerable<Person> GetPeopleListLongOperation()
    {
        // forcing "long" data load
        Thread.Sleep(5000);
        yield return new Person() { FirstName = "Name", LastName = "LastName", Age = new Random().Next(18, 40) };
    }

    public Task<IEnumerable<Person>> GetPeopleListLongOperationAsync()
    {
        return Task.Run<IEnumerable<Person>>(() =>
        {
            return GetPeopleListLongOperation();
        });
    }
}
</code>```

I'm using Task.Run to fetch data in background thread. The problem is - it is running in Main Thread and it's blocking the UI.

Any suggestions? I'm not sure anymore, if i understand async operations correctly ...

EDIT

Changing Task result type from IEnumerable to List made it work. Can someone explain me why?

```<code>    public Task<List<Person>> GetPeopleListLongOperationAsync()
    {
        return Task.Run<List<Person>>(() =>
        {
            return GetPeopleListLongOperation().ToList();
        });
    }
</code>```

答:
Forget about the threading complication for now, and just take this code:

```<code>public IEnumerable<Person> GetPeopleListLongOperation()
{
    // forcing "long" data load
    Thread.Sleep(5000);
    yield return new Person();
}
</code>```

When you call GetPeopleListLongOperation() it will return immediately, it won't wait 5 seconds. This is because iterator blocks like this are lazily evaluated; Thread.Sleep(5000) will only be called when you enumerate through the sequence.

Now you understand that, you should see that you 'fix' works because ToList will enumerate the sequence to completion while still on the thread pool thread and return the cached results. Without this you were enumerating the sequence on the UI thread on the call to result.First() and blocking it.

Body:
I'm trying to make an asynchronous call to load data to my grid. Problem is, operation is blocking the UI (running in the main thread) - and i don't know why. I'm trying to make it to fetch data in the background ... Here's the code:

Binding ViewModel class to DataContext of the main window:

<Window.DataContext>
    <vm:MainWindowViewModel WindowTitle="MVVM" BtnLoadText="LOAD DATA"/>
</Window.DataContext>

DataGrid with column binding to the collection property (PeopleList) in ViewModel class:

    <DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Path=PeopleList, Mode=TwoWay}" Margin="5">
        <DataGrid.Columns>
            <DataGridTextColumn Header="First name" Binding="{Binding Path=FirstName}"/>
            <DataGridTextColumn Header="Last name" Binding="{Binding Path=LastName}"/>
            <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="btn_LoadData" Margin="5" Grid.Row="1" Content="{Binding Path=BtnLoadText}" Click="btn_LoadData_Click"/>

Code-Behind of the MainWindow - running asynchronous button click event:

public partial class MainWindow : Window
{
    private MainWindowViewModel mainWindowViewModel;
    public MainWindow()
    {
        InitializeComponent();
        mainWindowViewModel = (MainWindowViewModel)DataContext;
    }

    private async void btn_LoadData_Click(object sender, RoutedEventArgs e)
    {
        await mainWindowViewModel.LoadData();
    }
}

ViewModel class responsible for MainWindow:

class MainWindowViewModel
{
    public string WindowTitle { get; set; }
    public string BtnLoadText { get; set; }

    public ObservableCollection<Person> PeopleList { get; set; }

    private Database database = new Database();

    public MainWindowViewModel()
    {
        PeopleList = new ObservableCollection<Person>();
    }

    public async Task LoadData()
    {
        PeopleList.Clear();

        var result = await database.GetPeopleListLongOperationAsync();

        PeopleList.Add(result.First());
    }
}

As you see, i'm making an asynchronous call with LoadData method, which gets data from the database and adding it to ObservableCollection, which updates DataGrid (Binding from the DataGrid)

Database class, which "emulates" data fetching:

public class Database
{
    public IEnumerable<Person> GetPeopleListLongOperation()
    {
        // forcing "long" data load
        Thread.Sleep(5000);
        yield return new Person() { FirstName = "Name", LastName = "LastName", Age = new Random().Next(18, 40) };
    }

    public Task<IEnumerable<Person>> GetPeopleListLongOperationAsync()
    {
        return Task.Run<IEnumerable<Person>>(() =>
        {
            return GetPeopleListLongOperation();
        });
    }
}

I'm using Task.Run to fetch data in background thread. The problem is - it is running in Main Thread and it's blocking the UI.

Any suggestions? I'm not sure anymore, if i understand async operations correctly ...

EDIT

Changing Task result type from IEnumerable to List made it work. Can someone explain me why?

    public Task<List<Person>> GetPeopleListLongOperationAsync()
    {
        return Task.Run<List<Person>>(() =>
        {
            return GetPeopleListLongOperation().ToList();
        });
    }

Body:
Forget about the threading complication for now, and just take this code:

public IEnumerable<Person> GetPeopleListLongOperation()
{
    // forcing "long" data load
    Thread.Sleep(5000);
    yield return new Person();
}

When you call GetPeopleListLongOperation() it will return immediately, it won't wait 5 seconds. This is because iterator blocks like this are lazily evaluated; Thread.Sleep(5000) will only be called when you enumerate through the sequence.

Now you understand that, you should see that you 'fix' works because ToList will enumerate the sequence to completion while still on the thread pool thread and return the cached results. Without this you were enumerating the sequence on the UI thread on the call to result.First() and blocking it.


来源: stackexchange

问:
ReInitialize twitter-fabric
In MainActivity I use CrashLytic

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

     if (!newUser){
           if (!Fabric.isInitialized())
                    Fabric.with(context, new Crashlytics());
     } else {

        goToRegistrationFrame();

     }
   }
</code>```

I switch Fragment by this code, when User try to  restore his account
and I'm trying to reload application

```<code>Intent i = getActivity().getBaseContext().getPackageManager()
                        .getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
</code>```

After reload Application it's starting from registration fragment where I'm using Digits, and setting up new Fabric parameters

```<code>Fabric.with(getActivity(), new TwitterCore(authConfig),
                new Digits.Builder().withTheme(R.style.CustomDigitsTheme).build());
</code>```

But unfortunatly I see that Fabric.isInitialized() is TRUE, and as a result when I call :

```<code>Digits.authenticate(authConfigBuilder.build());
</code>```

I've got this exception:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'com.digits.sdk.android.AuthClient com.digits.sdk.android.Digits.getAuthClient()' on a null object reference
</code>```

My quesyion is:

How to reinitialize Fabric, I know that the problem is that Fabric was setted before and not cleaned whet application was reloaded.

Or how to reloadd application to get the same result and Fabric was not be initialized when I switch to new Fragment.

Thx

答:
I've found only one way, just reload app by this decisison
https://github.com/JakeWharton/ProcessPhoenix</p>

ContentLicense: CC BY-SA 3.0

Title: ReInitialize twitter-fabric

Body:
In MainActivity I use CrashLytic

 @Override
    protected void onCreate(Bundle savedInstanceState) {

     if (!newUser){
           if (!Fabric.isInitialized())
                    Fabric.with(context, new Crashlytics());
     } else {

        goToRegistrationFrame();

     }
   }

I switch Fragment by this code, when User try to  restore his account
and I'm trying to reload application

Intent i = getActivity().getBaseContext().getPackageManager()
                        .getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);

After reload Application it's starting from registration fragment where I'm using Digits, and setting up new Fabric parameters

Fabric.with(getActivity(), new TwitterCore(authConfig),
                new Digits.Builder().withTheme(R.style.CustomDigitsTheme).build());

But unfortunatly I see that Fabric.isInitialized() is TRUE, and as a result when I call :

Digits.authenticate(authConfigBuilder.build());

I've got this exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.digits.sdk.android.AuthClient com.digits.sdk.android.Digits.getAuthClient()' on a null object reference

My quesyion is:

How to reinitialize Fabric, I know that the problem is that Fabric was setted before and not cleaned whet application was reloaded.

Or how to reloadd application to get the same result and Fabric was not be initialized when I switch to new Fragment.

Thx


问:
What does the performSelector method do?
What does performSelector do? What is the difference between creating a new NSThread and the performSelector method?

How it works and where should we use it?

答:
All of these perform the same task, that is make the doStuff method on anObject execute synchronously on the current thread:

```<code>// 1
[anObject doStuff];

// 2
[anObject performSelector:@selector(doStuff)];

// 3
objc_msgSend(anObject, @selector(doStuff));

// 4
IMP imp = [anObject methodForSelector:@selector(doStuff)];
imp(anObject, @selector(doStuff));
</code>```

Is how you normally should go about to do stuff.

Is for dynamically dispatching a message. Use if the selector is unknown, or provided by a client, for example if you implement an target-action pattern. or if the class of anObject is unknown, usually used by first asking if the object has the method with -[NSObject respondsToSelector:].

Is what no 1. is actually compiled down to. Usually never any real need to do this.

Cached the actual IMP (implementation) for a method, and then call it directly. Can sometimes be faster than 1. if used in a tight loop. Just remember; premature optimization is evil.

What you need to grasp is that in Objective-C methods are more important than classes/interfaces. Usually you do not query an object if it belongs to a particular class, or conforms to any protocol, that is for the compiler to complain about. At run-time you instead query for specific methods.

In short: It does not matter what you are, just what you can do.

As a convenience NSObject also have several siblings to performSelector that are asynchronios. Most notably:

performSelector:withObject:afterDelay: - To execute the method on the current thread after a delay.

performSelectorInBackground:withObject: - To execute the method on a new background thread.

performSelectorOnMainThread:withObject:waitUntilDone: - To execute the method on the main thread.

performSelector:onThread:withObject:waitUntilDone: - To execute the method on any thread.

The asynchronous performers all depend on a NSRunLoop to function. This is not something you need to worry about unless you spawn a thread yourself. If you do then you need to also run the new threads run loop. Just skip that for now.

ContentLicense: CC BY-SA 2.5

Body:
All of these perform the same task, that is make the doStuff method on anObject execute synchronously on the current thread:

// 1
[anObject doStuff];

// 2
[anObject performSelector:@selector(doStuff)];

// 3
objc_msgSend(anObject, @selector(doStuff));

// 4
IMP imp = [anObject methodForSelector:@selector(doStuff)];
imp(anObject, @selector(doStuff));

Is how you normally should go about to do stuff.

Is for dynamically dispatching a message. Use if the selector is unknown, or provided by a client, for example if you implement an target-action pattern. or if the class of anObject is unknown, usually used by first asking if the object has the method with -[NSObject respondsToSelector:].

Is what no 1. is actually compiled down to. Usually never any real need to do this.

Cached the actual IMP (implementation) for a method, and then call it directly. Can sometimes be faster than 1. if used in a tight loop. Just remember; premature optimization is evil.

What you need to grasp is that in Objective-C methods are more important than classes/interfaces. Usually you do not query an object if it belongs to a particular class, or conforms to any protocol, that is for the compiler to complain about. At run-time you instead query for specific methods.

In short: It does not matter what you are, just what you can do.

As a convenience NSObject also have several siblings to performSelector that are asynchronios. Most notably:

performSelector:withObject:afterDelay: - To execute the method on the current thread after a delay.

performSelectorInBackground:withObject: - To execute the method on a new background thread.

performSelectorOnMainThread:withObject:waitUntilDone: - To execute the method on the main thread.

performSelector:onThread:withObject:waitUntilDone: - To execute the method on any thread.

The asynchronous performers all depend on a NSRunLoop to function. This is not something you need to worry about unless you spawn a thread yourself. If you do then you need to also run the new threads run loop. Just skip that for now.


问:
React Native ListView onEndReached doesn't called
I want to implement infinite scroll so I do this in my ListView tag

```<code>renderRow(data){
    return (
        <CardSection>
            <Text>
                {data.id}
            </Text>
        </CardSection>
    );
}

<ListView
    dataSource={this.dataSource}
    renderRow={this.renderRow}
    onEndReached = {this.loadMoreNews.bind(this)}
    pageSize = {5}
/>
</code>```

I get 5 data every fetch action that I call in loadMoreNews() and componentWillMount. Because the first 5 data doesn't fill the entire screen I expected that onEndReached to be called automatically since it already in the end of the ListView, but it doesn't.

I tried to style the Text tag in renderRow into this

```<code>renderRow(data){
    return (
        <CardSection>
            <Text style={{height:100}}>
                {data.id}
            </Text>
        </CardSection>
    );
}
</code>```

and it works as i want. I'm afraid that my renderRow won't fill the entire screen if my aplication is running in the wide screen device.

Is it the behavior of ListView or I missed something? What is the solution? I don't really want to force my component to be very big so it always fill the entire screen.

答:
You could compare component contentsize with height of the device and call loadMoreNews fn.</p>

```<code>const deviceHeight = Dimensions.get('window').height;

<ListView
   dataSource={this.dataSource}
   renderRow={this.renderRow}
   onLayout={(event) => {
      var layout = event.nativeEvent.layout;
      if(layout.height < deviceHeight) this.loadMoreNews()
   }}
   onEndReached = {this.loadMoreNews.bind(this)}
   pageSize = {5}
/>
</code>```

Body:
I want to implement infinite scroll so I do this in my ListView tag

renderRow(data){
    return (
        <CardSection>
            <Text>
                {data.id}
            </Text>
        </CardSection>
    );
}

<ListView
    dataSource={this.dataSource}
    renderRow={this.renderRow}
    onEndReached = {this.loadMoreNews.bind(this)}
    pageSize = {5}
/>

I get 5 data every fetch action that I call in loadMoreNews() and componentWillMount. Because the first 5 data doesn't fill the entire screen I expected that onEndReached to be called automatically since it already in the end of the ListView, but it doesn't.

I tried to style the Text tag in renderRow into this

renderRow(data){
    return (
        <CardSection>
            <Text style={{height:100}}>
                {data.id}
            </Text>
        </CardSection>
    );
}

and it works as i want. I'm afraid that my renderRow won't fill the entire screen if my aplication is running in the wide screen device.

Is it the behavior of ListView or I missed something? What is the solution? I don't really want to force my component to be very big so it always fill the entire screen.

Body:
You could compare component contentsize with height of the device and call loadMoreNews fn.

const deviceHeight = Dimensions.get('window').height;

<ListView
   dataSource={this.dataSource}
   renderRow={this.renderRow}
   onLayout={(event) => {
      var layout = event.nativeEvent.layout;
      if(layout.height < deviceHeight) this.loadMoreNews()
   }}
   onEndReached = {this.loadMoreNews.bind(this)}
   pageSize = {5}
/>


问:
How can I write if/else with Boolean in Bash?
How can I write an 'if then' statement to switch between these to variables as in the following?

```<code>if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}
</code>```

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

```<code>$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi
</code>```

答:
As addition to Gordon's excellent answer, in Bash you can also use the double-parentheses construct. It works for integers, and it is the closest form to other languages. Demo:

```<code>for i in {-2..2}; do
    printf "for %s " "$i"

    if (( i ))   # You can omit the `$`
    then
        echo is nonzero
    else
        echo is zero
    fi

done
</code>```

Output:

```<code>for -2 is nonzero
for -1 is nonzero
for 0 is zero
for 1 is nonzero
for 2 is nonzero
</code>```

You can use any arithmetic operations inside, e.g.:

```<code>for i in {1..6}; do
    printf "for %s " "$i"

    if (( i % 2 )) #modulo
    then
        echo odd
    else
        echo even
    fi
done
</code>```

Output

```<code>for 1 odd
for 2 even
for 3 odd
for 4 even
for 5 odd
for 6 even
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I write an 'if then' statement to switch between these to variables as in the following?

if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi

Body:
As addition to Gordon's excellent answer, in Bash you can also use the double-parentheses construct. It works for integers, and it is the closest form to other languages. Demo:

for i in {-2..2}; do
    printf "for %s " "$i"

    if (( i ))   # You can omit the `$`
    then
        echo is nonzero
    else
        echo is zero
    fi

done

Output:

for -2 is nonzero
for -1 is nonzero
for 0 is zero
for 1 is nonzero
for 2 is nonzero

You can use any arithmetic operations inside, e.g.:

for i in {1..6}; do
    printf "for %s " "$i"

    if (( i % 2 )) #modulo
    then
        echo odd
    else
        echo even
    fi
done

Output

for 1 odd
for 2 even
for 3 odd
for 4 even
for 5 odd
for 6 even


问:
ImportError: No module named lxml - Even though LXML Is installed
I'm getting this error "ImportError: No module named lxml" Even though LXML Is definitely installed. Specifically it's installed within the python Virtualenv for the project. and ultimately I'm working on the Python/Amazon Product API. I get the error after trying to run one of the example scripts for that project from the terminal (mac).

How can I fix this? or further track down the issue?

Google searching lead me to:

Reintsall LXML

Ensure Xcode license was agreed to: sudo xcodebuild -license

Updating LXML with: pip install --upgrade lxml Currently at ver 3.4.0

reinstalled LXML dependencies as outlined here - pip install libxml2-dev libxslt-dev python-dev

The line of code throwing the error is from lxml import etree, objectify, this is in a folder far away from where LXML is installed in my virtual environment (although I am running the script from within my virtualenv in terminal). If the issues is simply a matter of the script not knowing where to find the LXML install, how would I fix that?

答:
So it turns out that if you're using python via homebrew, things get a little sketchy with apps like Inkscape that have it hardcoded in their mind that a certain version of python is needed.

Getting the right python version was simply uninstalling brew & installing PIP:

brew uninstall --ignore-dependencies python

sudo easy_install pip

STATIC_DEPS=true sudo pip install lxml


问:
How to change certain words into the tagged forms of training lists
I tried to change certain strings into the forms of tagged words listed in train.

```<code>train = c('love/POS','happy/POS','sad/NEG','fearsome/NEG','lazy/NEG')
test = c('I love you', 'I am so happy now', 'You look sad somehow', 'the lazy boy look so fearsome')
</code>```

With them, I wanted to make an outcome like

```<code>[1]'I love/POS you' 'I am so happy/POS now' 'You look sad/NEG somehow' 'the lazy/NEG boy look so fearsome/NEG'
</code>```

Of course, I can use gsub like this as a primitive way

```<code>part1 = gsub('love', 'love/POS', test)
part2 = gsub('happy', 'happy/POS', part1)
.......
</code>```

However, this way is not productive at all when I have bigger training lists.

In order to make it possible in a more effective way, I tried

```<code>process1 = unlist(strsplit(test, '[[:space:]]+'))

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

trainedtest = mgsub(process1, train, test)
trainedtest
</code>```

In fact, it is not working at all because the length of process1 and train lists are not same. Technically, I should make a program which can select certain words to change into tagged forms of train lists, calculating similarities between process1 and train.

Is there any way to make it possible?

答:
Here is a base R solution using match with nomatch = 0 (i.e. return nothing for no match - default is NA)

```<code>v1 <- sub('/.*', '', train)
sapply(strsplit(test, ' '), function(i)
       {i[grepl(paste(v1, collapse = '|'), i)] <- train[match(i, v1, nomatch = 0)];
                                                              paste(i, collapse = ' ')})

#[1] "I love/POS you"    "I am so happy/POS now"  "You look sad/NEG somehow"
#[4] "the lazy/NEG boy look so fearsome/NEG"
</code>```

Body:
I tried to change certain strings into the forms of tagged words listed in train.

train = c('love/POS','happy/POS','sad/NEG','fearsome/NEG','lazy/NEG')
test = c('I love you', 'I am so happy now', 'You look sad somehow', 'the lazy boy look so fearsome')

With them, I wanted to make an outcome like

[1]'I love/POS you' 'I am so happy/POS now' 'You look sad/NEG somehow' 'the lazy/NEG boy look so fearsome/NEG'

Of course, I can use gsub like this as a primitive way

part1 = gsub('love', 'love/POS', test)
part2 = gsub('happy', 'happy/POS', part1)
.......

However, this way is not productive at all when I have bigger training lists.

In order to make it possible in a more effective way, I tried

process1 = unlist(strsplit(test, '[[:space:]]+'))

mgsub <- function(pattern, replacement, x, ...) {
  if (length(pattern)!=length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }
  result <- x
  for (i in 1:length(pattern)) {
    result <- gsub(pattern[i], replacement[i], result, ...)
  }
  result
}

trainedtest = mgsub(process1, train, test)
trainedtest

In fact, it is not working at all because the length of process1 and train lists are not same. Technically, I should make a program which can select certain words to change into tagged forms of train lists, calculating similarities between process1 and train.

Is there any way to make it possible?

Body:
Here is a base R solution using match with nomatch = 0 (i.e. return nothing for no match - default is NA)

v1 <- sub('/.*', '', train)
sapply(strsplit(test, ' '), function(i)
       {i[grepl(paste(v1, collapse = '|'), i)] <- train[match(i, v1, nomatch = 0)];
                                                              paste(i, collapse = ' ')})

#[1] "I love/POS you"    "I am so happy/POS now"  "You look sad/NEG somehow"
#[4] "the lazy/NEG boy look so fearsome/NEG"


问:
How to broker secure connection across firewalls using untrusted host?
I have an interesting network security challenge that I can't figure out the best way to attack.

I need to provide a way to allow two computers (A and B) that are behind firewalls to make a secure connection to each other using only a common "broker" untrusted server on the internet (somewhere like RackSpace). (the server is considered untrusted because the customers behind the firewalls won't trust it since it is on an open server) I can not adjust the firewall settings to allow the networks to directly connect to each other because the connections are no known ahead of time.

This is very similar to a NAT to NAT connection problem like that handled by remote desktop help tools (crossloop, copilot, etc).

What I would really like to find is a way to open an SSL connection between the two hosts and have the public server broker the connection.  Preferably when host A tries to connect to host B, it should have to provide a token that the broker can check with host B before establishing the connection.

To add another wrinkle to this, the connection mechanism needs to support two types of communication.  First, HTTP request/response to a REST web service and second persistent socket connection(s) to allow for real-time message passing.

I have looked at the techniques I know about like OpenSSL using certificates, OAuth, etc, but I don't see anything that quite does what I need.

Has anyone else handled something like this before?  Any pointers?

答: In general, SSL is packet-based protocol (for the purpose of solving your task). If you can have the host forward the packets back and forth, you can easily have SSL-secured communication channel. One thing you need is something like our SSL/TLS components, which allow any transport and not just sockets. I.e. the component tells your code "send this packet to the other side" or "do you have anything for me to receive?" and your code communicates with your intermediate server. </p>


问:
How do center an image within another image and have it responsive to mobile landscape?
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

```<code>.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}
</code>```

working, sort of. The HTML:

```<code><div class="parent">
<img class="image1" src="https://placehold.it/1"/ alt="1">
<img class="image2" src="https://placehold.it/2"/ alt="2">
</div>
</code>```

答:
About responsiveness, use 'media query'

set width for image 2, for example, 50%

now set left: 25%

Body:
I have a play image which needs centering over another image. I'm using percentages, to try to have it working on all devices, but the percentages are not acting like they should. I have taken screenshots of the mobile site in portrait and landscape, you can find them here http://imgur.com/a/gN53f

The desktop site has an entirely different row which is hidden on small devices, the code below is visible exclusively on the mobile site.

Here's the css:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
  z-index: 1;
}
.image2 {
  position: absolute;
  top: 30%;
  left: 43%;
  z-index: 2;
}

working, sort of. The HTML:


问:
GridView event raise unexpectedly after postback
Consider this Asp.net page code:

```<code><head runat="server">
<title></title>
<script type="text/javascript">
        function showhide(master, detail) {
            var src = $(master).children()[0].src;
            if (src.endsWith("plus.png"))
                src = src.replace('plus.png', 'minus.png');
            else
                src = src.replace('minus.png', 'plus.png');

            $(master).children()[0].src = src;

            $(detail).slideToggle("normal");
        }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/scripts/jquery-1.6.2.min.js" ScriptMode="Release" />
    </Scripts>
</asp:ScriptManager>
<div>
<asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
    SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders
FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID]
Group By [Customers].[CustomerID], [Customers].[CompanyName]">
</asp:SqlDataSource>
    <asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
        DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>'
                        onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
                        <asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
                            Style="margin-right: 5px;" runat="server" /><span class="header">
                                <%#Eval("CustomerID")%>
                                :
                                <%#Eval("CompanyName")%>
                                (<%#Eval("TotalOrders")%>Orders) </span>
                    </div>
                    <div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
                        <asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="ddd" runat="server"
                            ShowHeader="true" EnableViewState="false">
                            <RowStyle CssClass="row" />
                            <AlternatingRowStyle CssClass="altrow" />
                            <Columns>
                                <asp:TemplateField ItemStyle-CssClass="rownum">
                                    <ItemTemplate>
                                        <%# Container.DataItemIndex + 1 %>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
                                <asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="100px" />
                                <asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="110px" />
                                <asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
                                    ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
                                <asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="100px" />
                            </Columns>
                        </asp:GridView>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</code>```

and the code behind:

```<code>protected void Page_Load(object sender, EventArgs e)
{

}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string custID = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            List<Order> ord = (from o in dc.Orders
                               where o.CustomerID == custID.Trim()
                               select o).ToList();

            GridView ctrl = e.Row.FindControl("ddd") as GridView;
            ctrl.DataSource = ord;
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("Default.aspx");
}
</code>```

the problem is when I Click on Button1 to redirect to another page gvCustomers_RowCreated raise and I get Null reference error.Why this event raised after postback?

EDIT 1):

I removed SqlDataSource and bind GridView in the code behind like this:

```<code>public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            var query = dc.ExecuteQuery<clsRetern>("SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID] Group By [Customers].[CustomerID], [Customers].[CompanyName]").ToList();

            List<clsRetern> ret = new List<clsRetern>();
            foreach (var item in query)
            {
                clsRetern r = new clsRetern();
                r.CompanyName = item.CompanyName;
                r.CustomerID = item.CustomerID;
                r.TotalOrders = item.TotalOrders;

                ret.Add(r);
            }

            gvCustomers.DataSource = ret;
            gvCustomers.DataBind();
        }
    }
}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string custID = ((clsRetern)e.Row.DataItem).CustomerID.Trim();
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            List<Order> ord = (from o in dc.Orders
                               where o.CustomerID == custID.Trim()
                               select o).ToList();

            GridView ctrl = e.Row.FindControl("ddd") as GridView;
            ctrl.DataSource = ord;
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("Default.aspx",true);
}
}

public class clsRetern
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
   public int TotalOrders { get; set; }
}
</code>```

I tried Response.Redirect("Default.aspx"); but the problem still remains.

答: Add EnableViewState=False to the page directive to prevent "RowCreated" running on every post back.</p>

Body:
Consider this Asp.net page code:

<title></title>

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

<asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
    SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders
FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID]
Group By [Customers].[CustomerID], [Customers].[CompanyName]">
</asp:SqlDataSource>
    <asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
        DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>'
                        onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
                        <asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
                            Style="margin-right: 5px;" runat="server" />
                                <%#Eval("CustomerID")%>
                                :
                                <%#Eval("CompanyName")%>
                                (<%#Eval("TotalOrders")%>Orders)

                    <div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
                        <asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="ddd" runat="server"
                            ShowHeader="true" EnableViewState="false">
                            <RowStyle CssClass="row" />
                            <AlternatingRowStyle CssClass="altrow" />
                            <Columns>
                                <asp:TemplateField ItemStyle-CssClass="rownum">
                                    <ItemTemplate>
                                        <%# Container.DataItemIndex + 1 %>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
                                <asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="100px" />
                                <asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="110px" />
                                <asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
                                    ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
                                <asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
                                    ItemStyle-Width="100px" />
                            </Columns>
                        </asp:GridView>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>

and the code behind:

protected void Page_Load(object sender, EventArgs e)
{

}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string custID = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            List<Order> ord = (from o in dc.Orders
                               where o.CustomerID == custID.Trim()
                               select o).ToList();

            GridView ctrl = e.Row.FindControl("ddd") as GridView;
            ctrl.DataSource = ord;
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("Default.aspx");
}

the problem is when I Click on Button1 to redirect to another page gvCustomers_RowCreated raise and I get Null reference error.Why this event raised after postback?

EDIT 1):

I removed SqlDataSource and bind GridView in the code behind like this:

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            var query = dc.ExecuteQuery<clsRetern>("SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID] Group By [Customers].[CustomerID], [Customers].[CompanyName]").ToList();

            List<clsRetern> ret = new List<clsRetern>();
            foreach (var item in query)
            {
                clsRetern r = new clsRetern();
                r.CompanyName = item.CompanyName;
                r.CustomerID = item.CustomerID;
                r.TotalOrders = item.TotalOrders;

                ret.Add(r);
            }

            gvCustomers.DataSource = ret;
            gvCustomers.DataBind();
        }
    }
}
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string custID = ((clsRetern)e.Row.DataItem).CustomerID.Trim();
        using (DataClassesDataContext dc=new DataClassesDataContext())
        {
            List<Order> ord = (from o in dc.Orders
                               where o.CustomerID == custID.Trim()
                               select o).ToList();

            GridView ctrl = e.Row.FindControl("ddd") as GridView;
            ctrl.DataSource = ord;
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("Default.aspx",true);
}
}

public class clsRetern
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
   public int TotalOrders { get; set; }
}

I tried Response.Redirect("Default.aspx"); but the problem still remains.


问:
How to run Quarz Cron Job between specific time?
I want to execute cron job between specific time. i.e. Cron job should execute every 15 minutes between 7:03 to 21:04?

I can manage between 7 to 9 but can't schedule between 7:03 to 9:05.

答:
After understanding your requirement clearly, AFAIK, you need two schedulers:

First Scheduler (runs between hours 07:00 to 21:00):

Cron expression should be like 0 3/15 7-20 * * *

0 - seconds

3/15 - runs at 3rd, 18th, 33rd, 48th minutes of each hour

7-20 - starting from 07AM to 08PM (included)

Second Scheduler (runs ONLY at 21:04):

Cron expression should be like 0 4 21 * * * (which runs ONLY at 21:04)


问:
Elements from xml using php
so I can access an xml file and all its elements using

```<code>$xml = simplexml_load_file('file.xml');
</code>```

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

```<code><images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >
</code>```

I am in desperate need to loop through these images and get their Url. For that I've tried:

```<code>$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '<br>';
    $i++
}
</code>```

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

答:
OK - I've changed it to 'load_string' for my example, but this works fine.  I think that you maybe overcomplicating it?

```<code>$file = '
<images>
    <image id="1" time_modif="1490197696">
       http://www.image123.com
    </image>
    <image id="2" time_modif="1490197699">
        http://www.image234.com
    </image>
    <image id="3" time_modif="1490197702">
        http://www.image456.com
    </image>
</images >';

$xml = simplexml_load_string($file);

foreach ($xml as $img)
{
    echo $img.'<br>';
}
</code>```

Outputs:

http://www.image123.com

http://www.image234.com

http://www.image456.com

Title: Elements from xml using php

Body:
so I can access an xml file and all its elements using

$xml = simplexml_load_file('file.xml');

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

<images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >

I am in desperate need to loop through these images and get their Url. For that I've tried:

$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '
';
    $i++
}

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

Body:
OK - I've changed it to 'load_string' for my example, but this works fine.  I think that you maybe overcomplicating it?

$file = '
<images>
    <image id="1" time_modif="1490197696">
       http://www.image123.com
    </image>
    <image id="2" time_modif="1490197699">
        http://www.image234.com
    </image>
    <image id="3" time_modif="1490197702">
        http://www.image456.com
    </image>
</images >';

$xml = simplexml_load_string($file);

foreach ($xml as $img)
{
    echo $img.'<br>';
}

Outputs:

http://www.image123.com

http://www.image234.com

http://www.image456.com


问:
Same inputid in 2 conditionalPanel - Shiny
I'm a Shiny newbie and was trying to get something simple working, but unable to :(

Here is a part of my ui.R

```<code>sidebarLayout(
  sidebarPanel(

    radioButtons("market",
                 "Choose a Region to build the Sales file:",
                 c("North America & ANZ" = "NA", "Europe" = "EU"), inline = TRUE),

    conditionalPanel(
      condition = "input.market == 'NA'",
      radioButtons("Locale",
                   "Choose a locale to see the sales Calendar:",
                   c("US and Canada" = "US_CA", "ANZ" = "ANZ"), inline = TRUE),

      numericInput("sale_num", "Choose a Sale Number from the Table below",1,width = '100px' )

    ),

    conditionalPanel(
      condition = "input.market == 'EU'",
      radioButtons("Locale",
                   "Choose a locale to see the sales Calendar:",
                   c("UK" = "UK", "FR and RoE" = "FR_ROE","DE,AT & CH" = "DACH"), inline = TRUE),
      numericInput("sale_num", "Choose a Sale Number from the Table below",1,width = '100px' )),

    dataTableOutput("sales"))

  ),
</code>```

Here is my  server.R

```<code>server <- shinyServer(function(input, output) {
       output$sales <- renderDataTable({
       saleTable(input$Locale)
       },options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
 })
</code>```

When a change in the market radio button is triggered, the Locale radio does not update and hence the sales output table still has stale values and is not reflected by any change in Locale values.

I know I'm supposed to use something like UpdateRadiobuttons, but I'm not sure how. :(

saleTable is just a function in my Rscript that produces a data table.

Please help!

Thanks in advance!

答:
Please post a minimal example, i.e. your function saleTable. Don't use the same input ID twice in your app, it's bad style and will not work in most cases. Here are two solutions: First one is bad style, second one better style.

1) Rename the second Locale to Locale2 and put this in your output$sales:

```<code>output$sales <- renderDataTable({
    if(input$market == 'NA') data <- input$Locale
    else if(input$market=="EU") data <- input$Locale2
    saleTable(data)
    }, options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
)
</code>```

2) Create the second output as UIOutput and make it dependent on the first one:

```<code>ui <- shinyUI(
  sidebarLayout(
    sidebarPanel(
          radioButtons("market",
                   "Choose a Region to build the Sales file:",
                   c("North America & ANZ" = "NA", "Europe" = "EU"), inline = TRUE),
      uiOutput("Locale")),
      mainPanel(dataTableOutput("sales"))))

server <- function(input, output, session) {
  output$Locale <- renderUI({
    if(input$market == "NA") myChoices <-  c("US and Canada" = "US_CA", "ANZ" = "ANZ")
    else myChoices <- c("UK" = "UK", "FR and RoE" = "FR_ROE","DE,AT & CH" = "DACH")

  radioButtons("Locale","Choose a locale to see the sales Calendar:",
                choices <- myChoices,
                 inline = TRUE)
  })
  output$sales <- renderDataTable({
    saleTable(input$Locale)
  },options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
}

shinyApp(ui = ui, server = server)
</code>```

Body:
I'm a Shiny newbie and was trying to get something simple working, but unable to :(

Here is a part of my ui.R

sidebarLayout(
  sidebarPanel(

    radioButtons("market",
                 "Choose a Region to build the Sales file:",
                 c("North America & ANZ" = "NA", "Europe" = "EU"), inline = TRUE),

    conditionalPanel(
      condition = "input.market == 'NA'",
      radioButtons("Locale",
                   "Choose a locale to see the sales Calendar:",
                   c("US and Canada" = "US_CA", "ANZ" = "ANZ"), inline = TRUE),

      numericInput("sale_num", "Choose a Sale Number from the Table below",1,width = '100px' )

    ),

    conditionalPanel(
      condition = "input.market == 'EU'",
      radioButtons("Locale",
                   "Choose a locale to see the sales Calendar:",
                   c("UK" = "UK", "FR and RoE" = "FR_ROE","DE,AT & CH" = "DACH"), inline = TRUE),
      numericInput("sale_num", "Choose a Sale Number from the Table below",1,width = '100px' )),

    dataTableOutput("sales"))

  ),

Here is my  server.R

server <- shinyServer(function(input, output) {
       output$sales <- renderDataTable({
       saleTable(input$Locale)
       },options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
 })

When a change in the market radio button is triggered, the Locale radio does not update and hence the sales output table still has stale values and is not reflected by any change in Locale values.

I know I'm supposed to use something like UpdateRadiobuttons, but I'm not sure how. :(

saleTable is just a function in my Rscript that produces a data table.

Please help!

Thanks in advance!

Body:
Please post a minimal example, i.e. your function saleTable. Don't use the same input ID twice in your app, it's bad style and will not work in most cases. Here are two solutions: First one is bad style, second one better style.

1) Rename the second Locale to Locale2 and put this in your output$sales:

output$sales <- renderDataTable({
    if(input$market == 'NA') data <- input$Locale
    else if(input$market=="EU") data <- input$Locale2
    saleTable(data)
    }, options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
)

2) Create the second output as UIOutput and make it dependent on the first one:

ui <- shinyUI(
  sidebarLayout(
    sidebarPanel(
          radioButtons("market",
                   "Choose a Region to build the Sales file:",
                   c("North America & ANZ" = "NA", "Europe" = "EU"), inline = TRUE),
      uiOutput("Locale")),
      mainPanel(dataTableOutput("sales"))))

server <- function(input, output, session) {
  output$Locale <- renderUI({
    if(input$market == "NA") myChoices <-  c("US and Canada" = "US_CA", "ANZ" = "ANZ")
    else myChoices <- c("UK" = "UK", "FR and RoE" = "FR_ROE","DE,AT & CH" = "DACH")

  radioButtons("Locale","Choose a locale to see the sales Calendar:",
                choices <- myChoices,
                 inline = TRUE)
  })
  output$sales <- renderDataTable({
    saleTable(input$Locale)
  },options = list(autoWidth = FALSE,searching = FALSE,pageLength=10))
}

shinyApp(ui = ui, server = server)


问:
VBA - Evaluate returning #VALUE
A formula with Evaluate works fine in a test workbook.
All results are good.

Exactlythe same code  returns #Value in the workbook I should use (that contains other macros).
The error code is 2029.
In addition, when I only put in the sheet the formula resulting from the code (either when debugging or directly in the code), the result is correct if I do Ctrl+Shft+Enter in the cell where the formula is .

As a consequence, what I understand is that the formula is not evaluated by Application.Evaluate.
Any hints of the possible cause ?
The following is part of the code

```<code>Const TEMPLATE = "=INDEX({0},MATCH(1,({1}={2})*({3}={4}),{5}))"
Const MATCH_TYPE = 0

Dim originalReferenceStyle
originalReferenceStyle = xlA1
Application.ReferenceStyle = xlR1C1

Dim myFormula As String
myFormula = Replace(TEMPLATE, "{0}", amountRange.Address(External:=True))
myFormula = Replace(myFormula, "{1}", accountRange.Address(External:=True))
myFormula = Replace(myFormula, "{2}", accountCriteria.Address(External:=True))
myFormula = Replace(myFormula, "{3}", dateRange.Address(External:=True))
myFormula = Replace(myFormula, "{4}", dateCriteria.Address(External:=True))
myFormula = Replace(myFormula, "{5}", MATCH_TYPE)
myIndexMatch = Application.Evaluate(myFormula)
</code>```

答:
If you're facing a similar problem, try reducing the length of the formula !
It seems that Evaluate doesn't like formulas of more than 255 characters (same with FormulaArray) !!!
Take care that if you refer to ranges with (External:=True) in your formula, the name of the file is included... In my case, reducing the file name to 2 letters did the trick !
Hope this will help...</p>

Title: VBA - Evaluate returning #VALUE

Body:
A formula with Evaluate works fine in a test workbook.
All results are good.

Exactlythe same code  returns #Value in the workbook I should use (that contains other macros).
The error code is 2029.
In addition, when I only put in the sheet the formula resulting from the code (either when debugging or directly in the code), the result is correct if I do Ctrl+Shft+Enter in the cell where the formula is .

As a consequence, what I understand is that the formula is not evaluated by Application.Evaluate.
Any hints of the possible cause ?
The following is part of the code

Const TEMPLATE = "=INDEX({0},MATCH(1,({1}={2})*({3}={4}),{5}))"
Const MATCH_TYPE = 0

Dim originalReferenceStyle
originalReferenceStyle = xlA1
Application.ReferenceStyle = xlR1C1

Dim myFormula As String
myFormula = Replace(TEMPLATE, "{0}", amountRange.Address(External:=True))
myFormula = Replace(myFormula, "{1}", accountRange.Address(External:=True))
myFormula = Replace(myFormula, "{2}", accountCriteria.Address(External:=True))
myFormula = Replace(myFormula, "{3}", dateRange.Address(External:=True))
myFormula = Replace(myFormula, "{4}", dateCriteria.Address(External:=True))
myFormula = Replace(myFormula, "{5}", MATCH_TYPE)
myIndexMatch = Application.Evaluate(myFormula)


问:
how to log http redirects when using Safari
Safari seems not to log http redirects in the network inspector tool.

I'm in a environment where I can't use http proxy (like Charles) so I'm wondering if there's any safari plugin able to do that.

Thanks.

答:
Unfortunately, this is a bug in webkit:

Web Inspector: Redirect requests are not shown in either Network or Timeline tabs

According to the page, the bug status is "NEW", so it's not fixed yet.

I've searched in Safari extension market but nothing is found.

I also find this SO post and confirmed that in the latest Safari Technology Overview, Network requests info can be preserved when page navigates. However, redirect requests are not "preserved".


问:
Apache is downloading php files instead of displaying them
OS and server information:

CentOS 6.4 (Final)

Apache 2.2.15

PHP 5.5.1

I previously had php 5.3.x installed but decided to upgrade. I first uninstalled the php 5.3.x and then installed php 5.5.1 but after the installation completed apache did not parse the php files it just downloaded them. I have checked similar questions here in stackoverflow but none of them have helped me so far.

For the record I have the following lines in my httpd.conf and php.conf that should make php work but don't:

```<code>AddHandler application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml
AddType application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml
AddType application/x-httpd-php-source .phps
AddHandler php5-script .php
</code>```

I would really appreciate any help.
Thank you.

EDIT:

I have these lines in the php.conf

```<code><IfModule !worker.c>
  LoadModule php5_module modules/libphp5.so
</IfModule>
<IfModule worker.c>
  LoadModule php5_module modules/libphp5-zts.so
</IfModule>
</code>```

EDIT:

By removing the

```<code>AddType application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml
</code>```

apache no longer downloads the file. Now apache is showing the source code, but not all of it just part. I added

```<code>AddType text/html .php
</code>```

but no luck.

答: I had this problem. It turned out that I had both nginx and apache installed and automatically starting on boot. The problem was that nginx was binding to the http port first which prevented apache from starting.</p>

Body:
OS and server information:

CentOS 6.4 (Final)

Apache 2.2.15

PHP 5.5.1

I previously had php 5.3.x installed but decided to upgrade. I first uninstalled the php 5.3.x and then installed php 5.5.1 but after the installation completed apache did not parse the php files it just downloaded them. I have checked similar questions here in stackoverflow but none of them have helped me so far.

For the record I have the following lines in my httpd.conf and php.conf that should make php work but don't:

AddHandler application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml
AddType application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml
AddType application/x-httpd-php-source .phps
AddHandler php5-script .php

I would really appreciate any help.
Thank you.

EDIT:

I have these lines in the php.conf

<IfModule !worker.c>
  LoadModule php5_module modules/libphp5.so
</IfModule>
<IfModule worker.c>
  LoadModule php5_module modules/libphp5-zts.so
</IfModule>

EDIT:

By removing the

AddType application/x-httpd-php .php5 .php4 .php .php3 .php2 .phtml

apache no longer downloads the file. Now apache is showing the source code, but not all of it just part. I added

AddType text/html .php

but no luck.


问:
Why does Internet Explorer not like this jQuery?
While debugging some jQuery that is not working in IE, I found this error message:

```<code>var item = $("#item_"+ itemArray[itemIndex]).find('a').text().trim();

Object doesn't support this property or method (script.js, line 100, character 2)
</code>```

The character 2 doesn't make sense to me. Based on the text displayed character 2 would be the letter a in var but of course that doesn't make any sense.

(Should I not use var?)

I know that jQuery is working to some extent or the script would not have been able to get this far on my page.

答:
IE doesn't have a trim method.

Instead, you can call jQuery.trim(...).

Body:
While debugging some jQuery that is not working in IE, I found this error message:

var item = $("#item_"+ itemArray[itemIndex]).find('a').text().trim();

Object doesn't support this property or method (script.js, line 100, character 2)

The character 2 doesn't make sense to me. Based on the text displayed character 2 would be the letter a in var but of course that doesn't make any sense.

(Should I not use var?)

I know that jQuery is working to some extent or the script would not have been able to get this far on my page.


问:
Moving cells to last row without erasing over existing
The following code checks to see if any of my rows on the main page contain a date from a year ago or older. If it does, it copies it to the "Archive" worksheet and deletes it from the main page. However, what it's doing now is just copying from the main page and overriding what already exists on the archive page instead of adding to the last row. I've tried subbing in LastRow from a function, but I was getting an error with how I was using it. Anyone have a better solution?</p>

```<code>Sub TestDateTransfer()
With Application
PrevCalc = .Calculation
.Calculation = xlCalculationManual
.Cursor = xlWait
.Calculate
.EnableEvents = False
.ScreenUpdating = False
End With
Application.DisplayAlerts = False
Worksheets("Archive").Activate
Range("A3:I1000").Select
Selection.ClearContents
Worksheets("Main Page").Activate
Dim MyDate As Date
MyDate = "03/27/2017"
Set i = Sheets("Main Page")
Set E = Sheets("Archive")
Dim d
Dim j
d = 2
j = 2

Do Until IsEmpty(i.Range("C" & j))

  If i.Range("C" & j) <= MyDate - 365 Then
  d = d + 1
  E.rows(d).Value = i.rows(j).Value

  End If
  j = j + 1
 Loop
 Worksheets("Archive").Activate
 ActiveSheet.Range("H1").Select 'To unselect the page
 Worksheets("Main Page").Activate
 MyDate = "03/27/2017"
 Dim y
 Dim z
 y = 2
 z = 2
 Do Until IsEmpty(i.Range("C" & z))

  If i.Range("C" & z) <= MyDate - 365 Then
  y = y + 1
  i.rows(z).Delete

  End If
  z = z + 1
  Loop
 With Application
.Cursor = xlDefault
.Calculate
.Calculation = PrevCalc
'.ScreenUpdating = True 'Not Needed...
.EnableEvents = True
 End With
 ActiveSheet.Range("H1").Select
 End Sub
</code>```

答:
You could exploit AutoFilter() method of Range object and copy/paste filtered rows in one shot:

```<code>Option Explicit

Sub main()
    Dim MyDate As Date
    MyDate = "03/27/2017"

    Dim E As Worksheet
    Set E = Worksheets("Archive")

    With Worksheets("Main Page")
        With .Range("C1", .Cells(.Rows.Count, "C").End(xlUp))
            .AutoFilter field:=1, Criteria1:="<=" & CDbl((MyDate - 365))
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Intersect(.Parent.UsedRange, .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow).Copy Destination:=E.Cells(Rows.Count, 1).End(xlUp).Offset(1)
        End With
        .AutoFilterMode = False
    End With
End Sub
</code>```

Body:
The following code checks to see if any of my rows on the main page contain a date from a year ago or older. If it does, it copies it to the "Archive" worksheet and deletes it from the main page. However, what it's doing now is just copying from the main page and overriding what already exists on the archive page instead of adding to the last row. I've tried subbing in LastRow from a function, but I was getting an error with how I was using it. Anyone have a better solution?

Sub TestDateTransfer()
With Application
PrevCalc = .Calculation
.Calculation = xlCalculationManual
.Cursor = xlWait
.Calculate
.EnableEvents = False
.ScreenUpdating = False
End With
Application.DisplayAlerts = False
Worksheets("Archive").Activate
Range("A3:I1000").Select
Selection.ClearContents
Worksheets("Main Page").Activate
Dim MyDate As Date
MyDate = "03/27/2017"
Set i = Sheets("Main Page")
Set E = Sheets("Archive")
Dim d
Dim j
d = 2
j = 2

Do Until IsEmpty(i.Range("C" & j))

  If i.Range("C" & j) <= MyDate - 365 Then
  d = d + 1
  E.rows(d).Value = i.rows(j).Value

  End If
  j = j + 1
 Loop
 Worksheets("Archive").Activate
 ActiveSheet.Range("H1").Select 'To unselect the page
 Worksheets("Main Page").Activate
 MyDate = "03/27/2017"
 Dim y
 Dim z
 y = 2
 z = 2
 Do Until IsEmpty(i.Range("C" & z))

  If i.Range("C" & z) <= MyDate - 365 Then
  y = y + 1
  i.rows(z).Delete

  End If
  z = z + 1
  Loop
 With Application
.Cursor = xlDefault
.Calculate
.Calculation = PrevCalc
'.ScreenUpdating = True 'Not Needed...
.EnableEvents = True
 End With
 ActiveSheet.Range("H1").Select
 End Sub

Body:
You could exploit AutoFilter() method of Range object and copy/paste filtered rows in one shot:

Option Explicit

Sub main()
    Dim MyDate As Date
    MyDate = "03/27/2017"

    Dim E As Worksheet
    Set E = Worksheets("Archive")

    With Worksheets("Main Page")
        With .Range("C1", .Cells(.Rows.Count, "C").End(xlUp))
            .AutoFilter field:=1, Criteria1:="<=" & CDbl((MyDate - 365))
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Intersect(.Parent.UsedRange, .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow).Copy Destination:=E.Cells(Rows.Count, 1).End(xlUp).Offset(1)
        End With
        .AutoFilterMode = False
    End With
End Sub


问:
perl compare sorted array using smart match
The following is the code, actually, @arr0 and @arr1 are not equal, even after sorting, they are not equal, but why "eq" will be printed? at first, I thought about the return value of sort funtion, but it did return an array,so what's the reason?</p>

```<code>my @arr0 = (1,2);
my @arr1 = ("a","b");

if ( (sort @arr0) ~~ (sort @arr1) ) {
    print "eq\n";
};
</code>```

答:
[Note: All links to documentation in this answer are to the documentation for version 5.12.1. This ensures the answer is useful for the original poster - it might make it less useful for other people.]

It's important to realise that arrays and lists are not the same. This is one case where the behaviour is different.

It's also important to read the documentation for sort(), which starts by saying:

In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of sort() is undefined.

There are two important things there. Firstly, in list context, sort() returns a list, not an array. And secondly, in scalar context, its behaviour is undefined.

Now let's look at the smartmatch documentation. That's a big table of left- and right-operands that I won't reproduce here. But note that it doesn't mention lists at all. So, almost certainly, smartmatch is calling sort() in scalar context and doing either a string or numeric comparison
on the results (one of the last few rows in the table).

But we know that sort()'s behaviour in scalar context is undefined. So who knows what value smartmatch is comparing. But I guess that whatever random value it is returning, it is (at least) returning the same random value for both of your lists. Which means they appear to be equal.

As you've said in a comment, it works when you save the sorted results in arrays and pass arrays to smartmatch. That's because arrays have special behaviours defined in the smartmatch table.

Arrays are not lists

Don't call sort() in scalar context

Update: As ThisSuitIsNotBlack mentions in the comments, smartmatch has been rather unstable since it was introduced in Perl 5.10. Its behaviour has been tweaked in pretty much every Perl release since then and its final form still isn't completely agreed. For that reason, I strongly discourage you from using it at all.

Body:
The following is the code, actually, @arr0 and @arr1 are not equal, even after sorting, they are not equal, but why "eq" will be printed? at first, I thought about the return value of sort funtion, but it did return an array,so what's the reason?

my @arr0 = (1,2);
my @arr1 = ("a","b");

if ( (sort @arr0) ~~ (sort @arr1) ) {
    print "eq\n";
};


问:
How to Fill the data in google spreadsheet after creation of sheet?
I have a script that create's an empty google spreadsheet.
after creation of google spreadsheet. how i can add some data in it?

just some string is enough

script for creating the file :

```<code>function createSpread()
{

                var name =   $('[name=id]').val();
                gapi.client.load('drive', 'v2', function() {

                var request = gapi.client.request({
                   'path': '/drive/v2/files/',
                   'method': 'POST',
                   'headers': {
                       'Content-Type': 'application/json',
                   },
                   'body':{
                       "title" : name,
                       "mimeType" : "application/vnd.google-apps.spreadsheet",
                       "parents": [{
                            "kind": "drive#file",
                            "id": FOLDER_ID,
                        }],
                   }
                });
                request.execute(function(resp) { console.log(resp)

                });
            });
}
</code>```

Can you please help anyone

Thanks in advance

答:
Just an additonal tip for you, here's a code snippet I use when I'm writing to a spreadsheet using Sheets API.

```<code> function writeToSheet(){

        //Sheet1 is the name of the my sheet
        // "range":"Sheet1!"+A+":"+C, means column A to C since im writing 3 items
         var params = {
           "range":"Sheet1!"+A+":"+C,
           "majorDimension": "ROWS",
           "values": [
           ["name","address", "email"]
          ],
         }
         var xhr = new XMLHttpRequest();
         xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/'+myspreadsheetId+'/'+"values/"+"Sheet1!"+A+":"+C+"?"+'valueInputOption=USER_ENTERED');
         xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);

        xhr.send(JSON.stringify(params));
      }
</code>```

More samples are found in Basic Writing.

Body:
I have a script that create's an empty google spreadsheet.
after creation of google spreadsheet. how i can add some data in it?

just some string is enough

script for creating the file :

function createSpread()
{

                var name =   $('[name=id]').val();
                gapi.client.load('drive', 'v2', function() {

                var request = gapi.client.request({
                   'path': '/drive/v2/files/',
                   'method': 'POST',
                   'headers': {
                       'Content-Type': 'application/json',
                   },
                   'body':{
                       "title" : name,
                       "mimeType" : "application/vnd.google-apps.spreadsheet",
                       "parents": [{
                            "kind": "drive#file",
                            "id": FOLDER_ID,
                        }],
                   }
                });
                request.execute(function(resp) { console.log(resp)

                });
            });
}

Can you please help anyone

Thanks in advance

Body:
Just an additonal tip for you, here's a code snippet I use when I'm writing to a spreadsheet using Sheets API.

 function writeToSheet(){

        //Sheet1 is the name of the my sheet
        // "range":"Sheet1!"+A+":"+C, means column A to C since im writing 3 items
         var params = {
           "range":"Sheet1!"+A+":"+C,
           "majorDimension": "ROWS",
           "values": [
           ["name","address", "email"]
          ],
         }
         var xhr = new XMLHttpRequest();
         xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/'+myspreadsheetId+'/'+"values/"+"Sheet1!"+A+":"+C+"?"+'valueInputOption=USER_ENTERED');
         xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);

        xhr.send(JSON.stringify(params));
      }

More samples are found in Basic Writing.


问:
How can I get the data fields from subclass not superclass?
I have a super class named TestSuper

```<code>public class TestSuper {
  int a = 0;
}
</code>```

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

```<code>public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}
</code>```

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

```<code>public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}
</code>```

but the output is "0 0" instead of "1 2", what do I do?

答:
First understand the difference between hiding and overriding: https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Then create a getter method in the base-class which you can override in the subclass.

Body:
I have a super class named TestSuper

public class TestSuper {
  int a = 0;
}

and I have 2 sub classes named TestSub and TestSub2 that extend TestSuper

public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}

in my main class i created a method that takes in a type TestSuper and returns the a value of it and in the main i display it on the console

public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}

but the output is "0 0" instead of "1 2", what do I do?


答:
IE doesn't have String.trim(), you'll need $.trim() (which uses native trim if available, emulates it in IE), like this:

```<code>var item = $.trim($("#item_"+ itemArray[itemIndex]).find('a').text());
</code>```

Title: Why does Internet Explorer not like this jQuery?

Body:
IE doesn't have String.trim(), you'll need $.trim() (which uses native trim if available, emulates it in IE), like this:

var item = $.trim($("#item_"+ itemArray[itemIndex]).find('a').text());


问:
filtering numbers from Python list
I am proceeding NLP to a certain data from websites. Here I have a crawled data set which is a tokenized list. I want to handle only words rather than other numbers from this list. So I've already search other similar questions and already tried those answered written but it doesn't work in my case. The picture below is the screenshot of iPython notebook that you can see some numbers on the list.

enter image description here

I have tried those below.

```<code>#(1)
no_integers = [x for x in tokens if not (x.isdigit() or x[0] == '-' and x[1:].isdigit())]

#(2)
is_integer = lambda s: s.isdigit() or (x[0] == '-' and x[1:].isdigit())
no_integers = filter(is_integer, tokens)

#(3)
def int_filter( tokens ):
for v in tokens:
    try:
        int(v)
        continue # Skip these
    except ValueError:
        yield v # Keep these

list( int_filter( tokens ))
</code>```

I don't get what is the problem. There is not compile error. To figure out if works, I tried to compare the 'len(tokens)' of before and after. But, nothing changes.

答:
You can remove all words that are integers/numbers/floats this way:

```<code>tokens = "I like 55 donuts with glaze".split()
no_integers = [token for token in tokens if not token.isdigit()]
print(no_integers)
</code>```

If you wish to remove negatives and decimals:

```<code>tokens = "I like 55 95.5 donuts with glaze".split()
no_integers = [token for token in tokens if not all(char.isdigit() or char == '.' or char == '-' for char in token)]
print(no_integers)
token ="55"
print (all(char.isdigit() for char in token))
</code>```

Title: filtering numbers from Python list

Body:
I am proceeding NLP to a certain data from websites. Here I have a crawled data set which is a tokenized list. I want to handle only words rather than other numbers from this list. So I've already search other similar questions and already tried those answered written but it doesn't work in my case. The picture below is the screenshot of iPython notebook that you can see some numbers on the list.

enter image description here

I have tried those below.

#(1)
no_integers = [x for x in tokens if not (x.isdigit() or x[0] == '-' and x[1:].isdigit())]

#(2)
is_integer = lambda s: s.isdigit() or (x[0] == '-' and x[1:].isdigit())
no_integers = filter(is_integer, tokens)

#(3)
def int_filter( tokens ):
for v in tokens:
    try:
        int(v)
        continue # Skip these
    except ValueError:
        yield v # Keep these

list( int_filter( tokens ))

I don't get what is the problem. There is not compile error. To figure out if works, I tried to compare the 'len(tokens)' of before and after. But, nothing changes.

Body:
You can remove all words that are integers/numbers/floats this way:

tokens = "I like 55 donuts with glaze".split()
no_integers = [token for token in tokens if not token.isdigit()]
print(no_integers)

If you wish to remove negatives and decimals:

tokens = "I like 55 95.5 donuts with glaze".split()
no_integers = [token for token in tokens if not all(char.isdigit() or char == '.' or char == '-' for char in token)]
print(no_integers)
token ="55"
print (all(char.isdigit() for char in token))


问:
adding a before event to either an IDictionary or class
Is it possible to create an event before an item is added or updated to an IDictionary?

```<code>public static IDictionary<string, Aircraft> aircraftList = new Dictionary<string, Aircraft>();
</code>```

and I use it like this

```<code>MainForm.aircraftList[acNumber].FlightStatus = strFlying;
</code>```

What I want to do is not to update the value if the new value is null, empty string or an int == 0

Aircraft is a class with lots of values which are a mix of strings int's and doubles...

or is there a way of doing this type of action within the class?

currently I'm doing this everywhere I assign a value via an if statement, I assume there is a better way?

答:
You could roll out your own Dictionary class and use custom Add() function (and other functions). Something like this:

```<code>class MyCustomDictionary : Dictionary<string, Aircraft>
{
  public new Add(string key, Aircraft value)
  {
    if (YOUR_CONDITION)
    {
      base.Add(key, value);
    }
  }
}
</code>```

You should note the use of new keyword here. The Add() function cannot be overridden because the base class doesn't define it as overridable. So you must use new in your definition.

Body:
Is it possible to create an event before an item is added or updated to an IDictionary?

public static IDictionary<string, Aircraft> aircraftList = new Dictionary<string, Aircraft>();

and I use it like this

MainForm.aircraftList[acNumber].FlightStatus = strFlying;

What I want to do is not to update the value if the new value is null, empty string or an int == 0

Aircraft is a class with lots of values which are a mix of strings int's and doubles...

or is there a way of doing this type of action within the class?

currently I'm doing this everywhere I assign a value via an if statement, I assume there is a better way?

Body:
You could roll out your own Dictionary class and use custom Add() function (and other functions). Something like this:

class MyCustomDictionary : Dictionary<string, Aircraft>
{
  public new Add(string key, Aircraft value)
  {
    if (YOUR_CONDITION)
    {
      base.Add(key, value);
    }
  }
}

You should note the use of new keyword here. The Add() function cannot be overridden because the base class doesn't define it as overridable. So you must use new in your definition.


问:
Finding the averege in a loop counting to 100
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

```<code>for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}
</code>```

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?

答:
```<code>$i=0;
$tempx=0;
for ($x = 3; $x < 100; $x+=3) {
    //total sum
    $tempx = $tempx + $x;
    //count of how many times the loop ran in this case 33 times
    $i++;

     }

//first $i was 0 so we add 1
$i=$i + 1;
//getting the average
$average=$tempx / $i;
echo $average;
//output
</code>```

Body:
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?


问:
JavaScript best practice, Using closures
Hey I read at Google article (here) that we need to be careful when using closures.

For example, they gave there this function:

```<code>function foo(element, a, b) {
    element.onclick = function() { /* uses a and b */ };
}
</code>```

And I quote:

the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection.

And I also read an article on the module pattern , and there is a lot of use in closures

for example if I declare a module like that:

```<code>(function () {
    var a = function () { };
    var b = function () { };
}());
</code>```

So b have access to a , meaning its also save reference to all functions declared on the module.

Is it considered bad practice too?

答:
Yes, we need to be careful with any advanced feature, but the short answer is that they have a useful role to play.

The purpose of closure is to retain variables for later. If you never use those variables, then obviously you’re hanging on to data unnecessarily.

JavaScript garbage collection is pretty good, and it’s getting better. But it still has to try to work out when you’ve truly finished with a variable, and it’s not psychic.

On the other hand the most important part of using closures is they allow you to define variables of limited scope, so you can reduce your reliance on global variables, which are definitely far more problematic than a few extra closure variables.

The real problem with closure variables is not the extra memory they consume, but misunderstanding when they apply. For example, many new JavaScript developers when they find a loop variable has been retained when after the value has been assigned.

Many JavaScript developers bloat their code with truck loads of libraries which create huge and complex objects to perform simple tasks. That will be a much greater cost to consider.

The short answer is that, used judiciously, closures are valuable, and often the best way to perform a task.

Body:
Hey I read at Google article (here) that we need to be careful when using closures.

For example, they gave there this function:

function foo(element, a, b) {
    element.onclick = function() { /* uses a and b */ };
}

And I quote:

the function closure keeps a reference to element, a, and b even if it never uses element. Since element also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection.

And I also read an article on the module pattern , and there is a lot of use in closures

for example if I declare a module like that:

(function () {
    var a = function () { };
    var b = function () { };
}());

So b have access to a , meaning its also save reference to all functions declared on the module.

Is it considered bad practice too?


问:
Android Studio 1.4 Rendering Problems In New Drawer Template
I have just updated to Android Studio 1.4. I have created a new project with the target SDK set to Marshmellow. When I create a new Navigation Drawer Activity, I can run the activity on a virtual device just fine. However none of the XML layouts display in the preview pane.

Here are the errors:
activity_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   The following classes could not be instantiated:
  - android.support.design.widget.NavigationView (Open Class, Show Exception, Clear Cache)
   Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  Exception Details android.content.res.Resources$NotFoundException: Could not find bool resource matching value 0x7F090006 (resolved name: abc_config_showMenuShortcutsWhenKeyboardPresent) in current configuration.   at android.content.res.BridgeResources.throwException(BridgeResources.java:841)   at android.content.res.BridgeResources.getBoolean(BridgeResources.java:610)   at android.support.v7.internal.view.menu.MenuBuilder.setShortcutsVisibleInner(MenuBuilder.java:790)   at android.support.v7.internal.view.menu.MenuBuilder.(MenuBuilder.java:227)   at android.support.design.internal.NavigationMenu.(NavigationMenu.java:34)   at android.support.design.widget.NavigationView.(NavigationView.java:99)   at android.support.design.widget.NavigationView.(NavigationView.java:92)   at java.lang.reflect.Constructor.newInstance(Constructor.java:422)   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)   at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:835)   at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)   at android.view.LayoutInflater.rInflate(LayoutInflater.java:811)   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)   at android.view.LayoutInflater.inflate(LayoutInflater.java:394) Copy stack to clipboard  Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

app_bar_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

content_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

nav_header_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  Couldn't resolve resource @style/ThemeOverlay.AppCompat.Dark (3 similar errors not shown) Failed to find style 'textViewStyle' in current theme (2 similar errors not shown)

Since its mentioning missing styles, here's my styles.xml:

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

I'm new to Android development and when the default templates are throwing errors at you like this, it isn't the best way to be introduced to a new framework :(

Even an explanation as to what is going wrong would help. Thanks.

答: Your activity class must extend AppCompatActivity

Body:
I have just updated to Android Studio 1.4. I have created a new project with the target SDK set to Marshmellow. When I create a new Navigation Drawer Activity, I can run the activity on a virtual device just fine. However none of the XML layouts display in the preview pane.

Here are the errors:
activity_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   The following classes could not be instantiated:
  - android.support.design.widget.NavigationView (Open Class, Show Exception, Clear Cache)
   Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  Exception Details android.content.res.Resources$NotFoundException: Could not find bool resource matching value 0x7F090006 (resolved name: abc_config_showMenuShortcutsWhenKeyboardPresent) in current configuration.   at android.content.res.BridgeResources.throwException(BridgeResources.java:841)   at android.content.res.BridgeResources.getBoolean(BridgeResources.java:610)   at android.support.v7.internal.view.menu.MenuBuilder.setShortcutsVisibleInner(MenuBuilder.java:790)   at android.support.v7.internal.view.menu.MenuBuilder.(MenuBuilder.java:227)   at android.support.design.internal.NavigationMenu.(NavigationMenu.java:34)   at android.support.design.widget.NavigationView.(NavigationView.java:99)   at android.support.design.widget.NavigationView.(NavigationView.java:92)   at java.lang.reflect.Constructor.newInstance(Constructor.java:422)   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)   at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:835)   at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)   at android.view.LayoutInflater.rInflate(LayoutInflater.java:811)   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)   at android.view.LayoutInflater.inflate(LayoutInflater.java:394) Copy stack to clipboard  Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

app_bar_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

content_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  NOTE: One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes   Failed to find style 'toolbarStyle' in current theme (8 similar errors not shown)

nav_header_main.xml:

Rendering Problems Missing styles. Is the correct theme chosen for this layout?  Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.  Couldn't resolve resource @style/ThemeOverlay.AppCompat.Dark (3 similar errors not shown) Failed to find style 'textViewStyle' in current theme (2 similar errors not shown)

Since its mentioning missing styles, here's my styles.xml:

<resources>


问:
[Update]:Save settings of Android studio
I am new to Android Studio IDE i want to share my project in SVN.Everything was fine i ignored files and then committed by project.Then i try to check out the project and open in Android Studio IDE but the problem i lost the settings in android studio i knew i ignore some files that contains this settings.Can anyone help me on the file that need to commit so that i can restore the settings.The following settings are missing.

答:
dont ignore .gradle!

project settings usually reside in .iml (IDEA markup language I believe), those are settings for the IDE.
More broad and user based settings live und .idea/, usually you dont want have them in your source repository.


问:
Android Marshmallow and Above Device - how to know “Never ask again” is checked by the user
I want to request for the permission android.permission.READ_EXTERNAL_STORAGE for getting Media data.

But before requesting for that permission, i want to know whether it is blocked by the user by checking "Never ask again" check box.

Is there a proper way to know "Never ask again" for a permission?

So if I can understand whether "Never show again" is clicked or not.

答: Look like similar question has been asked before you can get your answer here How Do We Distinguish Never-Asked From Stop-Asking in Android M's Runtime Permissions?</p>


问:
Access Label control inside the detailsview control
I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object."
can anyone guide me please.. ??
My front end code is:

```<code><asp:Panel ID="sub_question_panel" runat="server">
   <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6"    ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
   <Fields>
      <asp:TemplateField>
         <ItemTemplate>
               <table id="Question_view_table">
                  <tr>
<td style="font-family:Arial Rounded MT;">
<label id="Question_no"><span style="font-size:20px;">Question</span>:</label>
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label></td>
</tr>
<tr>
<td style="height:20px"></td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px; ">
<label id="Question_detail"><%# Eval ("Question") %></label>
</td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px;">
<ol style="list-style:upper-alpha">
<li>
<label id="optn1"> &nbsp&nbsp<%# Eval ("Option1") %></label></li>
<li>
<label id="optn2"> &nbsp&nbsp<%# Eval ("Option2") %></label></li>
<li>
<label id="optn3"> &nbsp&nbsp<%# Eval ("Option3") %></label></li>
<li>
<label id="optn4"> &nbsp&nbsp<%# Eval ("Option4") %></label></li>
</ol>
</td>
</tr>
            </table>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>
</code>```

My back end code is:

```<code>protected void Page_Load(object sender, EventArgs e)
{
      int question_id = 1;
      Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
      Question_Id .Text = Convert.ToString(question_id);
}
</code>```

答:
You use FindControl to find Ques_id_label, but then reference it normally anyway: Ques_id_label.Text =

It should be Question_Id.Text = Convert.ToString(question_id);, with the ID you assigned with FindControl.

But did it even compile? Do you use an editor like Visual Studio? Because when I tried your snippet it gave the error The name 'Ques_id_label' does not exist in the current context, as it is supposed to.

Body:
I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object."
can anyone guide me please.. ??
My front end code is:

<asp:Panel ID="sub_question_panel" runat="server">
   <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6"    ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
   <Fields>
      <asp:TemplateField>
         <ItemTemplate>

Question:
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label>

<%# Eval ("Question") %>

 &nbsp&nbsp<%# Eval ("Option1") %>

 &nbsp&nbsp<%# Eval ("Option2") %>

 &nbsp&nbsp<%# Eval ("Option3") %>

 &nbsp&nbsp<%# Eval ("Option4") %>

</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>

My back end code is:

protected void Page_Load(object sender, EventArgs e)
{
      int question_id = 1;
      Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
      Question_Id .Text = Convert.ToString(question_id);
}