问:
UWP: Cannot make ListView scrollable
I have a page with a simple grid (2x2). In one grid on the bottom left corner is another Grid and inside this grid is a ListView bound to a collection. Entries can be added to the collection so the ListView grows in height (height of ListView is set to auto, so that all space available is used).

What I want is, if all available space (from the screen height) is used, scrollbars for the ListView should appear and should be usable. Funny (unfunny) thing is: scrollbars do appear but I cannot use them, I cannot scroll the ListView with the vertical scrollbar that appears when I hover the ListView.

It works, when I set the height of the ListView to a fixed value, but I don't want it that way, because then it doesn't use all the available space on the screen.

This is the XAML of the page (I removed some parts for demonstration purposes) :

```<code><Page
    x:Class="Qooli.TimeTracker.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Qooli.TimeTracker"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        ...
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <StackPanel Name="spAddEntry" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Text="Add new entry:" Name="lblAddNewEntry" />
            ...
        </StackPanel>

        <StackPanel Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Text="Allocated time:" Name="lblAllocatedTime" />
            ...
        </StackPanel>

        <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Margin="30">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Daily overview:" Name="lblDailyOverview" Grid.Row="0" Grid.Column="0" />
            <ListView Name="lvTimeEntries"  Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left"
                      Height="Auto"
                      MinHeight="100"
                      VerticalAlignment="Top"
                      MinWidth="300"
                      SelectionMode="Single"
                      ItemsSource="{x:Bind ViewModel.TimeEntriesAdvancedCollectionView, Mode=OneWay}"
                      ScrollViewer.VerticalScrollBarVisibility="Visible"
                      ScrollViewer.IsVerticalRailEnabled="True"
                      ScrollViewer.VerticalScrollMode="Enabled">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel></StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate x:DataType="local:TimeEntry">
                        <Grid Background="{Binding Type, Converter={StaticResource TimeEntryTypeColorConverter}}" Padding="5">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="200"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="{x:Bind Time, Mode=OneWay}" Style="{StaticResource TitleTextBlockStyle}"
                                       MinWidth="60"
                                       MaxWidth="60"
                                       Grid.Row="0" Grid.Column="0">
                            </TextBlock>
                            <TextBlock Text="{x:Bind Title, Mode=OneWay}" Style="{StaticResource BodyTextBlockStyle}" Margin="5,0,0,0"
                                       MinWidth="100"
                                       MaxWidth="100"
                                       Grid.Row="0" Grid.Column="1">
                            </TextBlock>
                            <Button Name="btnEditTimeEntry" Grid.Row="0" Grid.Column="2" Margin="5,5,5,5">
                                <SymbolIcon x:Name="edit" Symbol="Edit"/>
                            </Button>
                            <Button Name="btnDeleteTimeEntry" Grid.Row="0" Grid.Column="3" Margin="5,5,5,5">
                                <SymbolIcon x:Name="delete" Symbol="Delete"/>
                            </Button>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ListView>
        </Grid>

        <StackPanel Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Style="{StaticResource summaryTextStyle}" Text="Start time:" Name="lblDayStartTime" />
            ...
        </StackPanel>

    </Grid>
</Page>
</code>```

Can someone spot why it is behaving this way?

答: You need to set the height of the second row to "*" for both grids.

Title: UWP: Cannot make ListView scrollable

Body:
I have a page with a simple grid (2x2). In one grid on the bottom left corner is another Grid and inside this grid is a ListView bound to a collection. Entries can be added to the collection so the ListView grows in height (height of ListView is set to auto, so that all space available is used).

What I want is, if all available space (from the screen height) is used, scrollbars for the ListView should appear and should be usable. Funny (unfunny) thing is: scrollbars do appear but I cannot use them, I cannot scroll the ListView with the vertical scrollbar that appears when I hover the ListView.

It works, when I set the height of the ListView to a fixed value, but I don't want it that way, because then it doesn't use all the available space on the screen.

This is the XAML of the page (I removed some parts for demonstration purposes) :

<Page
    x:Class="Qooli.TimeTracker.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Qooli.TimeTracker"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        ...
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <StackPanel Name="spAddEntry" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Text="Add new entry:" Name="lblAddNewEntry" />
            ...
        </StackPanel>

        <StackPanel Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Text="Allocated time:" Name="lblAllocatedTime" />
            ...
        </StackPanel>

        <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Margin="30">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Daily overview:" Name="lblDailyOverview" Grid.Row="0" Grid.Column="0" />
            <ListView Name="lvTimeEntries"  Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left"
                      Height="Auto"
                      MinHeight="100"
                      VerticalAlignment="Top"
                      MinWidth="300"
                      SelectionMode="Single"
                      ItemsSource="{x:Bind ViewModel.TimeEntriesAdvancedCollectionView, Mode=OneWay}"
                      ScrollViewer.VerticalScrollBarVisibility="Visible"
                      ScrollViewer.IsVerticalRailEnabled="True"
                      ScrollViewer.VerticalScrollMode="Enabled">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel></StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate x:DataType="local:TimeEntry">
                        <Grid Background="{Binding Type, Converter={StaticResource TimeEntryTypeColorConverter}}" Padding="5">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="200"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="{x:Bind Time, Mode=OneWay}" Style="{StaticResource TitleTextBlockStyle}"
                                       MinWidth="60"
                                       MaxWidth="60"
                                       Grid.Row="0" Grid.Column="0">
                            </TextBlock>
                            <TextBlock Text="{x:Bind Title, Mode=OneWay}" Style="{StaticResource BodyTextBlockStyle}" Margin="5,0,0,0"
                                       MinWidth="100"
                                       MaxWidth="100"
                                       Grid.Row="0" Grid.Column="1">
                            </TextBlock>
                            <Button Name="btnEditTimeEntry" Grid.Row="0" Grid.Column="2" Margin="5,5,5,5">
                                <SymbolIcon x:Name="edit" Symbol="Edit"/>
                            </Button>
                            <Button Name="btnDeleteTimeEntry" Grid.Row="0" Grid.Column="3" Margin="5,5,5,5">
                                <SymbolIcon x:Name="delete" Symbol="Delete"/>
                            </Button>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ListView>
        </Grid>

        <StackPanel Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30">
            <TextBlock Style="{StaticResource summaryTextStyle}" Text="Start time:" Name="lblDayStartTime" />
            ...
        </StackPanel>

    </Grid>
</Page>

Can someone spot why it is behaving this way?


来源: stackexchange

问:
why doesn't my string support the item Assignment
the idea here is to  be able to take a user input witch is Main and shuffle its value and re-enter it into the Second Entry, error message :    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

```<code>from tkinter import *
import random

def randomize(a):
    Second.delete(0 , 'end')
    b = Main.get()
    c = random.shuffle(b)
    Second.insert(0 , c)

root = Tk()

Main = Entry(root)
Main.grid(row = 1,column = 0 , sticky = 'we')

Second = Entry(root)
Second.grid(row = 2 , column = 0 , sticky = 'we')

randombutton = Button(root , text = 'Randomize')
randombutton.grid(row = 3 , column = 0 , sticky = 'we')
randombutton.bind('<Button-1>' , randomize)
</code>```

答:
The problem is that you are trying to call random.shuffle on a string, which is not possible (also, you are trying to assign the output of this to c, which will just return None). Instead you may want to convert it to a list, and then back into a string to output it within Second.

See the following code:

```<code>def randomize(a):
    Second.delete(0 , 'end')
    b = Main.get()
    c = list(b)
    random.shuffle(c) # Converted to a list, so it can be shuffled, see note for extra info
    Second.insert(0 , ''.join(c)) # Converted back into a string so it can be displayed
</code>```

Note: random.shuffle does not return any values, it simply shuffles (and therefore changes) the variable which you put into it. For example, in the code c = random.shuffle(b), b would NOW equal some random shuffling of whatever was in the entry box, whereas c would now equal None, as random.shuffle returns nothing.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
the idea here is to  be able to take a user input witch is Main and shuffle its value and re-enter it into the Second Entry, error message :    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

from tkinter import *
import random

def randomize(a):
    Second.delete(0 , 'end')
    b = Main.get()
    c = random.shuffle(b)
    Second.insert(0 , c)

root = Tk()

Main = Entry(root)
Main.grid(row = 1,column = 0 , sticky = 'we')

Second = Entry(root)
Second.grid(row = 2 , column = 0 , sticky = 'we')

randombutton = Button(root , text = 'Randomize')
randombutton.grid(row = 3 , column = 0 , sticky = 'we')
randombutton.bind('<Button-1>' , randomize)

Body:
The problem is that you are trying to call random.shuffle on a string, which is not possible (also, you are trying to assign the output of this to c, which will just return None). Instead you may want to convert it to a list, and then back into a string to output it within Second.

See the following code:

