问:
Angular RxJS: Do something when an observable is subscribed or unsubscribed
I'm translating some Javascript events to Observables using RxJS in an Angular app (Ionic framework). I want to start listening to the events when the "client" calls .subscribe(), and stop listening for them when he calls .unsubscribe(). I've looked at the documentation of the Observable class, but I wasn't able to see how to do that.

So, assuming there were "onSubscribe" and "onUnsubscribe" methods, I'd like to do something like this:

```<code>import { Observable, Subject } from 'rxjs';

...

on(name: string) : Observable<Event> {
    let observable = new Subject<any>();

    observable.onSubscribe(() => {
         this.addEventListener(name, (event) => {
             observable.next(event);
         });
    });

    observable.onUnsubscribe(() => {
        this.removeEventListener(name);
    });

    return observable;
}
</code>```

Is there any way to achieve this?

Thanks!

答:
import { Observable, Subject } from 'rxjs';

...

const unsubscribe;

on(name: string) : Observable<Event> {
    let observable = new Subject<any>();
    // subscribe method returns unsubscribe function, so you have to save in some varibale then call it.
    this.unsubscribe = observable.subscribe(() => {
         this.addEventListener(name, (event) => {
             observable.next(event);
         });
    });

    return observable;
}

// some where else you can do this
unsubscribe();```

Body:
I'm translating some Javascript events to Observables using RxJS in an Angular app (Ionic framework). I want to start listening to the events when the "client" calls .subscribe(), and stop listening for them when he calls .unsubscribe(). I've looked at the documentation of the Observable class, but I wasn't able to see how to do that.

So, assuming there were "onSubscribe" and "onUnsubscribe" methods, I'd like to do something like this:

import { Observable, Subject } from 'rxjs';

...

on(name: string) : Observable<Event> {
    let observable = new Subject<any>();

    observable.onSubscribe(() => {
         this.addEventListener(name, (event) => {
             observable.next(event);
         });
    });

    observable.onUnsubscribe(() => {
        this.removeEventListener(name);
    });

    return observable;
}

Is there any way to achieve this?

Thanks!


来源: stackexchange

问:
Multiline PageTitle with android.support.design.widget.TabLayout
in an android app, I use a TabLayout to display multiple Fragments in a single activity.
I want the tabs to be labeled with icons and a two line heading.

In the Activity's onCreate I initialise the SectionsPageAdapter and the TabLayout like:

```<code>private SectionsPagerAdapter mSectionsPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
    SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    // add a PageChangeListener to be able to detect which tab is activated
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
        ...
    });

    ...
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

    //Set icons for tabs
    tabLayout.getTabAt(0).setIcon(R.drawable.ic0);
    tabLayout.getTabAt(1).setIcon(R.drawable.ic1);
    tabLayout.getTabAt(2).setIcon(R.drawable.ic2);
}
</code>```

And in the SectionpagerAdapter I define the PageTitles using:

```<code>public CharSequence getPageTitle(int position) {
    switch (position) {
        case 0:
            return "First \nTab";
        case 1:
            return "Second \nTab";
        case 2:
            return "Third \nTab";
    }
    return null;
}
</code>```

But when i run the app, the PageTitles aren't broken in two lines, but shortened with ... to fit the screen.

How to enable multiline PageTitles for the Tabs?

答:
```<code>tabLayout.getTabAt(i).setCustomView(yuorTabView);
</code>```

And you can customize your own TabView

ContentLicense: CC BY-SA 3.0

Body:
in an android app, I use a TabLayout to display multiple Fragments in a single activity.
I want the tabs to be labeled with icons and a two line heading.

In the Activity's onCreate I initialise the SectionsPageAdapter and the TabLayout like:

private SectionsPagerAdapter mSectionsPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
    SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    // add a PageChangeListener to be able to detect which tab is activated
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
        ...
    });

    ...
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

    //Set icons for tabs
    tabLayout.getTabAt(0).setIcon(R.drawable.ic0);
    tabLayout.getTabAt(1).setIcon(R.drawable.ic1);
    tabLayout.getTabAt(2).setIcon(R.drawable.ic2);
}

And in the SectionpagerAdapter I define the PageTitles using:

public CharSequence getPageTitle(int position) {
    switch (position) {
        case 0:
            return "First \nTab";
        case 1:
            return "Second \nTab";
        case 2:
            return "Third \nTab";
    }
    return null;
}

But when i run the app, the PageTitles aren't broken in two lines, but shortened with ... to fit the screen.

How to enable multiline PageTitles for the Tabs?

Body:
tabLayout.getTabAt(i).setCustomView(yuorTabView);

And you can customize your own TabView


问:
Pandas Groupby Sum to Columns
I am doing groupby and can get the sum for a column ok, but how to I get sum of two columns together?

```<code>detail [ 'debit' ] = df.groupby ( 'type' ) [ 'debit' ].sum ()
detail [ 'credit' ] = df.groupby ( 'type' ) [ 'credit' ].sum ()
</code>```

Now I need the (credit - debit) together.

something like this:

```<code>detail [ 'profit' ] = df.groupby ( 'type' ) ( [ 'credit' ] - [ 'debit'  ] ).sum ()
</code>```

obviously that does not work.

Thanks.

答:
Like @IanS suggested, I would first save the result in a new column and apply the groupby function afterwards:

```<code>df['profit'] = df['credit'] - df['debit']
detail = df.groupby('type').sum()[['profit', 'credit', 'debit']]
</code>```

I also combined the the groupby-actions into one.

Title: Pandas Groupby Sum to Columns

Body:
I am doing groupby and can get the sum for a column ok, but how to I get sum of two columns together?

detail [ 'debit' ] = df.groupby ( 'type' ) [ 'debit' ].sum ()
detail [ 'credit' ] = df.groupby ( 'type' ) [ 'credit' ].sum ()

Now I need the (credit - debit) together.

something like this:

detail [ 'profit' ] = df.groupby ( 'type' ) ( [ 'credit' ] - [ 'debit'  ] ).sum ()

obviously that does not work.

Thanks.

Body:
Like @IanS suggested, I would first save the result in a new column and apply the groupby function afterwards:

df['profit'] = df['credit'] - df['debit']
detail = df.groupby('type').sum()[['profit', 'credit', 'debit']]

I also combined the the groupby-actions into one.


问:
Show div on click
I'm trying to make a div appear and disappear using javascript, but it's not working.I've included the javascript file(where the function is),but I don't understand why it's not working.

When I press the button, nothing happens.

HTML code:

```<code><script type="text/javascript" src="show_on_click.js"></script>

<div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>
</code>```

JavaScript code:

```<code>function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
}
</code>```

答:
Try this:

```<code><div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

<script>
  function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
  }
</script>
</code>```

There are one or both of two errors:

your src path for script is wrong

somewhere you redefine function for button

Title: Show div on click

Body:
I'm trying to make a div appear and disappear using javascript, but it's not working.I've included the javascript file(where the function is),but I don't understand why it's not working.

When I press the button, nothing happens.

HTML code:

Button Test

<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

JavaScript code:

function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
}

Body:
Try this:

<div id="myDiv" style="display:none" class="answer_list">Button Test</div>
<input type="button" name="answer" onclick="ShowDiv()" value="Test"/>

<script>
  function ShowDiv(){
    document.getElementById("myDiv").style.display = 'block';
  }
</script>

There are one or both of two errors:

your src path for script is wrong

somewhere you redefine function for button


问:
I do not understand this PHP Code, what is it doing?
How to read php

i'm learning php, I wrote this.  (It is from a book)

```<code>   <?php if(!empty($data)):  ?>
        <ul>
             <?php foreach ($data as $dataprint): ?>
                  <li><?= $dataprint ?></li>
             <?php endforeach ?>
        </ul>