def randomize(a):
    Second.delete(0 , 'end')
    b = Main.get()
    c = list(b)
    random.shuffle(c) # Converted to a list, so it can be shuffled, see note for extra info
    Second.insert(0 , ''.join(c)) # Converted back into a string so it can be displayed

Note: random.shuffle does not return any values, it simply shuffles (and therefore changes) the variable which you put into it. For example, in the code c = random.shuffle(b), b would NOW equal some random shuffling of whatever was in the entry box, whereas c would now equal None, as random.shuffle returns nothing.

Hope this helps!


问:
Kotlin type missmatch. Expected Any received MyObject
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

```<code>abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}
</code>```

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.

答:
Haven't tried it, but I think this would work

fun <T:Any> addResource(source: LiveData<Resource<T>>)

Body:
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.


答:
I Create 25 events is different time.  After a while, the database takes all the resources, and reboots.

```<code>   CREATE EVENT `auction_event_46709`
   ON SCHEDULE EVERY 5 MINUTE STARTS '2017-12-07 10:23:03'
   ON COMPLETION NOT PRESERVE ENABLE
   DO CALL auction_update_price(46709)
</code>```

Procedure:

```<code>CREATE PROCEDURE `auction_update_price`( IN p_id INT )
BEGIN
 DECLARE cur_price INT;
 DECLARE stp_price INT;
 DECLARE st_price INT;
 DECLARE str_price INT;
 SELECT current_price, step_price, stop_price, start_price INTO cur_price, stp_price, st_price, str_price FROM product_to_auction WHERE product_id = p_id;
 IF( cur_price - stp_price > st_price ) THEN
   UPDATE product_to_auction SET current_price = current_price - step_price WHERE current_price > stop_price AND product_id = p_id;
 ELSE
    UPDATE product_to_auction SET current_price = str_price WHERE product_id = p_id;
 END IF;
END
</code>```

How to Fix?

Title: mysql - Is it a good practice to have a lot of events?

Body:
I have a table tblMatch :

+---------+---------------------+------------------+-----------+
|  ID     |      start_date     |     end_date     |  status   |
+---------+---------------------+------------------+-----------+
|  1      |   2017-12-09 03:23  | 2017-12-10 03:23 |      1    |
+---------+---------------------+------------------+-----------+
| ...     |         ...         |       ...        |      1    |
+---------+---------------------+------------------+-----------+
| 1000000 |   2017-12-22 15:12  | 2017-12-30 15:12 |      1    |
+---------+---------------------+------------------+-----------+

When I insert a row, I create one event too.
Event will change status to 0 if the match is ended.

CREATE EVENT test_event_increment_number
ON SCHEDULE AT end_date
ON COMPLETION NOT PRESERVE
DO
   UPDATE tblMatch SET status = 0 WHERE ID = increment_number;

If tblMatch has 100 million matches :
Does it effect server performance?
Is it bad or good idea to create a lot of events?

Body:
I Create 25 events is different time.  After a while, the database takes all the resources, and reboots.

   CREATE EVENT `auction_event_46709`
   ON SCHEDULE EVERY 5 MINUTE STARTS '2017-12-07 10:23:03'
   ON COMPLETION NOT PRESERVE ENABLE
   DO CALL auction_update_price(46709)

Procedure:

CREATE PROCEDURE `auction_update_price`( IN p_id INT )
BEGIN
 DECLARE cur_price INT;
 DECLARE stp_price INT;
 DECLARE st_price INT;
 DECLARE str_price INT;
 SELECT current_price, step_price, stop_price, start_price INTO cur_price, stp_price, st_price, str_price FROM product_to_auction WHERE product_id = p_id;
 IF( cur_price - stp_price > st_price ) THEN
   UPDATE product_to_auction SET current_price = current_price - step_price WHERE current_price > stop_price AND product_id = p_id;
 ELSE
    UPDATE product_to_auction SET current_price = str_price WHERE product_id = p_id;
 END IF;
END

How to Fix?


问:
How can i remove a class from a div and add a new class with jQuery to that div when a specific div doesnt exist in the page?
As the title describes what I m trying to do is to remove the class half-width and add the new class full-width to a div with id="planetdata1" when the div with id="a12" doesn't exist anymore in the page.

In this example, there's the div with id="a12"

```<code> <div id ="a12">Hey! i am the div that i hide my self sometimes</div>
 <div id="planetdata1" class="half-width"></div>
</code>```

But when the div with id="a12" is not displayed at the page then i want the div with the id="dataplanet1" to become like that:

```<code> <div id="planetdata1" class="full-width"></div>
</code>```

How can I do that with jQuery? I tried to find an answer before I post my question but didn't find anything similar.

答:
To check if the element is on the page or not, you can do something like this:

```<code>$("#a12").length
</code>```

The above will return 0 if the div is not in the page, and 1 if it is. Plus, to remove/add a class from/to the element, you can do the following:

```<code>$("#planetdata1").removeClass("half-width").addClass("full-width");
</code>```

Body:
As the title describes what I m trying to do is to remove the class half-width and add the new class full-width to a div with id="planetdata1" when the div with id="a12" doesn't exist anymore in the page.

In this example, there's the div with id="a12"

Hey! i am the div that i hide my self sometimes

But when the div with id="a12" is not displayed at the page then i want the div with the id="dataplanet1" to become like that:

How can I do that with jQuery? I tried to find an answer before I post my question but didn't find anything similar.

Body:
To check if the element is on the page or not, you can do something like this:

$("#a12").length

The above will return 0 if the div is not in the page, and 1 if it is. Plus, to remove/add a class from/to the element, you can do the following:

$("#planetdata1").removeClass("half-width").addClass("full-width");


问:
Laravel Eloquent belongsto relationship returns null
I have two Eloquent models:

1) Post

```<code>class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function product(){
        return $this->belongsTo(Product::class);
    }
</code>```

2) Product

```<code>protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
                        'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];

public function posts(){
    return $this->hasMany(Post::class);
}
</code>```

I need to get the product from a post
I do that:

```<code>$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}
</code>```

Like this it returns NULL
If I do like this:
 dd($key->product());
I get the product but I can't to use that

but I need to get something like that to use whant I need:

答:
Try to point out foregin key and other key in relation, examples:

```<code>public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}
</code>```

More: https://laravel.com/docs/5.5/eloquent-relationships

Body:
I have two Eloquent models:

1) Post

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function product(){
        return $this->belongsTo(Product::class);
    }

2) Product

protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
                        'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];

public function posts(){
    return $this->hasMany(Post::class);
}

I need to get the product from a post
I do that:

$posts = Post::get();

foreach($posts as $key){
    dd($key->product);
}

Like this it returns NULL
If I do like this:
 dd($key->product());
I get the product but I can't to use that

but I need to get something like that to use whant I need:

Body:
Try to point out foregin key and other key in relation, examples:

public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}

More: https://laravel.com/docs/5.5/eloquent-relationships


问:
How do I get simultaneous key repeats with SDL?
How do you detect simultaneous key repeats with SDL? Right now I can detect keys pressed at the same time (but not if they are all held down) or a single key held down. I want to be able to detect all the keys that are held down at any one time.

My code

SDL_EnableKeyRepeat (100, 200);

while (SDL_PollEvent (&event)) {

if (event.type == SDL_KEYDOWN) {

```<code>  if (event.key.keysym.sym == SDLK_t) {

  } else if (event.key.keysym.sym == SDL_y) {

  }
</code>```

} else if (blah) {

```<code>   //blah blah blah
</code>```

}

}

答: First detecting all keys that are held down might prove impossible. Due to keyboard limitations, most keyboards support 4-6 buttons pressed at the same time, after that key presses/releases wont register. Second i wouldn't suggest using key repeat. Dunno maybe other peoples experience differs, but you can get better accuracy by storing states of keys that interest you. I.e. in simple game that would be directional keys. And you just set moving left when left is pressed, and unset it when left is released or maybe when right is pressed. If you need it for something like typing you could probably make it using some array pressed_keys and put key ids there of keys that are pressed. (Im assuming your trying to make something game like).</p>

ContentLicense: CC BY-SA 2.5

Body:
How do you detect simultaneous key repeats with SDL? Right now I can detect keys pressed at the same time (but not if they are all held down) or a single key held down. I want to be able to detect all the keys that are held down at any one time.

My code

SDL_EnableKeyRepeat (100, 200);

while (SDL_PollEvent (&event)) {

if (event.type == SDL_KEYDOWN) {

  if (event.key.keysym.sym == SDLK_t) {

  } else if (event.key.keysym.sym == SDL_y) {

  }

} else if (blah) {

   //blah blah blah

}

}


答:
if you want to do this when the page load, try this </p>

```<code>$(function(){
   if($('#a12').length == 0){
      $('#planetdata1').removeClass('half-width');
      $('#planetdata1').addClass('full-width');
   }//end if
});
</code>```

Title: How can i remove a class from a div and add a new class with jQuery to that div when a specific div doesnt exist in the page?

Body:
if you want to do this when the page load, try this

$(function(){
   if($('#a12').length == 0){
      $('#planetdata1').removeClass('half-width');
      $('#planetdata1').addClass('full-width');
   }//end if
});


问:
Why the error "Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag" happens only on some devices?
I'm getting a crash report on Firebase with the message

Calling startActivity() from outside of an Activity context requires
  the FLAG_ACTIVITY_NEW_TASK flag.

This error occurs on a Samsung GT-I9500 with Android 19. I can't reproduce the error o my Google Pixel with Android Oreo (27).

I know how to set the flag, but I'm curious to know why this error occurs only on some versions of Android.

Here's how I'm starting the Activity:

```<code>    context.getApplicationContext().startActivity(intent);
</code>```

答:
I'm curious to know why this error occurs only on some versions of Android.

Because of a bug. See this issue and this issue.

Body:
I'm getting a crash report on Firebase with the message

Calling startActivity() from outside of an Activity context requires
  the FLAG_ACTIVITY_NEW_TASK flag.

This error occurs on a Samsung GT-I9500 with Android 19. I can't reproduce the error o my Google Pixel with Android Oreo (27).

I know how to set the flag, but I'm curious to know why this error occurs only on some versions of Android.

Here's how I'm starting the Activity:

    context.getApplicationContext().startActivity(intent);


问:
Constant to String in AppleScript
I have the following line of code:

```<code>tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind
    end if
end tell
</code>```

When I print trackMediaKind I get the following: «constant ****kMdS»

In iTunes the media kind looks like:

Is there way to make it print Music instead of «constant ****kMdS»?

-Edit-

```<code>tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        log trackMediaKind as string
    end if
end tell
</code>```

I ran the code up via the terminal by typing: osascript myscript.scpt it stills returns: «constant ****kMdS».

答:
You need to change the following line of code from:

```<code>display dialog trackMediaKind
</code>```

To:

```<code>display dialog trackMediaKind as string
</code>```

If you really want it to display "Music" then you need to do something such as:

```<code>tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        if trackMediaKind as string is "song" then
            display dialog "Music"
        end if
    end if
end tell
</code>```

BTW In the AppleScript Dictionary for iTunes (12.7.*) , looking at the properties of a track, the media kind shows:

media kind (alert tone/audiobook/book/home video/iTunesU/movie/song/music video/podcast/ringtone/TV show/voice memo/unknown) : the media kind of the track

In other words, you'll need to test the results against what could be returned and process it accordingly to your needs/wants if you want to display differently the returned. Also, anytime it returns things like e.g. «constant ****kMdS» try coercing to text with as string or as text.

Update to address the after the fact edit to your question:

While you didn't originally state in the OP you were running your script in Terminal using osascript, nonetheless there seems to be an issue between running the same code as a .scpt file in the two different environments. One would think that what works correctly in Script Editor, it would work correctly in Terminal using osascript, but in this particular case it doesn't.

The workaround in this particular case is to not use the .scpt file format and instead use a plain text format:

As an example, the following code should display a dialog box with "song" when a song track is playing iTunes and saved in Script Editor as Text, e.g. myscript.applescript, and then run in Terminal using: osascript myscript.applescript

```<code>tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind as string
    end if
end tell
</code>```

One can also use the AppleScript code in plain text format and make the file executable to be used directly without having to first type osascript on the command line. Save the following example AppleScript code using an osascript shebang.

```<code>#!/usr/bin/osascript

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind as string
    end if
end tell
</code>```

Make executable with chmod in Terminal, e.g.:

```<code>chmod u+x myscript.applescript
</code>```

Then, if it's in the current directory, execute the script using:

```<code>./myscript.applescript
</code>```

Otherwise, use the pathname to it, if it's not in the PATH.

Note: With this method, it is not necessary to use the .applescript extension or any extension. It's a users preference, even though Script Editor uses that extension by default for plain text AppleScript code files.

Title: Constant to String in AppleScript

Body:
I have the following line of code:

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind
    end if
end tell

When I print trackMediaKind I get the following: «constant ****kMdS»

In iTunes the media kind looks like:

Is there way to make it print Music instead of «constant ****kMdS»?

-Edit-

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        log trackMediaKind as string
    end if
end tell

I ran the code up via the terminal by typing: osascript myscript.scpt it stills returns: «constant ****kMdS».

Body:
You need to change the following line of code from:

display dialog trackMediaKind

To:

display dialog trackMediaKind as string

If you really want it to display "Music" then you need to do something such as:

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        if trackMediaKind as string is "song" then
            display dialog "Music"
        end if
    end if
end tell

BTW In the AppleScript Dictionary for iTunes (12.7.*) , looking at the properties of a track, the media kind shows:

media kind (alert tone/audiobook/book/home video/iTunesU/movie/song/music video/podcast/ringtone/TV show/voice memo/unknown) : the media kind of the track

In other words, you'll need to test the results against what could be returned and process it accordingly to your needs/wants if you want to display differently the returned. Also, anytime it returns things like e.g. «constant ****kMdS» try coercing to text with as string or as text.

Update to address the after the fact edit to your question:

While you didn't originally state in the OP you were running your script in Terminal using osascript, nonetheless there seems to be an issue between running the same code as a .scpt file in the two different environments. One would think that what works correctly in Script Editor, it would work correctly in Terminal using osascript, but in this particular case it doesn't.

The workaround in this particular case is to not use the .scpt file format and instead use a plain text format:

As an example, the following code should display a dialog box with "song" when a song track is playing iTunes and saved in Script Editor as Text, e.g. myscript.applescript, and then run in Terminal using: osascript myscript.applescript

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind as string
    end if
end tell

One can also use the AppleScript code in plain text format and make the file executable to be used directly without having to first type osascript on the command line. Save the following example AppleScript code using an osascript shebang.

#!/usr/bin/osascript

tell application "iTunes"
    if player state is playing then
        set trackMediaKind to media kind of current track
        display dialog trackMediaKind as string
    end if
end tell

Make executable with chmod in Terminal, e.g.:

chmod u+x myscript.applescript

Then, if it's in the current directory, execute the script using:

./myscript.applescript

Otherwise, use the pathname to it, if it's not in the PATH.

Note: With this method, it is not necessary to use the .applescript extension or any extension. It's a users preference, even though Script Editor uses that extension by default for plain text AppleScript code files.


问:
Reading in multiple files with Javascript results in only last file being read
I have to read in a few test text files into my JavaScript code. There are 3 files, titled 1.txt, 2.txt and 3.txt, each containing a single line. I wrote this piece of code which I thought would work just fine:

```<code>function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        console.log("Start loop")
        myFile = files.item(i);
        var myReader = new FileReader();
        myReader.readAsText(myFile);
        myReader.onload = function(e) {
            var rawLog = myReader.result;
            console.log(rawLog)
        };

    }
};

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</code>```

This results in a button on the web page that allows me to select multiple files. It is supposed to result in the following:

```<code>Start loop
Contents 1.txt
Start loop
Contents 2.txt
Start loop
Contents 3.txt
</code>```

But what it outputs is the following:

```<code>Start loop
Start loop
Start loop
null
null
Contents 3.txt
</code>```

How can I generate the first one? I expect the error to be in the onload function, but I'm not sure what I'm doing wrong...

答:
In your code var myReader = new FileReader(); is reassigning the variable in each loop hence destroying the first instance.

I recommend you split your code to two functions to prevent the local block variable's instances from being overwritten before they are done.

```<code>function readFile(file) {
    var myReader = new FileReader();
  myReader.readAsText(file);
  myReader.onload = function(e) {
      var rawLog = myReader.result;
      console.log(rawLog)
  };
}

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        myFile = files.item(i);
        readFile(myFile);
    }
};
</code>```

Body:
I have to read in a few test text files into my JavaScript code. There are 3 files, titled 1.txt, 2.txt and 3.txt, each containing a single line. I wrote this piece of code which I thought would work just fine:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        console.log("Start loop")
        myFile = files.item(i);
        var myReader = new FileReader();
        myReader.readAsText(myFile);
        myReader.onload = function(e) {
            var rawLog = myReader.result;
            console.log(rawLog)
        };

    }
};

document.getElementById('files').addEventListener('change', handleFileSelect, false);

This results in a button on the web page that allows me to select multiple files. It is supposed to result in the following:

Start loop
Contents 1.txt
Start loop
Contents 2.txt
Start loop
Contents 3.txt

But what it outputs is the following:

Start loop
Start loop
Start loop
null
null
Contents 3.txt

How can I generate the first one? I expect the error to be in the onload function, but I'm not sure what I'm doing wrong...

Body:
In your code var myReader = new FileReader(); is reassigning the variable in each loop hence destroying the first instance.