</code>```

I am unable to understand some of the code in this section.

 1. Why are there colons on line 1 and 3?

 2. What does the '<?= $dataprint ?> ) and why does it not have the standard 'PHP' word?

 3. why is there an equal mark in the next?

答:
Colons on lines 1 and 3 are an alternative way of doing the below code

```<code>if (!empty($data)) {
    ...
}
</code>```

It makes it a lot cleaner when outputting HTML.

(See http://php.net/manual/en/control-structures.alternative-syntax.php)

<?= is a shorthand way of writing <?php echo, again it's just an alternative way of doing things.

(See http://php.net/manual/en/function.echo.php)

Body:
How to read php

i'm learning php, I wrote this.  (It is from a book)

   <?php if(!empty($data)):  ?>

             <?php foreach ($data as $dataprint): ?>

<?= $dataprint ?>

             <?php endforeach ?>

I am unable to understand some of the code in this section.

 1. Why are there colons on line 1 and 3?

 2. What does the '<?= $dataprint ?> ) and why does it not have the standard 'PHP' word?

 3. why is there an equal mark in the next?

Body:
Colons on lines 1 and 3 are an alternative way of doing the below code

if (!empty($data)) {
    ...
}

It makes it a lot cleaner when outputting HTML.

(See http://php.net/manual/en/control-structures.alternative-syntax.php)

<?= is a shorthand way of writing <?php echo, again it's just an alternative way of doing things.

(See http://php.net/manual/en/function.echo.php)


问:
rails - Case Insensitive Search Condition
I have the following:

```<code>  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["fname || ' ' || lname LIKE ?", '%'+"#{params[:q]}"+'%']
</code>```

Problem here is that the search input params[:q] is case sensitive. How can I make it case insensitive in my Rails 3 Heroku app?

Thanks

答: A fairly "common" workaround for this problem seems to be to use the UPPER function to convert in your case "fname" or "lname" into uppercase and convert params[:q] as well, using e.g. upcase.

ContentLicense: CC BY-SA 2.5

Body:
I have the following:

  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["fname || ' ' || lname LIKE ?", '%'+"#{params[:q]}"+'%']

Problem here is that the search input params[:q] is case sensitive. How can I make it case insensitive in my Rails 3 Heroku app?

Thanks


问:
Is loop a good choice instead of what I have created?
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...</p>

```<code>// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});
</code>```

答:
Yes, it can be done with a loops:

var resets = [
  {id: 'inputTitleTag', props: ['value']},
  {id: 'titleTag', props: ['value']},
  {id: 'example', props: ['innerHTML']},
  {id: 'tytul', props: ['style', 'color']},
  {id: 'good', props: ['innerHTML']}
]
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  resets.forEach(function(reset) {
    reset.props.length === 1 ? document.getElementById(reset.id)[reset.props[0]] = "" : document.getElementById(reset.id)[reset.props[0]][reset.props[1]] = "";
  });
});
```

Body:
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...

// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});


问:
Realtime-notifications with ajax
Hello i'm a new developer and  in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me

here's my index page :

```<code>@extends('admin.app')
@section('content')
    <div class="container">
        <div class="row" style ="padding-top:40px;">
            <h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
            <br/><br/>
            <div class="col-md-2">
                    <p>Users online</p>
                    @foreach($users as $user)
                        @if($user->isOnline())
                            <li>{{$user->FullName}}</li>
                        @endif
                    @endforeach

            </div>

            <div class="col-md-8">
                <div class="panel panel-info">
                    <div class="panel-heading">
                        Recent Chat
                    </div>
                    <div class="panel-body">
                        <ul class="media-list" id="message">

                            @foreach($messages as $message )
                                <li class="media">
                                    <div class="media-body">
                                        <div class="media">

                                            <div class="media-body" >
                                                {{$message->message}}
                                                <br/>
                                               <bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
                                                   </small></bold>
                                                <hr>
                                            </div>
                                        </div>
                                    </div>
                                </li>

                            @endforeach
                        </ul>
                        <div>
                            <div class="panel-footer">
                                <div class="input-group">
                                    <input type="text" name="message" class="form-control" placeholder="Enter Message"/>
                                    {{csrf_field()}}
                                    <input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
                                    <span class="input-group-btn">
                                    <button type="submit" id="send" class="btn btn-info">Send</button>
                                </span>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            setTimeout(realTime, 2000);
        });
        function realTime() {
            $.ajax({
                type:'post',
                url:'/chat/get',
                data:{
                    '_token':$('input[name=_token]').val(),
                },
                success: function (data) {
                    $('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
                    for (var i=0; i < data.length; i++){
                        $('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
                    }
                },
            });
            setTimeout(realTime, 2000);
        }
        $(document).on('click','#send', function (){
            $.ajax({
                type:'post',
                url:'/chat/send',
                data:{
                    '_token':$('input[name=_token]').val(),
                    'from_name':$('input[name=from_name]').val(),
                    'message':$('input[name=message]').val(),
                },
                success: function (data) {
                  $('#message').append('  <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
                }
            })

            $('input[name=message]').val('');
        });

    </script>

@stop
</code>```

here's my routes :

```<code>Route::get('/chat', 'Chat\ChatController@index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController@sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController@getMessage' );
</code>```

here's my controllers:

```<code> public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $users=user::all();
        $messages=message::all();
        return view('admin.chat.index',['messages'=> $messages],compact('users'));
    }

    public function sendMessage(Request $request){

        $send = new Message();
        $send ->from_name = $request->from_name;
        $send ->message = $request->message;
        $send->save();
        return response()->json($send);

    }

    public function  getMessage(){
        $message = Message::all();
        return response()->json($message);

    }
</code>```

Sorry in advanced for the bad english but i am a foreigner

答:
```<code>   $(window).load(realTime);
    function realTime() {
        $.ajax({
            type:'post',
            url:'/chat/get',
            data:{
                '_token':$('input[name=_token]').val(),
            },
            success: function (data) {
                $('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
                for (var i=0; i < data.length; i++){
                    $('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
                }
             setTimeout(realTime, 2000);
            },
        });

    }
}
</code>```

Try this..

Title: Realtime-notifications with ajax

Body:
Hello i'm a new developer and  in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me

here's my index page :

@extends('admin.app')
@section('content')

Welcome {{Auth::user()->FullName}}

Users online

                    @foreach($users as $user)
                        @if($user->isOnline())

{{$user->FullName}}

                        @endif
                    @endforeach

                        Recent Chat

                            @foreach($messages as $message )

                                                {{$message->message}}

                                               <bold> {{$message->from_name}} |{{$message->created_at}}
                                                   </bold>

                            @endforeach

                                    <input type="text" name="message" class="form-control" placeholder="Enter Message"/>
                                    {{csrf_field()}}
                                    <input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">

                                    <button type="submit" id="send" class="btn btn-info">Send</button>

@stop

here's my routes :

Route::get('/chat', 'Chat\ChatController@index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController@sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController@getMessage' );

here's my controllers:

 public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $users=user::all();
        $messages=message::all();
        return view('admin.chat.index',['messages'=> $messages],compact('users'));
    }

    public function sendMessage(Request $request){

        $send = new Message();
        $send ->from_name = $request->from_name;
        $send ->message = $request->message;
        $send->save();
        return response()->json($send);

    }

    public function  getMessage(){
        $message = Message::all();
        return response()->json($message);

    }

Sorry in advanced for the bad english but i am a foreigner