I recommend you split your code to two functions to prevent the local block variable's instances from being overwritten before they are done.

function readFile(file) {
    var myReader = new FileReader();
  myReader.readAsText(file);
  myReader.onload = function(e) {
      var rawLog = myReader.result;
      console.log(rawLog)
  };
}

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        myFile = files.item(i);
        readFile(myFile);
    }
};


问:
server socket receives 2 http requests when I send from chrome and receives one when I send from firefox
I wrote a simple server using socket API in C under linux which listens at port 80 on localhost. Now when I send a request from the browser google chrome to the program it receives 2 requests while it receives only one when I send from firefox.

The URL I typed in the browser was: http://localhost/xyz.html

OUTPUT WHEN I TYPE URL IN CHROME

```<code>root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN

Inside HTTP server Handler

Inside HTTP request Handler

**Detected request: clientsocket_fd = 6 clientportnumber = 38027**

GET /xyz.html HTTP/1.1

Host: localhost

Connection: keep-alive

Cache-Control: max-age=0

Accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10

Accept-Encoding: gzip,deflate,sdch

Accept-Language: en-US,en;q=0.8

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Inside HTTP request Handler

**Detected request: clientsocket_fd = 7 clientportnumber = 38029**

^C

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL#
</code>```

the second request does not send any data so my code waits at the read call and so I have to terminate it '^C'.

OUTPUT WHEN I TYPE URL IN FIREFOX

```<code>root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN
Inside HTTP server Handler
Inside HTTP request Handler

**Detected request: clientsocket_fd = 6 clientportnumber = 45567**

GET /xyz.html HTTP/1.1

Host: localhost

User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-us,en;q=0.5

Accept-Encoding: gzip,deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive: 115

Connection: keep-alive

^C

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL#
</code>```

Question: How can chrome browser send 2 requests (one being empty) when I typed the URL only once. As you can see above I detected 2 requests. I tried to do netstat in the case of sending URL from chrome and I found that both of the request were sent by the browser only. and as u can see above when I send the URL from firefox only 1 request is received.

Here is the output of net stat when I send request from chrome

```<code>Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

tcp        0      0 117.195.110.186:48701   74.125.77.102:80        TIME_WAIT   -

tcp        0      0 117.195.110.186:48700   74.125.77.102:80        ESTABLISHED 5699/google-chrome

tcp        0      0 117.195.110.186:55815   209.85.175.138:80       ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:80            127.0.0.1:38029         ESTABLISHED -

tcp        0      0 127.0.0.1:38029         127.0.0.1:80            ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:38027         127.0.0.1:80            ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:80            127.0.0.1:38027         ESTABLISHED -

tcp        0      0 117.195.110.186:35402   74.125.153.125:5222     ESTABLISHED 4430/pidgin
</code>```

thanks in advance :)

答: Can you post the source of your server? My guess is that Chrome simply opens a socket against your server to optimize future requests to the same page, but does not send any command on it.</p>

Body:
I wrote a simple server using socket API in C under linux which listens at port 80 on localhost. Now when I send a request from the browser google chrome to the program it receives 2 requests while it receives only one when I send from firefox.

The URL I typed in the browser was: http://localhost/xyz.html

OUTPUT WHEN I TYPE URL IN CHROME

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN

Inside HTTP server Handler

Inside HTTP request Handler

**Detected request: clientsocket_fd = 6 clientportnumber = 38027**

GET /xyz.html HTTP/1.1

Host: localhost

Connection: keep-alive

Cache-Control: max-age=0

Accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10

Accept-Encoding: gzip,deflate,sdch

Accept-Language: en-US,en;q=0.8

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Inside HTTP request Handler

**Detected request: clientsocket_fd = 7 clientportnumber = 38029**

^C

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL#

the second request does not send any data so my code waits at the read call and so I have to terminate it '^C'.

OUTPUT WHEN I TYPE URL IN FIREFOX

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN
Inside HTTP server Handler
Inside HTTP request Handler

**Detected request: clientsocket_fd = 6 clientportnumber = 45567**

GET /xyz.html HTTP/1.1

Host: localhost

User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-us,en;q=0.5

Accept-Encoding: gzip,deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive: 115

Connection: keep-alive

^C

root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL#

Question: How can chrome browser send 2 requests (one being empty) when I typed the URL only once. As you can see above I detected 2 requests. I tried to do netstat in the case of sending URL from chrome and I found that both of the request were sent by the browser only. and as u can see above when I send the URL from firefox only 1 request is received.

Here is the output of net stat when I send request from chrome

Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

tcp        0      0 117.195.110.186:48701   74.125.77.102:80        TIME_WAIT   -

tcp        0      0 117.195.110.186:48700   74.125.77.102:80        ESTABLISHED 5699/google-chrome

tcp        0      0 117.195.110.186:55815   209.85.175.138:80       ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:80            127.0.0.1:38029         ESTABLISHED -

tcp        0      0 127.0.0.1:38029         127.0.0.1:80            ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:38027         127.0.0.1:80            ESTABLISHED 5699/google-chrome

tcp        0      0 127.0.0.1:80            127.0.0.1:38027         ESTABLISHED -

tcp        0      0 117.195.110.186:35402   74.125.153.125:5222     ESTABLISHED 4430/pidgin

thanks in advance :)


问:
how to change the text on the AppTheme?
I want to change the title that appear on my app.
This text is taken from the string.xml => the 'app_name'
Can't remove and use some other AppTheme ( using the default ) because this remove the 3 dots that i have to show the 'settings' activity.

I trying to play with all the AppTheme settings .. and nothing change this text.

答:
Try this in Your OnCreate() method of Your Activity

```<code>getSupportActionBar().setTitle("Prem");
</code>```

OR

add android:label="PREM" in your Activity tag in manifest file like below code

```<code><activity
     android:name=".YourAactivity"
     android:label="PREM" <--addhere your activity name--> />
</code>```

Title: how to change the text on the AppTheme?

Body:
Try this in Your OnCreate() method of Your Activity

getSupportActionBar().setTitle("Prem");

OR

add android:label="PREM" in your Activity tag in manifest file like below code

<activity
     android:name=".YourAactivity"
     android:label="PREM" <--addhere your activity name--> />


问:
how can i sort 2 dimensional array based on index array in PHP?
I have an array in PHP like this :

Array
(
    [0] => Array
        (
            [0] => black
            [2] => brown
            [1] => red
        )

```<code>[1] => Array
    (
        [2] => car
        [0] => bicycle
        [1] => motorcycle
    )
</code>```

)

How do I get the array, like this :

Result:

Array
(
    [0] => Array
        (
            [0] => black
            [1] => red
            [2] => brown
        )

```<code>[1] => Array
    (

        [0] => bicycle
        [1] => motorcycle
        [2] => car
    )
</code>```

)

Thanks

答:
You could try like this perhaps:

```<code>$arr=array(
    array(2=>'red',1=>'green',3=>'black'),
    array(1=>'pink',3=>'blue',2=>'yellow')
);
array_walk( $arr, function(&$v,$k){
    ksort($v);
});
echo '```', print_r( $arr, true ), '```';
</code>```

Outputs:

```<code>Array
(
    [0] => Array
        (
            [1] => green
            [2] => red
            [3] => black
        )

    [1] => Array
        (
            [1] => pink
            [2] => yellow
            [3] => blue
        )

)
</code>```

Body:
I have an array in PHP like this :

Array
(
    [0] => Array
        (
            [0] => black
            [2] => brown
            [1] => red
        )

[1] => Array
    (
        [2] => car
        [0] => bicycle
        [1] => motorcycle
    )

)

How do I get the array, like this :

Result:

Array
(
    [0] => Array
        (
            [0] => black
            [1] => red
            [2] => brown
        )

[1] => Array
    (

        [0] => bicycle
        [1] => motorcycle
        [2] => car
    )

)

Thanks

Body:
You could try like this perhaps:

$arr=array(
    array(2=>'red',1=>'green',3=>'black'),
    array(1=>'pink',3=>'blue',2=>'yellow')
);
array_walk( $arr, function(&$v,$k){
    ksort($v);
});
echo '<pre>', print_r( $arr, true ), '</pre>';

Outputs:

Array
(
    [0] => Array
        (
            [1] => green
            [2] => red
            [3] => black
        )

    [1] => Array
        (
            [1] => pink
            [2] => yellow
            [3] => blue
        )

)


问:
FireFox word breaks OK with css, but one letter at a time, not where hyphens go
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

```<code>.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}
</code>```

答:
a) Don't use word-break when you want to use hyphenation. It will simply always break the words.

b) To be on the safe side, add a language attribute to the container (can be html, body, or also the containing div, like
 - see below.

.a {
  width: 240px;
  border: 1px solid #eee;
}

.x {

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a" lang="en">
  <p class="x">
    A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy,
    my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents. I should be incapable of drawing a single stroke at the present moment; and yet I feel that I never was a greater artist than now.
  </p>
</div></code>```

Body:
FireFox word breaks OK with css, but one letter at a time, not where hyphens are supposed to be???

NOT FireFox:

FireFox:

Here's the CSS:

.superLongStuff {
    /*
        SUPER LOOOOOOOOOOOONG WORD STUFF ...
    */
    /* These are technically the same, but use both */
    overflow-wrap: break-word;
    word-wrap:     break-word;

    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break:     break-all;
    /* Instead use this non-standard one: */
    word-break:     break-word;

    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens:     auto;
    -moz-hyphens:    auto;
    -webkit-hyphens: auto;
    hyphens:         auto;
}

Body:
a) Don't use word-break when you want to use hyphenation. It will simply always break the words.

b) To be on the safe side, add a language attribute to the container (can be html, body, or also the containing div, like <div class="a" lang="en"> - see below.

.a {
  width: 240px;
  border: 1px solid #eee;
}

.x {

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;

}

<div class="a" lang="en">
  <p class="x">
    A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy,
    my dear friend, so absorbed in the exquisite sense of mere tranquil existence, that I neglect my talents. I should be incapable of drawing a single stroke at the present moment; and yet I feel that I never was a greater artist than now.
  </p>
</div>


问:
passing variable to partial loop
Could it be possible to pass the values in partial loop. for code

EDIT:: in my file where partial is called, i've another array to pass. and i want S/N for array

```<code> <?php echo $this->partialLoop("partials/destination.phtml", $this->deslist);?>
</code>```

and i my partial/destination.phtml file i have

```<code><td><?php echo ++$count; ?></td>
</code>```

i am getting warning message

```<code>    Notice: Undefined variable: count in
    /var/www/globaltours.com/application/modules/admin/views/scripts/partials/destination.phtml
    on line 2 1
</code>```

i wanted to display the count(order) of the items

答:
You miss something like:</p>

```<code>$count = 0;
</code>```

Title: passing variable to partial loop

Body:
Could it be possible to pass the values in partial loop. for code

EDIT:: in my file where partial is called, i've another array to pass. and i want S/N for array

 <?php echo $this->partialLoop("partials/destination.phtml", $this->deslist);?>

and i my partial/destination.phtml file i have

<?php echo ++$count; ?>

i am getting warning message

    Notice: Undefined variable: count in
    /var/www/globaltours.com/application/modules/admin/views/scripts/partials/destination.phtml
    on line 2 1

i wanted to display the count(order) of the items

Body:
You miss something like:

$count = 0;


答:
Don't use events at all for this sort of operation. Certainly don't use many events for it. Instead, use a query (or view) that takes your end_date into account and determines your status value dynamically based on date. For example, to retrieve a particular item by id, do this.

```<code> SELECT id, start_date, end_date
        CASE WHEN end_date <= CURDATE() THEN 0  ELSE status END AS status
   FROM tblMatch
  WHERE id = something
</code>```

This query returns the row from the table, along with the status value based on the moment you run the query. (I set it up so items with status = 0 are always marked as expired never mind the current time.)

If you want all the items with status 1 (meaning non expired) do this:

```<code> SELECT id, start_date, end_date, 1 AS status
   FROM tblMatch
  WHERE end_date < CURDATE ()
    AND status = 1
</code>```

If you MUST use an event, you can run it once a day, sometime after midnight to reset the status columns of all expiring rows to 0, with a query like this.

```<code>  UPDATE tblMatch SET status = 0 WHERE status = 1 AND end_date < CURDATE();
</code>```

(I prefer to run daily update queries shortly after 03:00 local time. Why? I'm located in the USA, and our daylight saving time switchover is done, twice a year, at 02:00 local time. Doing daily updates after 03:00 ensures they'll still work properly on switchover days. )

For these queries to be efficient, you need a compound index on (status, end_date)

Body:
I have a table tblMatch :

+---------+---------------------+------------------+-----------+
|  ID     |      start_date     |     end_date     |  status   |
+---------+---------------------+------------------+-----------+
|  1      |   2017-12-09 03:23  | 2017-12-10 03:23 |      1    |
+---------+---------------------+------------------+-----------+
| ...     |         ...         |       ...        |      1    |
+---------+---------------------+------------------+-----------+
| 1000000 |   2017-12-22 15:12  | 2017-12-30 15:12 |      1    |
+---------+---------------------+------------------+-----------+

When I insert a row, I create one event too.
Event will change status to 0 if the match is ended.

CREATE EVENT test_event_increment_number
ON SCHEDULE AT end_date
ON COMPLETION NOT PRESERVE
DO
   UPDATE tblMatch SET status = 0 WHERE ID = increment_number;

If tblMatch has 100 million matches :
Does it effect server performance?
Is it bad or good idea to create a lot of events?

Body:
Don't use events at all for this sort of operation. Certainly don't use many events for it. Instead, use a query (or view) that takes your end_date into account and determines your status value dynamically based on date. For example, to retrieve a particular item by id, do this.

 SELECT id, start_date, end_date
        CASE WHEN end_date <= CURDATE() THEN 0  ELSE status END AS status
   FROM tblMatch
  WHERE id = something

This query returns the row from the table, along with the status value based on the moment you run the query. (I set it up so items with status = 0 are always marked as expired never mind the current time.)

If you want all the items with status 1 (meaning non expired) do this:

 SELECT id, start_date, end_date, 1 AS status
   FROM tblMatch
  WHERE end_date < CURDATE ()
    AND status = 1

If you MUST use an event, you can run it once a day, sometime after midnight to reset the status columns of all expiring rows to 0, with a query like this.

  UPDATE tblMatch SET status = 0 WHERE status = 1 AND end_date < CURDATE();

(I prefer to run daily update queries shortly after 03:00 local time. Why? I'm located in the USA, and our daylight saving time switchover is done, twice a year, at 02:00 local time. Doing daily updates after 03:00 ensures they'll still work properly on switchover days. )

For these queries to be efficient, you need a compound index on (status, end_date)


问:
Dynamic database connection using parameter available in url - codeigniter
I want to make dynamic database connection based on parameter in url which will be loaded first time. After that  maintain this connection throughout site.Example : maintaining using session or in define variable so that it will maintain connect throghout.</p>

答:
You can very much acheive the same using the pre_system hook.

There, you just need to perform the following steps.

Check in the session / cookie, if a variable for the db_in_use (whatever suites you) is available or not. If it is available, just dont do anything.

If it dose not exists back in the session. Just check the URL, based on the URL, set the variable value and put it in session. Now - you may create a variable which you may use to instantiate a connection with.

You may create a base model class where, based on the variable set - you may instantiate the connection for the application and extend each model from the base model created.

This should surely work for you.


问:
FlatList not displaying with fetched json object
I'm currently following Facebook's React Native Tutorial and I'm having trouble fetching a json object from https://facebook.github.io/react-native/movies.json and displaying it in a FlatList. Here is my code:

```<code>import React, { Component } from 'react';
import {FlatList, ActivityIndicator, ListView, View } from 'react-native';
import { Card, CardItem, Text, Container, Header, Title, Content, Footer, FooterTab, Button, Left, Right, Body, Icon } from 'native-base';

class JobPost extends Component {
  render(){
    return(
      <Card>
          <CardItem header>
              <Text>{this.props.header}</Text>
          </CardItem>
          <CardItem>
              <Body>
                  <Text>
                      {this.props.body}
                  </Text>
              </Body>
          </CardItem>
     </Card>
    )
  }
}

export default class Movies extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: ''
    }
  }

  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <FlatList
        data={this.state.dataSource}
        renderItem={({item}) => <Card header={item.title} body={item.releaseYear}/>}
        keyExtractor={item => item.title}
        />
      </View>
    );
  }
}
</code>```

The console log to print out the json object works correctly. However, I just get a blank screen when I run it in the IOS Simulator.

答:
Flat list will not update date if you don't set extraData.
You should use extraData for Flat list if want to update data (`extraData={this.state}    ): https://facebook.github.io/react-native/docs/0.48/flatlist.html#extradata

Body:
I'm currently following Facebook's React Native Tutorial and I'm having trouble fetching a json object from https://facebook.github.io/react-native/movies.json and displaying it in a FlatList. Here is my code:

import React, { Component } from 'react';
import {FlatList, ActivityIndicator, ListView, View } from 'react-native';
import { Card, CardItem, Text, Container, Header, Title, Content, Footer, FooterTab, Button, Left, Right, Body, Icon } from 'native-base';

class JobPost extends Component {
  render(){
    return(
      <Card>
          <CardItem header>
              <Text>{this.props.header}</Text>
          </CardItem>
          <CardItem>

                  <Text>
                      {this.props.body}
                  </Text>

          </CardItem>
     </Card>
    )
  }
}