Body:
   $(window).load(realTime);
    function realTime() {
        $.ajax({
            type:'post',
            url:'/chat/get',
            data:{
                '_token':$('input[name=_token]').val(),
            },
            success: function (data) {
                $('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
                for (var i=0; i < data.length; i++){
                    $('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
                }
             setTimeout(realTime, 2000);
            },
        });

    }
}

Try this..


问:
Checked checkbox using array response in JavaScript
I have a form and it has 4 checkboxes. I am getting a response from the server and according to that response I need to checked that particular checkbox/s.

For example I have four checkboxes called 2100,2200,2300,2400

Then I am getting a array response from the server and array has 2200 and 2400.
Then I need to checked both 2200 and 2400 checkboxes.

```<code>$.ajax({
    type: "POST",
    url: "send_db.php",
    data: {'send_array':array_send},
    success:  function(data){

    var jsonRes  = jQuery.parseJSON(data);
    var plant  = jsonRes.plant;
    var array_length = jsonRes.plant.length;

    for (var i = 0; i < array_length; i++) {

        document.getElementsByName("user_plant1").checked = true;

    }

    }
});
</code>```

Here plant has the values.

These are my checkboxes...

```<code><div class="form-group">
    <label class="checkbox-inline"><input type="checkbox" id="chk21" name="user_plant1" value="2100">2100</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk22" name="user_plant1" value="2200">2200</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk23" name="user_plant1" value="2300">2300</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk24" name="user_plant1" value="2400">2400</label>
</div>
</code>```

答:
Try the following way:

var chkData = "2200,2400";
chkData = chkData.split(',');

var el=document.querySelectorAll('input[name=user_plant1]');
el.forEach(function(chk){
  if(chkData.includes(chk.value)){
    chk.setAttribute('checked',true);
  }
  else{
    chk.checked = false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
    <label class="checkbox-inline"><input type="checkbox" id="chk21" name="user_plant1" value="2100">2100</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk22" name="user_plant1" value="2200">2200</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk23" name="user_plant1" value="2300">2300</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk24" name="user_plant1" value="2400">2400</label>
</div></code>```

Body:
I have a form and it has 4 checkboxes. I am getting a response from the server and according to that response I need to checked that particular checkbox/s.

For example I have four checkboxes called 2100,2200,2300,2400

Then I am getting a array response from the server and array has 2200 and 2400.
Then I need to checked both 2200 and 2400 checkboxes.

$.ajax({
    type: "POST",
    url: "send_db.php",
    data: {'send_array':array_send},
    success:  function(data){

    var jsonRes  = jQuery.parseJSON(data);
    var plant  = jsonRes.plant;
    var array_length = jsonRes.plant.length;

    for (var i = 0; i < array_length; i++) {

        document.getElementsByName("user_plant1").checked = true;

    }

    }
});

Here plant has the values.

These are my checkboxes...

    <input type="checkbox" id="chk21" name="user_plant1" value="2100">2100
    <input type="checkbox" id="chk22" name="user_plant1" value="2200">2200
    <input type="checkbox" id="chk23" name="user_plant1" value="2300">2300
    <input type="checkbox" id="chk24" name="user_plant1" value="2400">2400

Body:
Try the following way:

var chkData = "2200,2400";
chkData = chkData.split(',');

var el=document.querySelectorAll('input[name=user_plant1]');
el.forEach(function(chk){
  if(chkData.includes(chk.value)){
    chk.setAttribute('checked',true);
  }
  else{
    chk.checked = false;
  }
});

<div class="form-group">
    <label class="checkbox-inline"><input type="checkbox" id="chk21" name="user_plant1" value="2100">2100</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk22" name="user_plant1" value="2200">2200</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk23" name="user_plant1" value="2300">2300</label>
    <label class="checkbox-inline"><input type="checkbox" id="chk24" name="user_plant1" value="2400">2400</label>
</div>


问:
How to remove title bar in android?
I want to do android program that contains no title bar. For some reason I cant remove title bar.
I have already tried this coding.

```<code>this.requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

This one also I have tried but the program suddenly stops..

```<code> android:icon="@drawable/icon"
 android:label="@string/app_name"
 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
</code>```

How can I fix this?

答:
In the styles.xml file (App/src/main/res/values/styles.xml), make changes to the  to look like this:

If you find this:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</code>```

Change it to

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

Title: How to remove title bar in android?

Body:
I want to do android program that contains no title bar. For some reason I cant remove title bar.
I have already tried this coding.

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

This one also I have tried but the program suddenly stops..

 android:icon="@drawable/icon"
 android:label="@string/app_name"
 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

How can I fix this?

Body:
In the styles.xml file (App/src/main/res/values/styles.xml), make changes to the  to look like this:

If you find this:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Change it to

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">


问:
How to be warned a many-to-many relation gonna be update?
I want to do a specific treatment when a specific field is updated.

The obvious way is to do it with event preUpdate, and see what fields are updated. It works fine ... except for a many-to-many field. It triggers the event, but the ChangeSet is empty.

```<code>/**
 * @ORM\PreUpdate
*/
public function updateDate(PreUpdateEventArgs $event){
    $changeSet = $event->getEntityChangeSet();
    $res = "";
    foreach($changeSet as $key => $change){
        $line = $key." : ".$event->getOldValue($key)." || ".$event->getNewValue($key);
        $res .= $line;
    }
}
</code>```

In $res all my fields are modified except for the many-to-many field.

Also, I'm trying to do it in a listener, but I can't find how to extract the fields which are updated from the entityManager.

Thank you.

More informations :

Relation from the update entity :

```<code>/**
* @var Status
*
* @ORM\ManyToMany(targetEntity="User", inversedBy="projectsSupervisor", cascade={"persist"})
* @ORM\JoinTable(name="projects_supervisors")
*/
protected $supervisors;
</code>```

From the other side :

```<code>/**
* @var Project
*
* @ORM\ManyToMany(targetEntity="Task", mappedBy="users")
*/
protected *tasks
</code>```

Symfony version : 3.1.10

答:
It is not possible to track changes made to an many-to-many-association. See here :

Changes made only to the inverse side of an association are ignored.
  Make sure to update both sides of a bidirectional association (or at
  least the owning side, from Doctrine’s point of view)

Additionally, ::getEntityChangeSet() is only useful for regular fields, not associations. For One-To-Many-Associations, you can use $unitOfWork->getScheduledCollectionUpdates() :

```<code>foreach ($uow->getScheduledCollectionUpdates() as $collectionUpdate) {
    /** @var $collectionUpdate \Doctrine\ORM\PersistentCollection */
    if ($collectionUpdate->getOwner() === $entity) {
        // This entity has an association mapping which contains updates.
        $collectionMapping = $collectionUpdate->getMapping();
        print_r($collectionMapping); // Investigate this further
    }
}
</code>```

A practical example is viewable in my github repository "DoctrineWatcher" which does exactly the same (line 196+).

Body:
I want to do a specific treatment when a specific field is updated.

The obvious way is to do it with event preUpdate, and see what fields are updated. It works fine ... except for a many-to-many field. It triggers the event, but the ChangeSet is empty.

/**
 * @ORM\PreUpdate
*/
public function updateDate(PreUpdateEventArgs $event){
    $changeSet = $event->getEntityChangeSet();
    $res = "";
    foreach($changeSet as $key => $change){
        $line = $key." : ".$event->getOldValue($key)." || ".$event->getNewValue($key);
        $res .= $line;
    }
}

In $res all my fields are modified except for the many-to-many field.

Also, I'm trying to do it in a listener, but I can't find how to extract the fields which are updated from the entityManager.

Thank you.

More informations :

Relation from the update entity :

/**
* @var Status
*
* @ORM\ManyToMany(targetEntity="User", inversedBy="projectsSupervisor", cascade={"persist"})
* @ORM\JoinTable(name="projects_supervisors")
*/
protected $supervisors;

From the other side :

/**
* @var Project
*
* @ORM\ManyToMany(targetEntity="Task", mappedBy="users")
*/
protected *tasks

Symfony version : 3.1.10

Body:
It is not possible to track changes made to an many-to-many-association. See here :

Changes made only to the inverse side of an association are ignored.
  Make sure to update both sides of a bidirectional association (or at
  least the owning side, from Doctrine’s point of view)

Additionally, ::getEntityChangeSet() is only useful for regular fields, not associations. For One-To-Many-Associations, you can use $unitOfWork->getScheduledCollectionUpdates() :

foreach ($uow->getScheduledCollectionUpdates() as $collectionUpdate) {
    /** @var $collectionUpdate \Doctrine\ORM\PersistentCollection */
    if ($collectionUpdate->getOwner() === $entity) {
        // This entity has an association mapping which contains updates.
        $collectionMapping = $collectionUpdate->getMapping();
        print_r($collectionMapping); // Investigate this further
    }
}

A practical example is viewable in my github repository "DoctrineWatcher" which does exactly the same (line 196+).


问:
TextField takes unicode in Django
I am trying to save a string contains characters whose ordinal is not in range(128) into database. The field is declared as TextField in model and when I called the save() method, an exception was thrown:

```<code>File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 434, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 500, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 491, in _update return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 861, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 717, in execute_sql sql, params = self.as_sql()
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 826, in as_sql val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 276, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 53, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 652, in get_db_prep_value value = self.get_prep_value(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 647, in get_prep_value return self.to_python(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 610, in to_python if not ansi_date_re.search(value):
TypeError: expected string or buffer
</code>```

Here is what I did:

```<code>str_unicode = str.encode('utf-8')
m = MyModel.new(str = str_unicode)
m.save()
</code>```

So what should I do to enable the unicode compatibility?

Updated: I am currently using sqlite3 for development, python 2.6.1 and Django 1.2.4 on Mac

答:
Your problem is not with the TextField at all. If you look at the code referenced in the traceback, you're triggering an exception from within DateField's to_python method. You can see the relevant code here. Basically it looks like you're passing something inappropriate as the input to another field on your model.

Lesson to be learned: ALWAYS READ THE TRACEBACK CAREFULLY!

As a side note, if you really want to coerce something to unicode in Python call the builtin unicode type:

```<code>str_unicode = unicode(str)
</code>```

Using the encode method to convert to UTF-8 does something completely different.

Title: TextField takes unicode in Django

Body:
I am trying to save a string contains characters whose ordinal is not in range(128) into database. The field is declared as TextField in model and when I called the save() method, an exception was thrown:

File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 434, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 500, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 491, in _update return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 861, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 717, in execute_sql sql, params = self.as_sql()
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 826, in as_sql val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 276, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 53, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 652, in get_db_prep_value value = self.get_prep_value(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 647, in get_prep_value return self.to_python(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 610, in to_python if not ansi_date_re.search(value):
TypeError: expected string or buffer

Here is what I did:

str_unicode = str.encode('utf-8')
m = MyModel.new(str = str_unicode)
m.save()

So what should I do to enable the unicode compatibility?

Updated: I am currently using sqlite3 for development, python 2.6.1 and Django 1.2.4 on Mac

Body:
Your problem is not with the TextField at all. If you look at the code referenced in the traceback, you're triggering an exception from within DateField's to_python method. You can see the relevant code here. Basically it looks like you're passing something inappropriate as the input to another field on your model.

Lesson to be learned: ALWAYS READ THE TRACEBACK CAREFULLY!

As a side note, if you really want to coerce something to unicode in Python call the builtin unicode type:

str_unicode = unicode(str)

Using the encode method to convert to UTF-8 does something completely different.


问:
Ruby - XML to Hash and then Hash to XML, both XMLs are not same
I have an XML like:

```<code><response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
  <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
    <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
  </msg:trb>
</response>
</code>```

I'm supposed to read the XML in ruby and show it in a much readable HASH format in the UI(inside a textarea), where user can edit the values inside the HASH.

Then I'm supposed to form back the XML from the hash.

But, the initial and final XMLs differ

Code

XML > HASH

```<code>h = Hash.from_xml('
  <response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
    <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
      <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
    </msg:trb>
  </response>
')
</code>```

OUTPUT

```<code>#{
#  "response" => {
#    "xmlns:msg"=>"http://schemas.xyzlabs.net/2010/messaging/",
#    "xmlns:ld"=>"http://schemas.xyzlabs.net/2010/lab-data/",
#    "trb" => {
#      "proRefId" => "12345",
#      "tesComNa" => "Xyz Laboratories,Inc.",
#      "sample" => {
#        "ttz" => "020206b01",
#        "id" => "1898-57",
#        "name" => "Adam, Franklin"
#      }
#    }
#  }
#}
</code>```

Say user modifies the above and I'm trying to convert the modified HASH to XML again:

HASH > XML

```<code>h["response"].to_xml(root: "response")
</code>```

OUTPUT

```<code><?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
  <xmlns:msg>
    http://schemas.xyzlabs.net/2010/messaging/
  </xmlns:msg>
  <xmlns:ld>
    http://schemas.xyzlabs.net/2010/lab-data/undefined
  </undefinedxmlns:ld>
    undefined
  <trb>
    <proRefId>12345</proRefId>
    <tesComNa>Xyz Laboratories,Inc.</tesComNa>
    <sample>
      <ttz>020206b01</ttz>
      <id>1898-57</id>
      <name>Adam, Franklin</name>
  </sample>
    undefined
    </trb>
  undefined
</response>
</code>```

I see lots of undefined and the attributes of any node is converted to node itself.

How can I achieve the original XML back with only it's respective value modified(as done by user)?

答:
I think this might be related to your environment. I have tested your code with Rails console (Rails 5.1.4) and it works as expected:</p>

```<code>[1] pry(main)> h = Hash.from_xml('
[1] pry(main)*   <response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
[1] pry(main)*     <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
[1] pry(main)*       <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
[1] pry(main)*     </msg:trb>
[1] pry(main)*   </response>
[1] pry(main)* ')
=> {"response"=>
  {"xmlns:msg"=>"http://schemas.xyzlabs.net/2010/messaging/",
   "xmlns:ld"=>"http://schemas.xyzlabs.net/2010/lab-data/",
   "trb"=>
    {"proRefId"=>"12345",
     "tesComNa"=>"Xyz Laboratories,Inc.",
     "sample"=>{"ttz"=>"020206b01", "id"=>"1898-57", "name"=>"Adam, Franklin"}}}}

[2] pry(main)> h['response']['trb']['tesComNa'] = 'StackOverflow'
=> "StackOverflow"

[3] pry(main)> puts h["response"].to_xml(root: "response")
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <xmlns:msg>http://schemas.xyzlabs.net/2010/messaging/</xmlns:msg>
  <xmlns:ld>http://schemas.xyzlabs.net/2010/lab-data/</xmlns:ld>
  <trb>
    <proRefId>12345</proRefId>
    <tesComNa>StackOverflow</tesComNa>
    <sample>
      <ttz>020206b01</ttz>
      <id>1898-57</id>
      <name>Adam, Franklin</name>
    </sample>
  </trb>
</response>
</code>```

Body:
I have an XML like:

<response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
  <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
    <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
  </msg:trb>
</response>

I'm supposed to read the XML in ruby and show it in a much readable HASH format in the UI(inside a textarea), where user can edit the values inside the HASH.

Then I'm supposed to form back the XML from the hash.

But, the initial and final XMLs differ

Code

XML > HASH

h = Hash.from_xml('
  <response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
    <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
      <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
    </msg:trb>
  </response>
')

OUTPUT

#{
#  "response" => {
#    "xmlns:msg"=>"http://schemas.xyzlabs.net/2010/messaging/",
#    "xmlns:ld"=>"http://schemas.xyzlabs.net/2010/lab-data/",
#    "trb" => {
#      "proRefId" => "12345",
#      "tesComNa" => "Xyz Laboratories,Inc.",
#      "sample" => {
#        "ttz" => "020206b01",
#        "id" => "1898-57",
#        "name" => "Adam, Franklin"
#      }
#    }
#  }
#}

Say user modifies the above and I'm trying to convert the modified HASH to XML again:

HASH > XML

h["response"].to_xml(root: "response")

OUTPUT

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
  <xmlns:msg>
    http://schemas.xyzlabs.net/2010/messaging/
  </xmlns:msg>
  <xmlns:ld>
    http://schemas.xyzlabs.net/2010/lab-data/undefined
  </undefinedxmlns:ld>
    undefined
  <trb>
    <proRefId>12345</proRefId>
    <tesComNa>Xyz Laboratories,Inc.</tesComNa>
    <sample>
      <ttz>020206b01</ttz>
      <id>1898-57</id>
      <name>Adam, Franklin</name>
  </sample>
    undefined
    </trb>
  undefined
</response>

I see lots of undefined and the attributes of any node is converted to node itself.

How can I achieve the original XML back with only it's respective value modified(as done by user)?

Body:
I think this might be related to your environment. I have tested your code with Rails console (Rails 5.1.4) and it works as expected:

[1] pry(main)> h = Hash.from_xml('
[1] pry(main)*   <response xmlns:msg="http://schemas.xyzlabs.net/2010/messaging/" xmlns:ld="http://schemas.xyzlabs.net/2010/lab-data/">
[1] pry(main)*     <msg:trb proRefId="12345" tesComNa="Xyz Laboratories,Inc.">
[1] pry(main)*       <sample ttz="020206b01" id="1898-57" name="Adam, Franklin" />
[1] pry(main)*     </msg:trb>
[1] pry(main)*   </response>
[1] pry(main)* ')
=> {"response"=>
  {"xmlns:msg"=>"http://schemas.xyzlabs.net/2010/messaging/",
   "xmlns:ld"=>"http://schemas.xyzlabs.net/2010/lab-data/",
   "trb"=>
    {"proRefId"=>"12345",
     "tesComNa"=>"Xyz Laboratories,Inc.",
     "sample"=>{"ttz"=>"020206b01", "id"=>"1898-57", "name"=>"Adam, Franklin"}}}}

[2] pry(main)> h['response']['trb']['tesComNa'] = 'StackOverflow'
=> "StackOverflow"

[3] pry(main)> puts h["response"].to_xml(root: "response")
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <xmlns:msg>http://schemas.xyzlabs.net/2010/messaging/</xmlns:msg>
  <xmlns:ld>http://schemas.xyzlabs.net/2010/lab-data/</xmlns:ld>
  <trb>
    <proRefId>12345</proRefId>
    <tesComNa>StackOverflow</tesComNa>
    <sample>
      <ttz>020206b01</ttz>
      <id>1898-57</id>
      <name>Adam, Franklin</name>
    </sample>
  </trb>
</response>


问:
setting up an NSMutableDictionary
In my app delegate I look for a plist to import and turn it into an NSMutableDictionary.

```<code>NSLog(@"Reading session file from main bundle");
    NSString *plistPath = [Utilities localPathForFileName:kSessionFile];
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    temp = (NSMutableDictionary *)[NSPropertyListSerialization
                            propertyListFromData:plistXML
                            mutabilityOption:NSPropertyListMutableContainersAndLeaves
                            format:&format
                            errorDescription:&errorDesc];
</code>```

My NSMutableDictionary is then saved into a singleton for access throughout the app

```<code>[[self model] setStorage:temp];
</code>```

That all works fine and allows me to add objects to the dictionary at will because of the mutabilityOption. I also write it out to a plist. Second time the app opens it finds the saved plist and reads from there.

My question is, how can I initially create the NSMutableDictionary with the same mutabilityOptions WITHOUT reading it in from a pList? If I could do that, then I could also erase the data in the dictionary at will. Thanks in advance for your help.

答:
Surely all you need to do is this:</p>

```<code> [[self model] setStorage:[NSMutableDictionary dictionary]];
</code>```

Title: setting up an NSMutableDictionary

Body:
In my app delegate I look for a plist to import and turn it into an NSMutableDictionary.

NSLog(@"Reading session file from main bundle");
    NSString *plistPath = [Utilities localPathForFileName:kSessionFile];
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    temp = (NSMutableDictionary *)[NSPropertyListSerialization
                            propertyListFromData:plistXML
                            mutabilityOption:NSPropertyListMutableContainersAndLeaves
                            format:&format
                            errorDescription:&errorDesc];

My NSMutableDictionary is then saved into a singleton for access throughout the app

[[self model] setStorage:temp];

That all works fine and allows me to add objects to the dictionary at will because of the mutabilityOption. I also write it out to a plist. Second time the app opens it finds the saved plist and reads from there.

My question is, how can I initially create the NSMutableDictionary with the same mutabilityOptions WITHOUT reading it in from a pList? If I could do that, then I could also erase the data in the dictionary at will. Thanks in advance for your help.

Body:
Surely all you need to do is this:

 [[self model] setStorage:[NSMutableDictionary dictionary]];


问:
How to get part of filename into a variable?
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

```<code>name.surname.csv
</code>```

How can I write a function that populates two variables with the components of the file name?

```<code>A = name
B = surname
</code>```

答:
Try this, the name is split by . and stored in A and B

```<code>a="name.surname.csv"
A,B,C=a.split('.')
</code>```

Of course, this assumes that your file name is in the form first.second.csv

Body:
I have a lot of .csv files and I'd like to parse the file names.

The file names are in this format:

name.surname.csv

How can I write a function that populates two variables with the components of the file name?

A = name
B = surname

Body:
Try this, the name is split by . and stored in A and B

a="name.surname.csv"
A,B,C=a.split('.')

Of course, this assumes that your file name is in the form first.second.csv


答:
If the file names always have the exact same form, with exactly two periods, then you can do:</p>

```<code>>>> name, surname, ext = "john.doe.csv".split(".")
>>> name
'john'
>>> surname
'doe'
>>> ext
'csv'
>>>
</code>```

Title: How to get part of filename into a variable?

Body:
If the file names always have the exact same form, with exactly two periods, then you can do:

>>> name, surname, ext = "john.doe.csv".split(".")
>>> name
'john'
>>> surname
'doe'
>>> ext
'csv'
>>>


问:
Intent from onHandleIntent
I have the code

```<code> public class intentService extends IntentService {

        @Override
            protected void onHandleIntent(Intent intent) {

        RequestQueue queue = MyVolley.getRequestQueue(this);
                    queue = MyVolley.getRequestQueue(this);
                    GsonRequest<Transport> gsonRequest = new GsonRequest<Transport>(
                            url_transports, Transport.class, null, createMyReqSuccessListenerTransport(),
                            createMyReqErrorListenerTransport());

         Intent updateIntent = new Intent();
                    updateIntent.setAction(ACTION_UPDATE);
                    updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                    updateIntent.putExtra(EXTRA_KEY_UPDATE, 50);
</code>```

this.sendBroadcast(updateIntent);

// work

The Intent is working sending update value

```<code> private Response.Listener<Transport> createMyReqSuccessListenerTransport() {
        return new Response.Listener<Transport>() {
            @Override
            public void onResponse(Transport response) {

                    // send beetwean data
                    Intent updateIntent = new Intent();
                    updateIntent.setAction(ACTION_UPDATE);
                    updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                    updateIntent.putExtra(EXTRA_KEY_UPDATE, (i * 100) / size);
</code>```

```<code>                    **sendBroadcast(updateIntent); // dosn`t work**
</code>```

```<code>                }
</code>```

dosn`t work

答:
I decided the progblemm ny myself

I have to call the intent from handle

```<code> handler.post(new Runnable() {
                        @Override
                        public void run() {
                            // send beetwean data
                            Intent updateIntent = new Intent();
                            updateIntent.setAction(ACTION_UPDATE);
                            updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            updateIntent.putExtra(EXTRA_KEY_UPDATE, (finalI  * 100) / size );
                            sendBroadcast(updateIntent);
                        }
                    });
</code>```

Title: Intent from onHandleIntent

Body:
I have the code

 public class intentService extends IntentService {

        @Override
            protected void onHandleIntent(Intent intent) {

        RequestQueue queue = MyVolley.getRequestQueue(this);
                    queue = MyVolley.getRequestQueue(this);
                    GsonRequest<Transport> gsonRequest = new GsonRequest<Transport>(
                            url_transports, Transport.class, null, createMyReqSuccessListenerTransport(),
                            createMyReqErrorListenerTransport());

         Intent updateIntent = new Intent();
                    updateIntent.setAction(ACTION_UPDATE);
                    updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                    updateIntent.putExtra(EXTRA_KEY_UPDATE, 50);

this.sendBroadcast(updateIntent);

// work

The Intent is working sending update value

 private Response.Listener<Transport> createMyReqSuccessListenerTransport() {
        return new Response.Listener<Transport>() {
            @Override
            public void onResponse(Transport response) {

                    // send beetwean data
                    Intent updateIntent = new Intent();
                    updateIntent.setAction(ACTION_UPDATE);
                    updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                    updateIntent.putExtra(EXTRA_KEY_UPDATE, (i * 100) / size);

                    **sendBroadcast(updateIntent); // dosn`t work**

                }

dosn`t work

Body:
I decided the progblemm ny myself

I have to call the intent from handle

 handler.post(new Runnable() {
                        @Override
                        public void run() {
                            // send beetwean data
                            Intent updateIntent = new Intent();
                            updateIntent.setAction(ACTION_UPDATE);
                            updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            updateIntent.putExtra(EXTRA_KEY_UPDATE, (finalI  * 100) / size );
                            sendBroadcast(updateIntent);
                        }
                    });


问:
Javascript table's pagination

I'm trying to put pagination function into my table and taking this post "Simple pagination in javascript" for reference.

https://codepen.io/duongvu/pen/eewdPG?editors=1111

It's supposed to input the data from my array into the table's class. However it doesn't work in my case.

It freezes and can not proceed when clicking on <next>

答:
Try this out @Duong Vu</p>

```<code>for (var i = 0; i < records_per_page; i++)
 {
    col[i].innerText = content[i + (page-1) * records_per_page].number;
 }
</code>```

Title: Javascript table's pagination

Body:
Try this out @Duong Vu

for (var i = 0; i < records_per_page; i++)
 {
    col[i].innerText = content[i + (page-1) * records_per_page].number;
 }


问:
How to write selenium code for autocomplete text box withe list selection
I'm trying to write Selenium code for below HTML source code..

This field is the auto populated field for input selection

```<code><input id="ctl00_ContentPlaceHolder1_txtBranch" class="textbox_service ui-autocomplete-input" name="ctl00$ContentPlaceHolder1$txtBranch" style="width: 200px;" onblur="return branch();" onchange="return CheckBranchName();" tabindex="6" autocomplete="off" type="text"/>
</code>```

Any one can help me out to write the code?

Web element screen shot attached.
Thanks in advance.

答:
As per the HTML to click(select) the Auto Complete text, you can use the following line of code :

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='textbox_service ui-autocomplete-input' and contains(@id,'_ContentPlaceHolder') and contains(@name,'txtBranch')]"))).click();
</code>```

Body:
I'm trying to write Selenium code for below HTML source code..

This field is the auto populated field for input selection

<input id="ctl00_ContentPlaceHolder1_txtBranch" class="textbox_service ui-autocomplete-input" name="ctl00$ContentPlaceHolder1$txtBranch" style="width: 200px;" onblur="return branch();" onchange="return CheckBranchName();" tabindex="6" autocomplete="off" type="text"/>

Any one can help me out to write the code?

Web element screen shot attached.
Thanks in advance.

Body:
As per the HTML to click(select) the Auto Complete text, you can use the following line of code :

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='textbox_service ui-autocomplete-input' and contains(@id,'_ContentPlaceHolder') and contains(@name,'txtBranch')]"))).click();


问:
Get elements to align
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

```<code>var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});
</code>```

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
      <div class="board">
        <p>1st Event</p>
        <p>2nd Event</p>
        <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st News</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st Gallery</p>
        <p>2nd Gallery</p>
        <p>3rd Gallery</p>
      </div>
  </div>
</div></code>```

NEED ANSWER TO WORK IN IE9+ aswell

答:
I like @Hash 's answer more but here's a non-flexbox version just in case.

Downside is it requires extra wrapper div for each board

.board{
  display: table-cell;
  vertical-align:bottom;
  background: gray;
  width: 30%;
  margin-top:auto;

}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

.wrap{
  margin-left: 5px;
  display:inline-block;
  background:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
      <div class="board">
        <div class="wrap">
          <p>1st Event</p>
          <p>2nd Event</p>
          <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
          </div>
      </div>
      <div class="board">
        <div class="wrap">
          (This should align at bottom)
          <p>1st News</p>
        </div>
      </div>
      <div class="board">
       <div class="wrap">
          (This should align at bottom)
          <p>1st Gallery</p>
          <p>2nd Gallery</p>
          <p>3rd Gallery</p>
        </div>
      </div>
  </div>
</div></code>```

Title: Get elements to align

Body:
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

1st Event

2nd Event

3rd Event 3rd Event 3rd Event 3rd Event 3rd Event

        (This should align at bottom)

1st News

        (This should align at bottom)

1st Gallery

2nd Gallery

3rd Gallery

NEED ANSWER TO WORK IN IE9+ aswell

Body:
I like @Hash 's answer more but here's a non-flexbox version just in case.

Downside is it requires extra wrapper div for each board

.board{
  display: table-cell;
  vertical-align:bottom;
  background: gray;
  width: 30%;
  margin-top:auto;

}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

.wrap{
  margin-left: 5px;
  display:inline-block;
  background:red;
}

<div id="boards-container">
  <div class="boards">
      <div class="board">
        <div class="wrap">
          <p>1st Event</p>
          <p>2nd Event</p>
          <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
          </div>
      </div>
      <div class="board">
        <div class="wrap">
          (This should align at bottom)
          <p>1st News</p>
        </div>
      </div>
      <div class="board">
       <div class="wrap">
          (This should align at bottom)
          <p>1st Gallery</p>
          <p>2nd Gallery</p>
          <p>3rd Gallery</p>
        </div>
      </div>
  </div>
</div>


问:
How to create Entity Class for multiple table joins
I am developing a spring boot application, i need a proper design help for one of my entity relation.

These are my tables

```<code>DROP TABLE IF EXISTS user;
CREATE TABLE user
(
 User_ID   INT AUTO_INCREMENT PRIMARY KEY,
 Email     VARCHAR(1024),
 Phone     BIGINT,
 Password  VARCHAR(128),
 User_Type ENUM ('TEACHER', 'PARENT'),
 Status    ENUM ('ACTIVE', 'DEACTIVE', 'SUSPENDED')
 );

DROP TABLE IF EXISTS teacher;
CREATE TABLE teacher
(
   Teacher_ID      INT AUTO_INCREMENT PRIMARY KEY,
   Name            VARCHAR(1024),
   Email           VARCHAR(1024),
   Phone           BIGINT,
   Gender          ENUM (0, 1),
   Date_Of_Joining INT,
   Designation     VARCHAR(1024),
   Is_Active       INT
);

DROP TABLE IF EXISTS parent;
CREATE TABLE parent
(
  Parent_ID  INT AUTO_INCREMENT PRIMARY KEY,
  Name       VARCHAR(1024),
  Email      VARCHAR(1024),
  Phone      BIGINT,
  Occupation VARCHAR(1024),
  Address    VARCHAR(4048)
);

DROP TABLE IF EXISTS student;
CREATE TABLE student
(
  Student_ID    INT AUTO_INCREMENT PRIMARY KEY,
  Student_Name  VARCHAR(1024),
  Class         VARCHAR(16),
  Section       VARCHAR(16),
  Academic_Year VARCHAR(64),
  DOB           DATE,
  Gender        ENUM (0, 1),
  Parent_ID     INT
);
</code>```

Can anyone please help me creating entity classes for the same. Based on the type of user in user table i need to join with either teacher or parent table. For example if User_Type is TEACHER then i will join with teacher table else i will join user with parent table. Join condition would be email.

Student table has one to one relationship with parent table.

答:
You can use the following classes:

User:

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Inheritance(strategy= InheritanceType.JOINED)
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Column(name = "User_ID")
private Integer userID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Password", length = 128)
private String password;

@Column(name = "User_Type", columnDefinition = "enum ('TEACHER', 'PARENT')")
private String userType;

@Column(name = "Status", columnDefinition = "enum ('ACTIVE', 'DEACTIVE', 'SUSPENDED')")
private String status;
}
</code>```

Teacher:

```<code>@Entity
@Table(name = "teacher")
public class Teacher extends User{
@Id
@GeneratedValue
@Column(name = "teacher_ID")
private Integer teacherID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Gender", columnDefinition = "BOOLEAN")
private Boolean gender;

@Column(name = "Date_Of_Joining")
private Integer dateOfJoining;

@Column(name = "Designation", length = 1024)
private String designation;

@Column(name = "Is_Active")
private Integer isActive;
}
</code>```

Parent:

```<code>@Entity
@Table(name = "parent")
public class Parent extends User{
@Id
@GeneratedValue
@Column(name = "Parent_ID")
private Integer parentID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Occupation", length = 1024)
private String occupation;

@Column(name = "Address",length=4048)
private String address;
}
</code>```

Student:

```<code>@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue
@Column(name = "Student_ID")
private Integer studentID;

@Column(name = "student_name", length = 1024)
private String studentName;

@Column(name = "study_class", length = 16)
private String studyClass;

@Column(name = "section", length = 16)
private String section;

@Column(name = "academic_year",length = 64)
private String academicYear;

@Temporal(TemporalType.DATE)
@Column(name = "dob", length = 4048)
private Date dob;

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn(name = "parent")
public Parent parent;
}
</code>```

Try them out and see if that helps.

ContentLicense: CC BY-SA 4.0

Body:
I am developing a spring boot application, i need a proper design help for one of my entity relation.

These are my tables

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
 User_ID   INT AUTO_INCREMENT PRIMARY KEY,
 Email     VARCHAR(1024),
 Phone     BIGINT,
 Password  VARCHAR(128),
 User_Type ENUM ('TEACHER', 'PARENT'),
 Status    ENUM ('ACTIVE', 'DEACTIVE', 'SUSPENDED')
 );

DROP TABLE IF EXISTS teacher;
CREATE TABLE teacher
(
   Teacher_ID      INT AUTO_INCREMENT PRIMARY KEY,
   Name            VARCHAR(1024),
   Email           VARCHAR(1024),
   Phone           BIGINT,
   Gender          ENUM (0, 1),
   Date_Of_Joining INT,
   Designation     VARCHAR(1024),
   Is_Active       INT
);

DROP TABLE IF EXISTS parent;
CREATE TABLE parent
(
  Parent_ID  INT AUTO_INCREMENT PRIMARY KEY,
  Name       VARCHAR(1024),
  Email      VARCHAR(1024),
  Phone      BIGINT,
  Occupation VARCHAR(1024),
  Address    VARCHAR(4048)
);

DROP TABLE IF EXISTS student;
CREATE TABLE student
(
  Student_ID    INT AUTO_INCREMENT PRIMARY KEY,
  Student_Name  VARCHAR(1024),
  Class         VARCHAR(16),
  Section       VARCHAR(16),
  Academic_Year VARCHAR(64),
  DOB           DATE,
  Gender        ENUM (0, 1),
  Parent_ID     INT
);

Can anyone please help me creating entity classes for the same. Based on the type of user in user table i need to join with either teacher or parent table. For example if User_Type is TEACHER then i will join with teacher table else i will join user with parent table. Join condition would be email.

Student table has one to one relationship with parent table.

Body:
You can use the following classes:

User:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Inheritance(strategy= InheritanceType.JOINED)
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Column(name = "User_ID")
private Integer userID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Password", length = 128)
private String password;

@Column(name = "User_Type", columnDefinition = "enum ('TEACHER', 'PARENT')")
private String userType;

@Column(name = "Status", columnDefinition = "enum ('ACTIVE', 'DEACTIVE', 'SUSPENDED')")
private String status;
}

Teacher:

@Entity
@Table(name = "teacher")
public class Teacher extends User{
@Id
@GeneratedValue
@Column(name = "teacher_ID")
private Integer teacherID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Gender", columnDefinition = "BOOLEAN")
private Boolean gender;

@Column(name = "Date_Of_Joining")
private Integer dateOfJoining;

@Column(name = "Designation", length = 1024)
private String designation;

@Column(name = "Is_Active")
private Integer isActive;
}

Parent:

@Entity
@Table(name = "parent")
public class Parent extends User{
@Id
@GeneratedValue
@Column(name = "Parent_ID")
private Integer parentID;

@Column(name = "name", length = 1024)
private String name;

@Column(name = "email", length = 1024)
private String email;

@Column(name = "Phone")
private Long phone;

@Column(name = "Occupation", length = 1024)
private String occupation;

@Column(name = "Address",length=4048)
private String address;
}

Student:

@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue
@Column(name = "Student_ID")
private Integer studentID;

@Column(name = "student_name", length = 1024)
private String studentName;

@Column(name = "study_class", length = 16)
private String studyClass;

@Column(name = "section", length = 16)
private String section;

@Column(name = "academic_year",length = 64)
private String academicYear;

@Temporal(TemporalType.DATE)
@Column(name = "dob", length = 4048)
private Date dob;

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn(name = "parent")
public Parent parent;
}

Try them out and see if that helps.


答:
Use str.split and unpack the result in A, B and another "anonymous" variable to store (and ignore) the extension.

```<code>filename = 'name.surname.csv'
A, B, _ = filename.split('.')
</code>```

Body:
Use str.split and unpack the result in A, B and another "anonymous" variable to store (and ignore) the extension.

filename = 'name.surname.csv'
A, B, _ = filename.split('.')


答:
colons - this is a shorthand version of statements, you should not really learn them at such an early stage. First you need to learn the full versions.

<?= $variable ?> is a short version of <?php echo $variable ?> but means exactly the same.

Also, the shordhand versions from question one are actually not considered a good practice, because when you nest them they are hard to read.

Title: I do not understand this PHP Code, what is it doing?

Body:
How to read php

i'm learning php, I wrote this.  (It is from a book)

   <?php if(!empty($data)):  ?>

             <?php foreach ($data as $dataprint): ?>

<?= $dataprint ?>

             <?php endforeach ?>

I am unable to understand some of the code in this section.

 1. Why are there colons on line 1 and 3?

 2. What does the '<?= $dataprint ?> ) and why does it not have the standard 'PHP' word?

 3. why is there an equal mark in the next?


问:
Get value from json with non unique key in php
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

```<code><?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>
</code>```

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

答:
You can get the key value using key($location).

When key($location) returns 'non_unique_name', you can use

```<code>$location[key($location)]['val1'];
</code>```

to get true (value of val1 in JSON).

Body:
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

<?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

Body:
You can get the key value using key($location).

When key($location) returns 'non_unique_name', you can use

$location[key($location)]['val1'];

to get true (value of val1 in JSON).


问:
What's the best way to select multiple M:N relationships in SQL?
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

```<code>books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)
</code>```

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

答:
I think you probably want to do it as two queries, one for authors and one for subjects, however you could combine these into a single result using a UNION if you wanted.

```<code>SELECT books.book_id, books.book_title,
      'author' as record_type, authors.author_name as record_value
LEFT JOIN book_authors ON books.book_id = book_authors.book_id
LEFT JOIN authors ON authors.item_id = book_authors.author_id
UNION
SELECT books.book_id, books.book_title,
       'subject' as record_type, subjects.subject_name as record_value
LEFT JOIN book_subjects ON books.book_id = book_subjects.book_id
LEFT JOIN subjects ON subjects.subject_id = book_subjects.subject_id;
</code>```

I'm not sure that it really saves anything other than a round-trip to the database.  I offer it only for the potential contribution to your knowledge not in hopes that it is helpful to your immediate problem.

OwnerDisplayName: Ben Blank

Body:
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

LastEditorDisplayName: Ben Blank

Body:
I think you probably want to do it as two queries, one for authors and one for subjects, however you could combine these into a single result using a UNION if you wanted.

SELECT books.book_id, books.book_title,
      'author' as record_type, authors.author_name as record_value
LEFT JOIN book_authors ON books.book_id = book_authors.book_id
LEFT JOIN authors ON authors.item_id = book_authors.author_id
UNION
SELECT books.book_id, books.book_title,
       'subject' as record_type, subjects.subject_name as record_value
LEFT JOIN book_subjects ON books.book_id = book_subjects.book_id
LEFT JOIN subjects ON subjects.subject_id = book_subjects.subject_id;

I'm not sure that it really saves anything other than a round-trip to the database.  I offer it only for the potential contribution to your knowledge not in hopes that it is helpful to your immediate problem.

OwnerDisplayName: tvanfosson


问:
CUDA: embedded for loop kernel
I have some code that I want to make into a cuda kernel. Behold:

```<code>    for (r = Y; r < Y + H; r+=2)
    {
        ch1RowSum = ch2RowSum = ch3RowSum = 0;
        for (c = X; c < X + W; c+=2)
        {
            chan1Value = //some calc'd value
                            chan3Value = //some calc'd value
            chan2Value = //some calc'd value
            ch2RowSum  += chan2Value;
            ch3RowSum  += chan3Value;
            ch1RowSum  += chan1Value;
        }
        ch1Mean += ch1RowSum / W;
        ch2Mean += ch2RowSum / W;
        ch3Mean += ch3RowSum / W;
    }
</code>```

Should this be split up into two kernels, one to calculate the RowSums and one to calculate the Means, and how should I handle the fact that my loop indices dont start at zero and end at N?

答:
Let's suppose you have a kernel that computes the three values. Each thread in your configuration will compute the three values for each (r,c) pair.

```<code>__global__ value_kernel(Y, H, X, W)
{
    r = blockIdx.x + Y;
    c = threadIdx.x + W;

    chan1value = ...
    chan2value = ...
    chan3value = ...
}
</code>```

I don't believe you can calculate the sum (completely in parallel, at least) in the above kernel. You won't be able to use += like you have above. You could put it all in one kernel if you have only one thread in each block (row) do the sum and mean, like this...

```<code>__global__ both_kernel(Y, H, X, W)
{
    r = blockIdx.x + Y;
    c = threadIdx.x + W;

    chan1value = ...
    chan2value = ...
    chan3value = ...

    if(threadIdx.x == 0)
    {
        ch1RowSum = 0;
        ch2RowSum = 0;
        ch3RowSum = 0;

        for(i=0; i<blockDim.x; i++)
        {
            ch1RowSum += chan1value;
            ch2RowSum += chan2value;
            ch3RowSum += chan3value;
        }

        ch1Mean = ch1RowSum / blockDim.x;
        ch2Mean = ch2RowSum / blockDim.x;
        ch3Mean = ch3RowSum / blockDim.x;
    }
}
</code>```

but it's probably better to use the first value kernel and then a second kernel for both sums and means... It's possible to further parallelize the kernel below, and if it's separate you can focus on that when you're ready.

```<code>__global__ sum_kernel(Y,W)
{
    r = blockIdx.x + Y;

    ch1RowSum = 0;
    ch2RowSum = 0;
    ch3RowSum = 0;

    for(i=0; i<W; i++)
    {
        ch1RowSum += chan1value;
        ch2RowSum += chan2value;
        ch3RowSum += chan3value;
    }

    ch1Mean = ch1RowSum / W;
    ch2Mean = ch2RowSum / W;
    ch3Mean = ch3RowSum / W;
}
</code>```

Title: CUDA: embedded for loop kernel

Body:
I have some code that I want to make into a cuda kernel. Behold:

    for (r = Y; r < Y + H; r+=2)
    {
        ch1RowSum = ch2RowSum = ch3RowSum = 0;
        for (c = X; c < X + W; c+=2)
        {
            chan1Value = //some calc'd value
                            chan3Value = //some calc'd value
            chan2Value = //some calc'd value
            ch2RowSum  += chan2Value;
            ch3RowSum  += chan3Value;
            ch1RowSum  += chan1Value;
        }
        ch1Mean += ch1RowSum / W;
        ch2Mean += ch2RowSum / W;
        ch3Mean += ch3RowSum / W;
    }

Should this be split up into two kernels, one to calculate the RowSums and one to calculate the Means, and how should I handle the fact that my loop indices dont start at zero and end at N?

Body:
Let's suppose you have a kernel that computes the three values. Each thread in your configuration will compute the three values for each (r,c) pair.

__global__ value_kernel(Y, H, X, W)
{
    r = blockIdx.x + Y;
    c = threadIdx.x + W;

    chan1value = ...
    chan2value = ...
    chan3value = ...
}

I don't believe you can calculate the sum (completely in parallel, at least) in the above kernel. You won't be able to use += like you have above. You could put it all in one kernel if you have only one thread in each block (row) do the sum and mean, like this...

__global__ both_kernel(Y, H, X, W)
{
    r = blockIdx.x + Y;
    c = threadIdx.x + W;

    chan1value = ...
    chan2value = ...
    chan3value = ...

    if(threadIdx.x == 0)
    {
        ch1RowSum = 0;
        ch2RowSum = 0;
        ch3RowSum = 0;

        for(i=0; i<blockDim.x; i++)
        {
            ch1RowSum += chan1value;
            ch2RowSum += chan2value;
            ch3RowSum += chan3value;
        }

        ch1Mean = ch1RowSum / blockDim.x;
        ch2Mean = ch2RowSum / blockDim.x;
        ch3Mean = ch3RowSum / blockDim.x;
    }
}

but it's probably better to use the first value kernel and then a second kernel for both sums and means... It's possible to further parallelize the kernel below, and if it's separate you can focus on that when you're ready.

__global__ sum_kernel(Y,W)
{
    r = blockIdx.x + Y;

    ch1RowSum = 0;
    ch2RowSum = 0;
    ch3RowSum = 0;

    for(i=0; i<W; i++)
    {
        ch1RowSum += chan1value;
        ch2RowSum += chan2value;
        ch3RowSum += chan3value;
    }

    ch1Mean = ch1RowSum / W;
    ch2Mean = ch2RowSum / W;
    ch3Mean = ch3RowSum / W;
}