export default class Movies extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: ''
    }
  }

  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <FlatList
        data={this.state.dataSource}
        renderItem={({item}) => <Card header={item.title} body={item.releaseYear}/>}
        keyExtractor={item => item.title}
        />
      </View>
    );
  }
}

The console log to print out the json object works correctly. However, I just get a blank screen when I run it in the IOS Simulator.


问:
cannot run multiple contexts at once
I am using pyspark (Python- 3.6.2), when i started spark context with the following code it is throwing exception.

Can any one faced this kind of issue earlier?
I am attaching below screenshot for reference

答:
This is expected behavior. Spark does not support it won't support multiple SparkContexts. For reference, corresponding JIRA (SPARK-2243) has been resolved as Won't Fix.

There is JVM specific spark.driver.allowMultipleContexts used for testing which was never supported in Python (https://stackoverflow.com/a/28260286) and quoting Josh Rosen:

Multiple active contexts might work, by accident, in some cases, so we added the new configuration as a temporary escape hatch and for use in testing; users generally should not enable that flag, since it only disables the error-checking and doesn't actually enable proper support for multiple contexts.

Title: cannot run multiple contexts at once


问:
Generate a random number tab without the same number
I wish create a tab of number but never have the same number.
Example of result wished [1,4,7,5,0,2,3,8,9,6]

I have this error :

maximum call stack size exceeded

I think it caused by recursive but I don't know what to do.

```<code>cardsAlreadyUsed = [1,4,7]

setNumCardsToUsed(cardsAlreadyUsed){
    var nbMin = 0; var nbMax = 9;
    var result = Math.floor((Math.random() * nbMax) + nbMin);
    var i = 0;

    while (i < cardsAlreadyUsed.length) {
      if (result == cardsAlreadyUsed[i]) {
        result = null;
        break;
      }
      i++;
    }
    if (result == null)
        setNumCardsToUsed(cardsAlreadyUsed);
    else
        cardsAlreadyUsed.push(result);

    return result;
};
</code>```

答:
One fast way in achieving what you need is to shuffle a set of unique array.

function generateNumber() {
    var array = [0,1,2,3,4,5,6,7,8,9];
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function makeTab() {
   var toReturn = numseries[ tabCounter ];
   tabCounter++;
   return toReturn;
}

//Counter
var tabCounter = 0;

//Generate the series of number on the pageLoad
var numseries = generateNumber();

//Call to generate new tab
var newtab = makeTab();

console.log( newtab );```

So basically, on the page load, you generate the series of unique number.

If you want to generate a new tab, you can call the function makeTab();

Body:
I wish create a tab of number but never have the same number.
Example of result wished [1,4,7,5,0,2,3,8,9,6]

I have this error :

maximum call stack size exceeded

I think it caused by recursive but I don't know what to do.

cardsAlreadyUsed = [1,4,7]

setNumCardsToUsed(cardsAlreadyUsed){
    var nbMin = 0; var nbMax = 9;
    var result = Math.floor((Math.random() * nbMax) + nbMin);
    var i = 0;

    while (i < cardsAlreadyUsed.length) {
      if (result == cardsAlreadyUsed[i]) {
        result = null;
        break;
      }
      i++;
    }
    if (result == null)
        setNumCardsToUsed(cardsAlreadyUsed);
    else
        cardsAlreadyUsed.push(result);

    return result;
};

Body:
One fast way in achieving what you need is to shuffle a set of unique array.

function generateNumber() {
    var array = [0,1,2,3,4,5,6,7,8,9];
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function makeTab() {
   var toReturn = numseries[ tabCounter ];
   tabCounter++;
   return toReturn;
}

//Counter
var tabCounter = 0;

//Generate the series of number on the pageLoad
var numseries = generateNumber();

//Call to generate new tab
var newtab = makeTab();

console.log( newtab );

So basically, on the page load, you generate the series of unique number.

If you want to generate a new tab, you can call the function makeTab();


问:
How can I schedule a task at time from django frontend?
I'm programming an irrigation system with Django and I use Celery to handle asynchronous tasks.

In my application the user selects the days and hours that he wants to activate the irrigation, this is stored in the database and he can update them at any time.

I know I can schedule tasks like this, but I want to update the time.

```<code>from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
    print("This runs every Monday morning at 7:30a.m.")
</code>```

Another way is to use python-crontab

答:
did something similar by having a runtime table listing what I wanted to run and when available to be selected from Django.

Periodic task itself was then scheduled to run every 30 seconds and check if anything requested in this table ready to be executed and called one of the workers.

Edit:as requested by Graham an example

The settings in Django to setup the beat:

```<code>CELERY_BEAT_SCHEDULE = {
    'Runtime': {
    'task': 'Runtime',
    'schedule': timedelta(seconds=15),
    },
}
</code>```

The task calling the model defined in Django (irrigation_requests in this e.g.) that the user would be updating through the front end:

```<code>def Runtime():
    #get all from model in state requested
    irrigation_job=Irrigation_Requests.objects.filter(Status__in=['Requested'])

    # Process each requested if flag to do just one thing then you could just test irrigation_job exists
    for job in irrigation_job:
        ....
        print ("This runs every when requested and depending on job parameters stored in your model can have further scope")

    #update requested this could be done in loop above
    irrigation_job.update(Status='Processed')
</code>```

Body:
I'm programming an irrigation system with Django and I use Celery to handle asynchronous tasks.

In my application the user selects the days and hours that he wants to activate the irrigation, this is stored in the database and he can update them at any time.

I know I can schedule tasks like this, but I want to update the time.

from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
    print("This runs every Monday morning at 7:30a.m.")

Another way is to use python-crontab

Body:
did something similar by having a runtime table listing what I wanted to run and when available to be selected from Django.

Periodic task itself was then scheduled to run every 30 seconds and check if anything requested in this table ready to be executed and called one of the workers.

Edit:as requested by Graham an example

The settings in Django to setup the beat:

CELERY_BEAT_SCHEDULE = {
    'Runtime': {
    'task': 'Runtime',
    'schedule': timedelta(seconds=15),
    },
}

The task calling the model defined in Django (irrigation_requests in this e.g.) that the user would be updating through the front end:

def Runtime():
    #get all from model in state requested
    irrigation_job=Irrigation_Requests.objects.filter(Status__in=['Requested'])

    # Process each requested if flag to do just one thing then you could just test irrigation_job exists
    for job in irrigation_job:
        ....
        print ("This runs every when requested and depending on job parameters stored in your model can have further scope")

    #update requested this could be done in loop above
    irrigation_job.update(Status='Processed')

ContentLicense: CC BY-SA 4.0


问:
split database output in mule
I'm having below database output, how do i split it.

```<code> [{country=United States, accountID=4410, street=12345 Green Rd, state=Colorado, name=Dale Burgers, city=Boulder, postal=80305}, {country=United Kingdom, accountID=4411, street=capthorne Avenue, state=Harrow, name=Arjun, city=london, postal=ha29eb}, {country=usa, accountID=4412, street=elden st, state=va, name=Home Foods, city=herndon, postal=20170}, {country=usa, accountID=4413, street=herndon parkway, state=va, name=Home Foods 2, city=herndon, postal=20170}, {country=usa, accountID=4414, street=van barun st, state=va, name=home foods 3, city=herndon, postal=20170}, {country=United Kingdom, accountID=4415, street=355 E Capthorne Court, Alexandra Avenue, state=Harrow, name=Barkha , city=Haarow London, postal=ha29eb}, {country=Canada, accountID=4416, street=4130 Chromoly, state=BC, name=Spawn Cycles, city=Squamish, postal=L0L0L0}, {country=Canada, accountID=4417, street=1 Yonge Street, state=BC, name=Post Spawn, city=Vancouver, postal=L1L1L1}, {country=Canada, accountID=4418, street=1 Yonge Street, state=BC, name=Post Post Spawn, city=Vancouver, postal=L2L2L2}, {country=Canada, accountID=4419, street=1 Yonge Street, state=BC, name=Post Post Post Spawn, city=Vancouver, postal=L0L0L0}]
</code>```

i tried adding JSON to Object Transformer forming List type and Collection splitter but only first record is being passed.

```<code> {country=United States, accountID=4410, street=12345 Green Rd, state=Colorado, name=Dale Burgers, city=Boulder, postal=80305}
</code>```

答:
Database output should be List or Iterator only. But if you are getting JSON. You can achieve it in following ways

Using Dataweave which will return List-

```<code>%dw 1.0
%output application/java
---
payload
</code>```

Using Dataweave MEL function which will return Iterator (SplitIterator) -

```<code><set-payload value="#[split('payload','application/json')]" doc:name="Set Payload"/>
</code>```

Using JSON to Object Transformer -

```<code><json:json-to-object-transformer returnClass="java.util.List" doc:name="JSON to Object"/>
</code>```

Hope this helps.

Title: split database output in mule

Body:
I'm having below database output, how do i split it.

 [{country=United States, accountID=4410, street=12345 Green Rd, state=Colorado, name=Dale Burgers, city=Boulder, postal=80305}, {country=United Kingdom, accountID=4411, street=capthorne Avenue, state=Harrow, name=Arjun, city=london, postal=ha29eb}, {country=usa, accountID=4412, street=elden st, state=va, name=Home Foods, city=herndon, postal=20170}, {country=usa, accountID=4413, street=herndon parkway, state=va, name=Home Foods 2, city=herndon, postal=20170}, {country=usa, accountID=4414, street=van barun st, state=va, name=home foods 3, city=herndon, postal=20170}, {country=United Kingdom, accountID=4415, street=355 E Capthorne Court, Alexandra Avenue, state=Harrow, name=Barkha , city=Haarow London, postal=ha29eb}, {country=Canada, accountID=4416, street=4130 Chromoly, state=BC, name=Spawn Cycles, city=Squamish, postal=L0L0L0}, {country=Canada, accountID=4417, street=1 Yonge Street, state=BC, name=Post Spawn, city=Vancouver, postal=L1L1L1}, {country=Canada, accountID=4418, street=1 Yonge Street, state=BC, name=Post Post Spawn, city=Vancouver, postal=L2L2L2}, {country=Canada, accountID=4419, street=1 Yonge Street, state=BC, name=Post Post Post Spawn, city=Vancouver, postal=L0L0L0}]

i tried adding JSON to Object Transformer forming List type and Collection splitter but only first record is being passed.

 {country=United States, accountID=4410, street=12345 Green Rd, state=Colorado, name=Dale Burgers, city=Boulder, postal=80305}

Body:
Database output should be List or Iterator only. But if you are getting JSON. You can achieve it in following ways

Using Dataweave which will return List-

%dw 1.0
%output application/java
---
payload

Using Dataweave MEL function which will return Iterator (SplitIterator) -

<set-payload value="#[split('payload','application/json')]" doc:name="Set Payload"/>

Using JSON to Object Transformer -

<json:json-to-object-transformer returnClass="java.util.List" doc:name="JSON to Object"/>

Hope this helps.


问:
Symfony 2.8 FOSUserBundle Change the redirection after the password resetting
I'm following the FOSUserbundle Official documentation in order to change the redirection after a password resetting procedure. I created a new class named PasswordResettingListener and add it to services.yml

The class is executes up to the getSubscribedEvents() method but Symfony never calls my specific method that performs the redirect. Am I misunderstanding something?

src/AppBundle/EventListener/PasswordResettingListener.php:

```<code><?php
// src/AppBundle/EventListener/PasswordResettingListener.php

namespace AppBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class PasswordResettingListener implements EventSubscriberInterface {
    private $router;

    public function __construct(UrlGeneratorInterface $router){
        $this->router = $router;
    }

    /**
    * CALLED!
    */
    public static function getSubscribedEvents() {
        return array(
        FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess',
        );
    }

    public function onPasswordResettingSuccess(FormEvent $event) {
        die("alone"); //never called
        $url = $this->router->generate('tarifs'); //nevercalled
        die("die alone !!!!!"); // never called
        $event->setResponse(new RedirectResponse($url)); // ""
    }
}
</code>```

The service is recorded here (/app/config/services.yml):
    # app/config/services.yml
    services:

```<code>app.form.registration:
    class: AppBundle\Form\RegistrationType
    tags:
        - { name: form.type, alias: app_user_registration }

app.password_resetting:
    class: AppBundle\EventListener\PasswordResettingListener
    arguments: [@router]
    tags:
        - { name: kernel.event_subscriber }
</code>```

答:
You can use FOSUser's routing in order to change the redirect.
When importing it's routes, you have two options: either you add all by adding

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

or each of them, by path. This is the one for the user's profile:

```<code>fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile
</code>```

Just change it's prefix by your desired path and that's all.

PS: I tried to use Event Listener as well but it didn't worked.

Good luck!

Body:
I'm following the FOSUserbundle Official documentation in order to change the redirection after a password resetting procedure. I created a new class named PasswordResettingListener and add it to services.yml

The class is executes up to the getSubscribedEvents() method but Symfony never calls my specific method that performs the redirect. Am I misunderstanding something?

src/AppBundle/EventListener/PasswordResettingListener.php:

<?php
// src/AppBundle/EventListener/PasswordResettingListener.php

namespace AppBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class PasswordResettingListener implements EventSubscriberInterface {
    private $router;

    public function __construct(UrlGeneratorInterface $router){
        $this->router = $router;
    }

    /**
    * CALLED!
    */
    public static function getSubscribedEvents() {
        return array(
        FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess',
        );
    }

    public function onPasswordResettingSuccess(FormEvent $event) {
        die("alone"); //never called
        $url = $this->router->generate('tarifs'); //nevercalled
        die("die alone !!!!!"); // never called
        $event->setResponse(new RedirectResponse($url)); // ""
    }
}

The service is recorded here (/app/config/services.yml):
    # app/config/services.yml
    services:

app.form.registration:
    class: AppBundle\Form\RegistrationType
    tags:
        - { name: form.type, alias: app_user_registration }

app.password_resetting:
    class: AppBundle\EventListener\PasswordResettingListener
    arguments: [@router]
    tags:
        - { name: kernel.event_subscriber }

Body:
You can use FOSUser's routing in order to change the redirect.
When importing it's routes, you have two options: either you add all by adding

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

or each of them, by path. This is the one for the user's profile:

fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile

Just change it's prefix by your desired path and that's all.

PS: I tried to use Event Listener as well but it didn't worked.

Good luck!


问:
Destructive Stack Iteration
This is my Stack implementation.

```<code>class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return self

    def __next__(self):
        if self.head:
            curr = self.head
        else:
            raise StopIteration()
        self.head = self.head.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    for item in stack:
        print(item)
    print(stack.peek())
</code>```

The problem with this is the iteration. The iteration is destructive and thus the call to peek at the end of the iteration throws an error.

return self.head.val
AttributeError: 'NoneType' object has no attribute 'val'
How do I make the iteration non-desctructive?

答:
Because you can have more than one iterator on the same stack, __iter__ has to return a iterator-object, that iterates the stack:

```<code>class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if self.head:
            node.next = self.head
        self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return StackIterator(self.head)

class StackIterator:
    def __init__(self, head):
        self.head = head

    def __iter__(self):
        return self

    def __next__(self):
        if not self.head:
            raise StopIteration()
        item = self.head.val
        self.head = self.head.next
        return item
</code>```

Title: Destructive Stack Iteration

Body:
This is my Stack implementation.

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return self

    def __next__(self):
        if self.head:
            curr = self.head
        else:
            raise StopIteration()
        self.head = self.head.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    for item in stack:
        print(item)
    print(stack.peek())

The problem with this is the iteration. The iteration is destructive and thus the call to peek at the end of the iteration throws an error.

return self.head.val
AttributeError: 'NoneType' object has no attribute 'val'
How do I make the iteration non-desctructive?

Body:
Because you can have more than one iterator on the same stack, __iter__ has to return a iterator-object, that iterates the stack:

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if self.head:
            node.next = self.head
        self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return StackIterator(self.head)

class StackIterator:
    def __init__(self, head):
        self.head = head

    def __iter__(self):
        return self

    def __next__(self):
        if not self.head:
            raise StopIteration()
        item = self.head.val
        self.head = self.head.next
        return item


问:
Changing a List to a Dataframe in R
I have used the "htmltab" library to get data on the NFL draft and combine. The data has been selected fine but they are lists at the moment. I intend to merge them and perform analysis the data. at the moment it looks like this:
 image List of combine 2016 1
Whenever I try use the unlist method I lose the headers of the columns and they are still remaining as a list.
any suggestions on this?</p>

```<code>urlcom16 <- "http://nflcombineresults.com/nflcombinedata.php?
year=2016&pos=&college="
com16 <- htmltab(doc=urlcom16, which=1)
</code>```

答: Try as.data.frame(com16). If it doesn't work, you might not have the same vector length in each list entry.</p>

Title: Changing a List to a Dataframe in R

Body:
I have used the "htmltab" library to get data on the NFL draft and combine. The data has been selected fine but they are lists at the moment. I intend to merge them and perform analysis the data. at the moment it looks like this:
 image List of combine 2016 1
Whenever I try use the unlist method I lose the headers of the columns and they are still remaining as a list.
any suggestions on this?

urlcom16 <- "http://nflcombineresults.com/nflcombinedata.php?
year=2016&pos=&college="
com16 <- htmltab(doc=urlcom16, which=1)


问:
Hibernate: What is the correct way to update collection of an entity?
I am trying to optimize our hibernate application. In many places, while add/updating a collection of an entity, we are clearing it first, and then add all of them again from the input. I feel somehow, there should be a better way but could not found yet.

How do you do in your applications.?

答:
I guess with collection, you mean the "many" side of an @OneToMany relationship.

In this case, you can specify the value orphanRemoval in the @OneToMany annotation to the foreign reference in the owning class:

```<code>public class Parent {

    // ...

    @OneToMany(mappedBy = "whatever", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<Child> children;

}
</code>```

orphanRemoval will instruct Hibernate to delete all existing child entities that have been removed from the collection when the parent entity is persisted.

Body:
I guess with collection, you mean the "many" side of an @OneToMany relationship.

In this case, you can specify the value orphanRemoval in the @OneToMany annotation to the foreign reference in the owning class:

public class Parent {

    // ...

    @OneToMany(mappedBy = "whatever", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<Child> children;

}

orphanRemoval will instruct Hibernate to delete all existing child entities that have been removed from the collection when the parent entity is persisted.


答: Go to manifests > AndroidManifest.xml > You can change the title by changing the android:label field, in this specific case find aplication and change android:label. If you want an specific activity, you find the activity and is the same process

Title: how to change the text on the AppTheme?

Body:
I want to change the title that appear on my app.
This text is taken from the string.xml => the 'app_name'
Can't remove and use some other AppTheme ( using the default ) because this remove the 3 dots that i have to show the 'settings' activity.

I trying to play with all the AppTheme settings .. and nothing change this text.


问:
C - Storing pointers with malloc() in an array, can't free() them afterwards
I want to store pointers that have been allocated using malloc() in an array and then free all of them after. However even though the program doesn't complain it doesn't work. Below cleanMemManager() won't actually free the memory as when tested inside main() the char* pointer is not NULL and it will print ???.

code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void **ptrList = NULL;

void tfree(void** ptr)
{
    free(*ptr);
    *ptr = NULL;
}

void* talloc(int size)
{
    void* ptr = malloc(size);
    ptrList[0] = ptr;   ///No clue if this actually does what I think it does
    return ptrList[0];
}

void initMemManager()
{
    ptrList = (void**)malloc(sizeof(void**) * 3);
    memset(ptrList, 0, sizeof(void**) * 3);
}

void cleanMemManager()
{
    tfree(&ptrList[0]); //Doesn't free the right pointer it seems
}

int main()
{
    initMemManager();
    char* ptr = (char*)talloc(3);
    cleanMemManager();

    if (ptr != NULL) //This will trigger and I'm not expecting it to
        printf("???");

    getchar();
    return 0;
}
</code>```

I don't understand the syntax to use for this, does the pointer not actually get touched at all? What is it freeing then since it doesn't throw any errors?

答:
Freeing doesn't guarantee that pointers pointing to the allocated block will be set to NULL. If you actually try doing

```<code>if (ptrList[0] != NULL)
      printf("ptrList[0] != NULL");
</code>```

you will see that the program won't output and if you remove the cleanMemManager() function call, it will output. This means tfree function is working as intended, it's freeing the memory that was allocated.

Now as to why ptr variable being not set to NULL, it's simply because ptr is still storing the old address. cleanMemManager() has no way of mutating the variable ptr. This is commonly called dangling pointer or use after free.

Also free() doesn't clean/zero out the the allocated space, the block is simply marked as "free". The data will most likely remain in the memory for a moment until the free block is overwritten by another malloc request.

Body:
I want to store pointers that have been allocated using malloc() in an array and then free all of them after. However even though the program doesn't complain it doesn't work. Below cleanMemManager() won't actually free the memory as when tested inside main() the char* pointer is not NULL and it will print ???.

code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void **ptrList = NULL;

void tfree(void** ptr)
{
    free(*ptr);
    *ptr = NULL;
}

void* talloc(int size)
{
    void* ptr = malloc(size);
    ptrList[0] = ptr;   ///No clue if this actually does what I think it does
    return ptrList[0];
}

void initMemManager()
{
    ptrList = (void**)malloc(sizeof(void**) * 3);
    memset(ptrList, 0, sizeof(void**) * 3);
}

void cleanMemManager()
{
    tfree(&ptrList[0]); //Doesn't free the right pointer it seems
}

int main()
{
    initMemManager();
    char* ptr = (char*)talloc(3);
    cleanMemManager();

    if (ptr != NULL) //This will trigger and I'm not expecting it to
        printf("???");

    getchar();
    return 0;
}

I don't understand the syntax to use for this, does the pointer not actually get touched at all? What is it freeing then since it doesn't throw any errors?

Body:
Freeing doesn't guarantee that pointers pointing to the allocated block will be set to NULL. If you actually try doing

if (ptrList[0] != NULL)
      printf("ptrList[0] != NULL");

you will see that the program won't output and if you remove the cleanMemManager() function call, it will output. This means tfree function is working as intended, it's freeing the memory that was allocated.

Now as to why ptr variable being not set to NULL, it's simply because ptr is still storing the old address. cleanMemManager() has no way of mutating the variable ptr. This is commonly called dangling pointer or use after free.

Also free() doesn't clean/zero out the the allocated space, the block is simply marked as "free". The data will most likely remain in the memory for a moment until the free block is overwritten by another malloc request.


问:
Swapping two elements in Python
I was watching a video where all of a sudden the instructor uses the given code to swap two elements of a list L:

```<code>L[suffix], L[i] = L[i], L[suffix]
</code>```

What is the procedure undertaken inside for this method of swap? Is a new list formed? Or a tuple? Or a dictionary? Or something else???

Title: Swapping two elements in Python

Body:
I was watching a video where all of a sudden the instructor uses the given code to swap two elements of a list L:

L[suffix], L[i] = L[i], L[suffix]

What is the procedure undertaken inside for this method of swap? Is a new list formed? Or a tuple? Or a dictionary? Or something else???

Body:
It's easy to understand

>>> L = [0,4]
>>> L[0],L[1] = L[1],L[0]
>>> L
[4, 0]

Or this example,in this case you swap first and third element

>>> P = [0,4,9]
>>> P[0],P[2] = P[2],P[0]
>>> P
[9, 4, 0]


答:
The problem is that you do not make a difference between the iterable Stack itself and the iterator that __iter__ should return. __next__ should be called on said iterator, not on the Stack itself.

I propose the following solution:

```<code>class StackIterator:
    def __init__(self, stack):
        self.head = stack.head

    def __iter__(self):
        return self

    def __next__(self):
        if not self.head:
            raise StopIteration

        current = self.head
        self.head = self.head.next

        return current.val
</code>```

Get rid of __next__ in Stack and adjust __iter__ to:

```<code>def __iter__(self):
    return StackIterator(self)
</code>```

Demo:

```<code>>>> stack = Stack()
>>> stack.push(12)
>>> stack.push(13)
>>> stack.push(9)
>>>
>>> for x in stack:
...     print(x)
...
9
13
12
>>> stack.peek()
9
</code>```

Title: Destructive Stack Iteration

Body:
The problem is that you do not make a difference between the iterable Stack itself and the iterator that __iter__ should return. __next__ should be called on said iterator, not on the Stack itself.

I propose the following solution:

class StackIterator:
    def __init__(self, stack):
        self.head = stack.head

    def __iter__(self):
        return self

    def __next__(self):
        if not self.head:
            raise StopIteration

        current = self.head
        self.head = self.head.next

        return current.val

Get rid of __next__ in Stack and adjust __iter__ to:

def __iter__(self):
    return StackIterator(self)

Demo:

>>> stack = Stack()
>>> stack.push(12)
>>> stack.push(13)
>>> stack.push(9)
>>>
>>> for x in stack:
...     print(x)
...
9
13
12
>>> stack.peek()
9


答:
In main, char *ptr = (char*)talloc(3); declares ptr to be a local variable. It contains a copy of the value returned by talloc, and none of your subroutines know about ptr or where it is. So none of them change the value of ptr. Thus, when you reach if (ptr != NULL), the value of ptr has not changed.

Additionally:

In initMemManager, you should use sizeof(void *) in two places where you have sizeof(void**). In these places, you are allocating and copying void * objects, not void ** objects.

It looks like you are trying to implement a sort of smart memory manager that automatically sets pointers to NULL when they are freed. To do that in C, you would have to give up having copies of pointers. For example, ptr is a copy of ptrList[0], but tfree only sets whichever copy it is passed to NULL. We could give advice on building such a system, but it would quickly become cumbersome—your memory manager needs to keep a database of pointers and their copies (and pointers derived from them, as by doing array arithmetic). Or you have to refer to everything indirectly through that ptrList array, which adds some mess to your source code. Unfortunately, C is not a good language for this.

Title: C - Storing pointers with malloc() in an array, can't free() them afterwards