问:
Test Node.js API with Jest (and mockgoose)
Two questions here:

1) Is Jest a good options to test Node.js (express) APIs?

2) I'm trying to use Jest with Mockgoose, but I can't figure out how to establish the connection and run tests after. Here is my final attempt before coming on SO:

```<code>const Mongoose = require('mongoose').Mongoose
const mongoose = new Mongoose()
mongoose.Promise = require('bluebird')
const mockgoose = require('mockgoose')

const connectDB = (cb) => () => {
  return mockgoose(mongoose).then(() => {
    return mongoose.connect('mongodb://test/testingDB', err => {
      if (err) {
        console.log('err is', err)
        return process.exit()
      }
      return cb(() => {
        console.log('END') // this is logged
        mongoose.connection.close()
      })
    })
  })
}

describe('test api', connectDB((end) => {
  test('adds 1 + 2 to equal 3', () => {
    expect(1 + 2).toBe(3)
  })
  end()
}))
</code>```

The error is Your test suite must contain at least one test. This error makes a bit of sense to me but I can't figure out how to solve it. Any suggestions?

Output:

```<code>Test suite failed to run

Your test suite must contain at least one test.
</code>```

答:
Very late answer, but I hope it'll help.
If you pay attention, your describe block has no test function inside it.

The test function is actually inside the callback passed to describe.. kind of, the stack is complicated due to arrow function callbacks.

this example code will generate the same problem..

```<code>describe('tests',function(){
  function cb() {
    setTimeout(function(){
      it('this does not work',function(end){
        end();
      });
    },500);
  }
  cb();

  setTimeout(function(){
    it('also does not work',function(end){
      end();
    });
  },500);
});
</code>```

since the connection to mongo is async, when jest first scans the function to find "tests" inside the describe, it fails as there is none.
it may not look like it, but that's exactly what you're doing.

I think in this case your solution was a bit too clever(to the point it doesn't work), and breaking it down to simpler statements could've helped pinpointing this issue

Body:
Two questions here:

1) Is Jest a good options to test Node.js (express) APIs?

2) I'm trying to use Jest with Mockgoose, but I can't figure out how to establish the connection and run tests after. Here is my final attempt before coming on SO:

const Mongoose = require('mongoose').Mongoose
const mongoose = new Mongoose()
mongoose.Promise = require('bluebird')
const mockgoose = require('mockgoose')

const connectDB = (cb) => () => {
  return mockgoose(mongoose).then(() => {
    return mongoose.connect('mongodb://test/testingDB', err => {
      if (err) {
        console.log('err is', err)
        return process.exit()
      }
      return cb(() => {
        console.log('END') // this is logged
        mongoose.connection.close()
      })
    })
  })
}

describe('test api', connectDB((end) => {
  test('adds 1 + 2 to equal 3', () => {
    expect(1 + 2).toBe(3)
  })
  end()
}))

The error is Your test suite must contain at least one test. This error makes a bit of sense to me but I can't figure out how to solve it. Any suggestions?

Output:

Test suite failed to run

Your test suite must contain at least one test.

Body:
Very late answer, but I hope it'll help.
If you pay attention, your describe block has no test function inside it.

The test function is actually inside the callback passed to describe.. kind of, the stack is complicated due to arrow function callbacks.

this example code will generate the same problem..

describe('tests',function(){
  function cb() {
    setTimeout(function(){
      it('this does not work',function(end){
        end();
      });
    },500);
  }
  cb();

  setTimeout(function(){
    it('also does not work',function(end){
      end();
    });
  },500);
});

since the connection to mongo is async, when jest first scans the function to find "tests" inside the describe, it fails as there is none.
it may not look like it, but that's exactly what you're doing.

I think in this case your solution was a bit too clever(to the point it doesn't work), and breaking it down to simpler statements could've helped pinpointing this issue


来源: stackexchange

问:
Min and max properties in scene builder JavaFX do not work
I set min and max properties so that to make my window not resizable. But when I try it out it does not work. What is wrong?

答:
you could simply set the resizable property of your window to false, </p>

```<code>Stage stage = new Stage();
stage.setScene(scene);
stage.setResizable(false);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you could simply set the resizable property of your window to false,

Stage stage = new Stage();
stage.setScene(scene);
stage.setResizable(false);


问:
Issues when converting from Europe/London time to UTC
I am trying to convert a dateTime string from Europe/London time to UTC.

Googling tells me that UTC should be an hour behind Europe/London time but when I tried to write a unit test to verify this the time calculated results in the same epoch times. I also tried from another Timezone (Asia/Kolkata) and that works correctly. So I am quite confused and not sure what I'm doing wrong.

Here's the function I'm using (with a dateString of 2017-01-15 13:00:00 and both of the above mentioned timezones)

```<code>long getUTCTimeEpoch(final String dateString, @NonNull final String fromTimeZone) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    formatter.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
    try {
        Date inputTime = formatter.parse(dateString);
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(fromTimeZone));
        calendar.setTime(inputTime);
        Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        utcCalendar.setTimeInMillis(calendar.getTimeInMillis());
        return utcCalendar.getTime().getTime();
    } catch (ParseException e) {
        return 0;
    }
}
</code>```

This works,

```<code>assertThat(getUTCTimeEpoch(timeString, "Asia/Kolkata"), is(1484465400000))
</code>```

and this fails,

```<code>assertThat(getUTCTimeEpoch(timeString, "Europe/London"), is(1484481600000))
</code>```

答:
In this kind of a conversion a lot of players are involved, a couple are:

Local times from 2 different time zones

Local time zone rules (BST, GMT vs. WET; CET/CEST; etc.)

Solution: Use the java.time classes which handles all the stuff what you need.

Looking at you, ZonedDateTime.

Body:
I am trying to convert a dateTime string from Europe/London time to UTC.

Googling tells me that UTC should be an hour behind Europe/London time but when I tried to write a unit test to verify this the time calculated results in the same epoch times. I also tried from another Timezone (Asia/Kolkata) and that works correctly. So I am quite confused and not sure what I'm doing wrong.

Here's the function I'm using (with a dateString of 2017-01-15 13:00:00 and both of the above mentioned timezones)

long getUTCTimeEpoch(final String dateString, @NonNull final String fromTimeZone) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    formatter.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
    try {
        Date inputTime = formatter.parse(dateString);
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(fromTimeZone));
        calendar.setTime(inputTime);
        Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        utcCalendar.setTimeInMillis(calendar.getTimeInMillis());
        return utcCalendar.getTime().getTime();
    } catch (ParseException e) {
        return 0;
    }
}

This works,

assertThat(getUTCTimeEpoch(timeString, "Asia/Kolkata"), is(1484465400000))

and this fails,

assertThat(getUTCTimeEpoch(timeString, "Europe/London"), is(1484481600000))


问:
Is there a difference between activations functions in tensorflow? tf.nn.tanh vs tf.tanh
I want to setup a neuronal network and I am asking myself if there is a difference between those two functions?

tf.nn.tanh vs tf.tanh

答:
They are the exact same alias to tensorflow.python.ops.math_ops.tanh.

Same thing goes for tf.sigmoid and tf.nn.sigmoid.


问:
FragmentStatePagerAdapter items don't load
In my main activity I have multiple Fragments that you can navigate through a bottom navigation (Replace a FrameLayout container in main activity XML)

One of those Fragments contains a ViewPager that should show multiple Fragments (MyFragment) using a FragmentStatePagerAdapter (MyAdapter).

First time I open that Fragment it works just fine but when I navigate to a different one and then come back the first two Fragments in the Pager are grey and unpopulated. Anyone got an idea what the problem might be?

The Adapter is set up like this:
This is called in onFragmentViewCreated

```<code>private void setUpHeaderPager() {
    featuredAdapter = new MyAdapter(getActivity().getSupportFragmentManager());
    myPager.setAdapter(myAdapter);
    pageIndicatorView.setViewPager(myPager);
    pageIndicatorView.setAnimationType(AnimationType.WORM);
    compositeSubscription.add(apiService.getMyPOJOs()
            .subscribeOn(networkScheduler)
            .observeOn(uiScheduler)
            .subscribe(new Action1<List<MyPOJO>>() {
                @Override
                public void call(List<MyPOJO> myPOJOs) {
                    myAdapter.setItems(myPOJOs);
                    pageIndicatorView.setCount(myPOJOs.size());
                    myPager.setCurrentItem(0);
                    pageIndicatorView.setSelection(0);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    throwable.printStackTrace();
                }
            }));
}
</code>```

And this is what the Adapter looks like:

```<code>private class MyAdapter extends FragmentStatePagerAdapter {

    private List<SomePOJO> items = new ArrayList<>(0);

    public void setItems(@Nonnull List<Collection> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    FeaturedReleasesAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(items.get(position));
    }

    @Override
    public int getCount() {
        return items.size();
    }
}
</code>```

Just in case the relevant code of MyFragment:

```<code>public class FeaturedReleaseFragment extends BaseFragment {

private MyPOJO someObject = null;

// Bind some views

public static MyFragment newInstance(MyPOJO someObject) {
    MyFragment fragment = new MyFragment();
    fragment.someObject = someObject;
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_my_fragment, container, false);

    ButterKnife.bind(this, rootView);

    populate();

    return rootView;
}

private void populate() {
    if (MyPOJO != null) {
        // set some text and load images
    }
}
</code>```

onFragmentViewCreated is called just fine, the adapters getItem is not...

答:
It may be how you're navigating between the bottom navigation fragments and subsequently whats happening with their lifecycle.

If you are using .replace on the FragmentTransaction, try using .show and .hide instead.

Something like the following might do it:

```<code>public void navigateToFragment( Fragment frag ) {
     FragmentTransaction transaction = getFragmentManager().beginTransaction();

    transaction.hide(currentFragment);

    if ( !fragment.isAdded() ) {
        transaction.add(R.id.container,fragment)
    } else if ( !fragment.isHidden() ) {
        transaction.show(fragment);
    }
    transation.commit();
}
</code>```

Body:
In my main activity I have multiple Fragments that you can navigate through a bottom navigation (Replace a FrameLayout container in main activity XML)

One of those Fragments contains a ViewPager that should show multiple Fragments (MyFragment) using a FragmentStatePagerAdapter (MyAdapter).

First time I open that Fragment it works just fine but when I navigate to a different one and then come back the first two Fragments in the Pager are grey and unpopulated. Anyone got an idea what the problem might be?

The Adapter is set up like this:
This is called in onFragmentViewCreated

private void setUpHeaderPager() {
    featuredAdapter = new MyAdapter(getActivity().getSupportFragmentManager());
    myPager.setAdapter(myAdapter);
    pageIndicatorView.setViewPager(myPager);
    pageIndicatorView.setAnimationType(AnimationType.WORM);
    compositeSubscription.add(apiService.getMyPOJOs()
            .subscribeOn(networkScheduler)
            .observeOn(uiScheduler)
            .subscribe(new Action1<List<MyPOJO>>() {
                @Override
                public void call(List<MyPOJO> myPOJOs) {
                    myAdapter.setItems(myPOJOs);
                    pageIndicatorView.setCount(myPOJOs.size());
                    myPager.setCurrentItem(0);
                    pageIndicatorView.setSelection(0);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    throwable.printStackTrace();
                }
            }));
}

And this is what the Adapter looks like:

private class MyAdapter extends FragmentStatePagerAdapter {

    private List<SomePOJO> items = new ArrayList<>(0);

    public void setItems(@Nonnull List<Collection> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    FeaturedReleasesAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int position) {
        return MyFragment.newInstance(items.get(position));
    }

    @Override
    public int getCount() {
        return items.size();
    }
}

Just in case the relevant code of MyFragment:

public class FeaturedReleaseFragment extends BaseFragment {

private MyPOJO someObject = null;

// Bind some views

public static MyFragment newInstance(MyPOJO someObject) {
    MyFragment fragment = new MyFragment();
    fragment.someObject = someObject;
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_my_fragment, container, false);

    ButterKnife.bind(this, rootView);

    populate();

    return rootView;
}

private void populate() {
    if (MyPOJO != null) {
        // set some text and load images
    }
}

onFragmentViewCreated is called just fine, the adapters getItem is not...

Body:
It may be how you're navigating between the bottom navigation fragments and subsequently whats happening with their lifecycle.

If you are using .replace on the FragmentTransaction, try using .show and .hide instead.

Something like the following might do it:

public void navigateToFragment( Fragment frag ) {
     FragmentTransaction transaction = getFragmentManager().beginTransaction();

    transaction.hide(currentFragment);

    if ( !fragment.isAdded() ) {
        transaction.add(R.id.container,fragment)
    } else if ( !fragment.isHidden() ) {
        transaction.show(fragment);
    }
    transation.commit();
}


问:
System.Data.Entity.Spatial replacement in ASP.NET Core
I am trying to migrate a webform from ASP.NET MVC to ASP.NET Core MVC. Currently I am trying to find a way to replace:

```<code>using System.Data.Entity.Spatial;
</code>```

since it is not currently available in .NET Core or I may have not been able to find it.

Is there a way of including this package? Maybe through a NuGet package?

Ps. I read Microsoft guideline briefly but could not find anything related to it. For anyone who may be in a similar situation, the guide is here:
https://docs.asp.net/en/latest/migration/mvc.html

(Sorry if I couldn't write a good question, I am trying to get used to the system here)

答:
Spatial data isn't supported yet by Entity Framework Core.

Spatial is not planned for 2.0 and we haven’t finished planning for the version after. It might be a good idea to post more details about what you would like to have in spatial support at https://github.com/aspnet/EntityFramework/issues/1100, e.g. do you use specific spatial functions or do you need rich spatial types with all kinds of spatial functionality, would you use this only with a specific database or do you need to write the same code against multiple databases? Etc.

(Source: MSDN .NET Blog)

I have made a temporary workaround to include Geography column and use it in EF Core 1.0.0 and above. It's not perfect, but it will do for now. (Similar to Hatef’s answer apparently, wow great minds think alike I guess.)

See the accepted answer on: Entity Framework Core: Type Udt is not supported on this platform. (Spatial Data - Geography)

Body:
I am trying to migrate a webform from ASP.NET MVC to ASP.NET Core MVC. Currently I am trying to find a way to replace:

using System.Data.Entity.Spatial;

since it is not currently available in .NET Core or I may have not been able to find it.

Is there a way of including this package? Maybe through a NuGet package?

Ps. I read Microsoft guideline briefly but could not find anything related to it. For anyone who may be in a similar situation, the guide is here:
https://docs.asp.net/en/latest/migration/mvc.html

(Sorry if I couldn't write a good question, I am trying to get used to the system here)


问:
Removing characters in a java string
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

```<code>String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");
</code>```

This won't work!

答:
A java string (java.lang.String) is immutable; it cannot be edited.  You can try using StringBuffer (java.lang.StringBuffer) which is a mutable buffer for returning strings.

```<code>StringBuffer SQL = new StringBuffer();
SQL.append(" AND Gender = 'Female'");
</code>```

You can also use replace and delete to remove substrings from the buffer.  When you're done editing the buffer simply use SQL.toString().

ContentLicense: CC BY-SA 2.5

Title: Removing characters in a java string

Body:
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");

This won't work!

Body:
A java string (java.lang.String) is immutable; it cannot be edited.  You can try using StringBuffer (java.lang.StringBuffer) which is a mutable buffer for returning strings.

StringBuffer SQL = new StringBuffer();
SQL.append(" AND Gender = 'Female'");

You can also use replace and delete to remove substrings from the buffer.  When you're done editing the buffer simply use SQL.toString().


问:
iOS Launch Storyboard: How can I change a Tab Bar's tint color?

What I'm doing:

Using a 'launch storyboard'. It's quite simple, and contains a default UITabBarController. I've set the tab bar's 'tintColor' to red in the launch storyboard, as well as in my app. I'm using Xcode 7, iOS 9.

What doesn't work:

The launch screen loads the tab bar using the default blue iOS tint color...! Then after loading, the tint color switches to red when the launch screen storyboard is replaced.

How on earth are you meant to set a tab bar's tint color in a storyboard?

Demo Project: http://s000.tinyupload.com/?file_id=73998115878034693063

答:
Well thanks to @OIDor for his solution, it is a great hack.

To be clear however, you don't need to do all that. All you have to do is:

Edit the source of your Launch Screen storyboard and change
launchScreen="YES" to launchScreen="NO", this enables you to do the
next part...

Add the user-defined attribute tintColor on the Tab Bar
in the storyboard. This is not permitted by Xcode without the first
step

Hey presto it's all working.


答:
Try adding the line:

```<code>primaryStage.setResizable(false);
</code>```

This will make the window non-resizable, without the need for setting min and max values.

Title: Min and max properties in scene builder JavaFX do not work

Body: I set min and max properties so that to make my window not resizable. But when I try it out it does not work. What is wrong?

Body:
Try adding the line:

primaryStage.setResizable(false);

This will make the window non-resizable, without the need for setting min and max values.


问:
error (-38, 0) media player
Whenever i am trying to stop the media player in an another activity than i am getting an error:
 E/MediaPlayer: start called in state 64, mPlayer(0xa3baf580)
 E/MediaPlayer: error (-38, 0)

```<code>MainActivity:
</code>```

package radiofm.arabelradio;

```<code>import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

     private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.stop();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar() .setDisplayHomeAsUpEnabled(true);
        getSupportActionBar() .setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onStop () {
        super.onStop();
    }

        @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
media player objected created in one activity can not be used in the another activity
make another where you use the media player  to fragment or initialize the  media player in service so that u can access any where.

or

check this question answer
How can I stop media player in another activity?
 and check https://developer.android.com/guide/topics/media/mediaplayer.html#mpandservices

Title: error (-38, 0) media player

Body:
Whenever i am trying to stop the media player in an another activity than i am getting an error:
 E/MediaPlayer: start called in state 64, mPlayer(0xa3baf580)
 E/MediaPlayer: error (-38, 0)

MainActivity:

package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

     private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.stop();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar() .setDisplayHomeAsUpEnabled(true);
        getSupportActionBar() .setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onStop () {
        super.onStop();
    }

        @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


问:
WPF filter datagrid through textbox
I have been searching everywhere and I just cannot make it..
I have a simple DataGrid:

```<code><DataGrid Name="myGrid" HorizontalAlignment="Left" Height="399"
                  Margin="272,150,0,0" VerticalAlignment="Top" Width="735"/>
</code>```

When my form loads. I have this function to fill datagrid :

```<code>public MainWindow()
{
    InitializeComponent();
    myGrid.ItemsSource = datatble;
}
</code>```

I have a TextBox name "txtSearch" and my goal is to filter the datagrid and find all rows that contain txtSearch.Text (and hide the other rows)

Could someone provide an example ?

答:
You could set the RowFilter property of the DataView to a filter expression. This is how you would filter a DataTable.

Here is a basic example that should give you the idea:

```<code>public partial class MainWindow : Window
{
    DataTable _dataTable;
    public MainWindow()
    {
        InitializeComponent();
        _dataTable = new DataTable();
        _dataTable.Columns.Add(new DataColumn("Name"));
        _dataTable.Columns.Add(new DataColumn("Id"));
        _dataTable.Rows.Add("First", "1");
        _dataTable.Rows.Add("Second", "2");
        myGrid.ItemsSource = _dataTable.DefaultView;
    }

    private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
    {
        string filter = txtSearch.Text;
        if (string.IsNullOrEmpty(filter))
            _dataTable.DefaultView.RowFilter = null;
        else
            _dataTable.DefaultView.RowFilter = string.Format("Name Like '%{0}%' OR Id Like '%{0}%'", filter);
    }
}
</code>```

Title: WPF filter datagrid through textbox

Body:
I have been searching everywhere and I just cannot make it..
I have a simple DataGrid:

<DataGrid Name="myGrid" HorizontalAlignment="Left" Height="399"
                  Margin="272,150,0,0" VerticalAlignment="Top" Width="735"/>

When my form loads. I have this function to fill datagrid :

public MainWindow()
{
    InitializeComponent();
    myGrid.ItemsSource = datatble;
}

I have a TextBox name "txtSearch" and my goal is to filter the datagrid and find all rows that contain txtSearch.Text (and hide the other rows)

Could someone provide an example ?

Body:
You could set the RowFilter property of the DataView to a filter expression. This is how you would filter a DataTable.

Here is a basic example that should give you the idea:

public partial class MainWindow : Window
{
    DataTable _dataTable;
    public MainWindow()
    {
        InitializeComponent();
        _dataTable = new DataTable();
        _dataTable.Columns.Add(new DataColumn("Name"));
        _dataTable.Columns.Add(new DataColumn("Id"));
        _dataTable.Rows.Add("First", "1");
        _dataTable.Rows.Add("Second", "2");
        myGrid.ItemsSource = _dataTable.DefaultView;
    }

    private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
    {
        string filter = txtSearch.Text;
        if (string.IsNullOrEmpty(filter))
            _dataTable.DefaultView.RowFilter = null;
        else
            _dataTable.DefaultView.RowFilter = string.Format("Name Like '%{0}%' OR Id Like '%{0}%'", filter);
    }
}


问:
airbnb airflow scheduler keeps running tasks even if scheduled hourly
I am using airbnb's airflow and I create a simple task shown below. However the scheduler keeps running the task even though I set the interval to be hourly or any other interval. Another thing I notice is that if I set schedule interval to be '@once', it will never run the dag.

I followed the conventions here http://airflow.readthedocs.org/en/latest/scheduler.html#dag-runs

The simple dag im using.

```<code>"""
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from airflow import DAG
from airflow.operators import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2016, 1, 5),
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
}

dag = DAG(
    'schedule_test', default_args=default_args, schedule_interval='@hourly')

# t1, t2 and t3 are examples of tasks created by instatiating operators
t1 = BashOperator(
    task_id='print_date',
    bash_command='date',
    dag=dag)
</code>```

Scheduler output for reference. As you can see it keeps running it over and over but in my dag, I have schedule_interval='@hourly'

```<code>2016-01-06 20:34:37,266 - root - INFO - Starting the scheduler
2016-01-06 20:34:37,267 - root - INFO - Filling up the DagBag from /usr/local/airflow/dags
2016-01-06 20:34:37,267 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:37,272 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:37,281 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:37,288 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:37,291 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:37,318 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False>
2016-01-06 20:34:37,321 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:37,323 - root - INFO - Checking dependencies on 1 tasks instances, minus 0 skippable ones
2016-01-06 20:34:37,326 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T00:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:37,347 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:37,347 - root - INFO - Loop took: 0.071298 seconds
2016-01-06 20:34:37,356 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:37,357 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:22.357089
2016-01-06 20:34:42,269 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:42,274 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:42,277 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:42,295 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:42,296 - root - INFO - Loop took: 0.029931 seconds
2016-01-06 20:34:42,309 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:42,310 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:27.310303
2016-01-06 20:34:42,314 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T00:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T00:00:00
2016-01-06 20:34:47,895 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:47,900 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:47,904 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:47,922 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False>
2016-01-06 20:34:47,925 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False> successful
2016-01-06 20:34:47,926 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:34:47,928 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:34:47,937 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:47,940 - root - INFO - Checking dependencies on 2 tasks instances, minus 0 skippable ones
2016-01-06 20:34:47,943 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T01:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:47,947 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T02:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:47,960 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:47,960 - root - INFO - Loop took: 0.067789 seconds
2016-01-06 20:34:47,968 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:47,968 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:32.968940
2016-01-06 20:34:52,901 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:52,906 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:52,909 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:52,942 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:34:52,946 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:34:52,948 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 03:00:00: scheduled__2016-01-06T03:00:00, externally triggered: False>
2016-01-06 20:34:52,950 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:52,953 - root - INFO - Checking dependencies on 3 tasks instances, minus 0 skippable ones
2016-01-06 20:34:52,961 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T03:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:52,975 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:52,976 - root - INFO - Loop took: 0.07741 seconds
2016-01-06 20:34:52,982 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:52,983 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:37.983542
2016-01-06 20:34:52,987 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T02:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T02:00:00
2016-01-06 20:34:58,583 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T01:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T01:00:00
2016-01-06 20:35:04,215 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:35:04,223 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:35:04,229 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:35:04,263 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:35:04,267 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False> successful
2016-01-06 20:35:04,268 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:35:04,272 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False> successful
2016-01-06 20:35:04,273 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 03:00:00: scheduled__2016-01-06T03:00:00, externally triggered: False>
2016-01-06 20:35:04,276 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 04:00:00: scheduled__2016-01-06T04:00:00, externally triggered: False>
</code>```

答: I have seen this issue , actually in airflow.cfg file you can see number of workers and worker refresh time , generally it is 30 seconds so every 30 s new worker is started and that loads all dags again and runs them.I made worker refresh to 0 to stop this issue.</p>

Body:
I am using airbnb's airflow and I create a simple task shown below. However the scheduler keeps running the task even though I set the interval to be hourly or any other interval. Another thing I notice is that if I set schedule interval to be '@once', it will never run the dag.

I followed the conventions here http://airflow.readthedocs.org/en/latest/scheduler.html#dag-runs

The simple dag im using.

"""
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from airflow import DAG
from airflow.operators import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2016, 1, 5),
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
}

dag = DAG(
    'schedule_test', default_args=default_args, schedule_interval='@hourly')

# t1, t2 and t3 are examples of tasks created by instatiating operators
t1 = BashOperator(
    task_id='print_date',
    bash_command='date',
    dag=dag)

Scheduler output for reference. As you can see it keeps running it over and over but in my dag, I have schedule_interval='@hourly'

2016-01-06 20:34:37,266 - root - INFO - Starting the scheduler
2016-01-06 20:34:37,267 - root - INFO - Filling up the DagBag from /usr/local/airflow/dags
2016-01-06 20:34:37,267 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:37,272 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:37,281 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:37,288 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:37,291 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:37,318 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False>
2016-01-06 20:34:37,321 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:37,323 - root - INFO - Checking dependencies on 1 tasks instances, minus 0 skippable ones
2016-01-06 20:34:37,326 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T00:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:37,347 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:37,347 - root - INFO - Loop took: 0.071298 seconds
2016-01-06 20:34:37,356 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:37,357 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:22.357089
2016-01-06 20:34:42,269 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:42,274 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:42,277 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:42,295 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:42,296 - root - INFO - Loop took: 0.029931 seconds
2016-01-06 20:34:42,309 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:42,310 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:27.310303
2016-01-06 20:34:42,314 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T00:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T00:00:00
2016-01-06 20:34:47,895 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:47,900 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:47,904 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:47,922 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False>
2016-01-06 20:34:47,925 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 00:00:00: scheduled__2016-01-06T00:00:00, externally triggered: False> successful
2016-01-06 20:34:47,926 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:34:47,928 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:34:47,937 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:47,940 - root - INFO - Checking dependencies on 2 tasks instances, minus 0 skippable ones
2016-01-06 20:34:47,943 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T01:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:47,947 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T02:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:47,960 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:47,960 - root - INFO - Loop took: 0.067789 seconds
2016-01-06 20:34:47,968 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:47,968 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:32.968940
2016-01-06 20:34:52,901 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:34:52,906 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:34:52,909 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:34:52,942 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:34:52,946 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:34:52,948 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 03:00:00: scheduled__2016-01-06T03:00:00, externally triggered: False>
2016-01-06 20:34:52,950 - root - INFO - Getting list of tasks to skip for active runs.
2016-01-06 20:34:52,953 - root - INFO - Checking dependencies on 3 tasks instances, minus 0 skippable ones
2016-01-06 20:34:52,961 - root - INFO - Adding to queue: airflow run schedule_test print_date 2016-01-06T03:00:00 --local -sd DAGS_FOLDER/test.py
2016-01-06 20:34:52,975 - root - INFO - Done queuing tasks, calling the executor's heartbeat
2016-01-06 20:34:52,976 - root - INFO - Loop took: 0.07741 seconds
2016-01-06 20:34:52,982 - root - INFO - Finding 'running' jobs without a recent heartbeat
2016-01-06 20:34:52,983 - root - INFO - Failing jobs without heartbeat after 2016-01-06 20:32:37.983542
2016-01-06 20:34:52,987 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T02:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T02:00:00
2016-01-06 20:34:58,583 - root - INFO - commandairflow run schedule_test print_date 2016-01-06T01:00:00 --local -sd DAGS_FOLDER/test.py
Logging into: /usr/local/airflow/logs/schedule_test/print_date/2016-01-06T01:00:00
2016-01-06 20:35:04,215 - root - INFO - Prioritizing 0 queued jobs
2016-01-06 20:35:04,223 - root - INFO - Importing /usr/local/airflow/dags/test.py
2016-01-06 20:35:04,229 - root - INFO - Loaded DAG <DAG: schedule_test>
2016-01-06 20:35:04,263 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False>
2016-01-06 20:35:04,267 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 01:00:00: scheduled__2016-01-06T01:00:00, externally triggered: False> successful
2016-01-06 20:35:04,268 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False>
2016-01-06 20:35:04,272 - root - INFO - Marking run <DagRun schedule_test @ 2016-01-06 02:00:00: scheduled__2016-01-06T02:00:00, externally triggered: False> successful
2016-01-06 20:35:04,273 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 03:00:00: scheduled__2016-01-06T03:00:00, externally triggered: False>
2016-01-06 20:35:04,276 - root - INFO - Checking state for <DagRun schedule_test @ 2016-01-06 04:00:00: scheduled__2016-01-06T04:00:00, externally triggered: False>


问:
PowerPC GCC Print registers in assembly without % sign
On Matt Godbolt's Compiler Explorer website, you can compile code using various pre-installed compilers.  When using PowerPC gcc 4.8 the registers cannot be distinguished from immediates (for example addi 11,31,16).

However, when the -mregnames option is used, all registers are marked with %r followed by the register index. How do I omit just the % sign to get r1 instead of %r1?

For example, void nop () {} with gcc4.8 PowerPC -O0 -mregnames:

```<code>nop():
    stwu %r1,-16(%r1)
    stw %r31,12(%r1)
    mr %r31,%r1
    addi %r11,%r31,16
    lwz %r31,-4(%r11)
    mr %r1,%r11
    blr
</code>```

答:
When targeting PowerPC, you basically have two options for the syntax of assembly listings:

You can either use the IBM syntax (common on IBM assemblers), where the registers do not use any type of special prefix: they are just referred to with numbers. Yes, this makes it difficult to distinguish them from immediates.

Or, you can use Gnu/AT&T syntax, which always prefixes registers with % symbols (and an r, in this case). This not only makes it easier to distinguish between registers and immediates, but it also makes it possible to distinguish between integer registers (%r?) and floating-point registers (%f?).

There is no intermediate option, where you get the r (or f) prefix, but no leading %. If you need this, you can do like Jester suggested and post-process the output, using the regular expression %r[0-9]+ for matching.

Body:
On Matt Godbolt's Compiler Explorer website, you can compile code using various pre-installed compilers.  When using PowerPC gcc 4.8 the registers cannot be distinguished from immediates (for example addi 11,31,16).

However, when the -mregnames option is used, all registers are marked with %r followed by the register index. How do I omit just the % sign to get r1 instead of %r1?

For example, <a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'void+nop+()+%7B%0A%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:45.171322069863066,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:ppcg48,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'0'),libs:!(),options:'-O0+-mregnames',source:1),l:'5',n:'0',o:'PowerPC+gcc+4.8+(Editor+%231,+Compiler+%232)',t:'0')),k:54.82867793013693,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">void nop () {} with gcc4.8 PowerPC -O0 -mregnames:

nop():
    stwu %r1,-16(%r1)
    stw %r31,12(%r1)
    mr %r31,%r1
    addi %r11,%r31,16
    lwz %r31,-4(%r11)
    mr %r1,%r11
    blr


问:
Execute a bash script from the command line which requires an argument with spaces in
I am attempting to execute a bash script from the command line.
Sometimes it will require an argument that contains spaces.

```<code>bash test.sh -l "path/to/image/may contain spaces.png"
</code>```

What is the correct way to provide this? I have tried escaping \ but to no avail.

I receive the following error;

```<code> bash splash.sh -b \#\000000 -l \"img/Rev Logo.jpg\"
    convert: unable to open image ''"img/Rev'': No such file or directory @ error/blob.c/OpenBlob/3093.
</code>```

Which relates to this bit of code;

```<code>logo="$1"

if checkBackground -eq 1
        then
        convert -size $size canvas:$back -background $back $tmp01
fi

convert \'$logo\' -background $back $tmp02

composite $tmp02 -gravity center $tmp01 output.jpg
</code>```

答:
If the first argument to the script is "foo bar", then this line:

```<code>convert \'$logo\' -background $back $tmp02
</code>```

is passing as its first argument to convert the string 'foo and passing the second argument bar'.  You probably don't want that.  Change that line to:

```<code>convert "$logo" -background "$back" "$tmp02"
</code>```

In general, double quote any variables.

And when you invoke the script, just quote the argument.  If you call the script as:

```<code>bash splash.sh -b \#\000000 -l \"img/Rev Logo.jpg\"
</code>```

then you are passing two separate arguments: "img/Rev and Logo.jpg".  It is perfectly valid to have a filename with a double quote in it, but very unusual.  If you want to pass the single argument img/Rev Logo.jpg, you want to invoke your script as:

```<code>bash splash.sh -b "#000000" -l "img/Rev Logo.jpg"
</code>```

or

```<code>bash splash.sh -b \#000000 -l img/Rev\ Logo.jpg
</code>```

Body:
I am attempting to execute a bash script from the command line.
Sometimes it will require an argument that contains spaces.

bash test.sh -l "path/to/image/may contain spaces.png"

What is the correct way to provide this? I have tried escaping \ but to no avail.

I receive the following error;

 bash splash.sh -b \#\000000 -l \"img/Rev Logo.jpg\"
    convert: unable to open image ''"img/Rev'': No such file or directory @ error/blob.c/OpenBlob/3093.

Which relates to this bit of code;

logo="$1"

if checkBackground -eq 1
        then
        convert -size $size canvas:$back -background $back $tmp01
fi

convert \'$logo\' -background $back $tmp02

composite $tmp02 -gravity center $tmp01 output.jpg

Body:
If the first argument to the script is "foo bar", then this line:

convert \'$logo\' -background $back $tmp02

is passing as its first argument to convert the string 'foo and passing the second argument bar'.  You probably don't want that.  Change that line to:

convert "$logo" -background "$back" "$tmp02"

In general, double quote any variables.

And when you invoke the script, just quote the argument.  If you call the script as:

bash splash.sh -b \#\000000 -l \"img/Rev Logo.jpg\"

then you are passing two separate arguments: "img/Rev and Logo.jpg".  It is perfectly valid to have a filename with a double quote in it, but very unusual.  If you want to pass the single argument img/Rev Logo.jpg, you want to invoke your script as:

bash splash.sh -b "#000000" -l "img/Rev Logo.jpg"

or

bash splash.sh -b \#000000 -l img/Rev\ Logo.jpg


问:
Operator overloading in c (not c++) is it possible?
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

```<code>std::string a_string;
a_string = "bla"
</code>```

or using standard C

```<code>char a_char_array[10];
strcpy(a_char_array,"bla");
</code>```

or

```<code>char *a_char_pointer = "bla";
</code>```

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers

答: FYI: LccWin32 has some extensions that allow for operator overloading</p>

Body:
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

std::string a_string;
a_string = "bla"

or using standard C

char a_char_array[10];
strcpy(a_char_array,"bla");

or

char *a_char_pointer = "bla";

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers


答:
No, there's no difference.

In the tensorflow/tensorflow/python/ops/nn.py file (that's where tf.nn is defined) we can find the definition of tanh:

```<code>from tensorflow.python.ops.math_ops import tanh
</code>```

also, there's this TODO here

```<code># TODO(cwhipkey): sigmoid and tanh should not be exposed from tf.nn.
</code>```

Thus, probably tanh will be removed from the tf.nn package.

Hence tf.tanh (that's defined here) is the one to use.

Title: Is there a difference between activations functions in tensorflow? tf.nn.tanh vs tf.tanh

Body:
I want to setup a neuronal network and I am asking myself if there is a difference between those two functions?

tf.nn.tanh vs tf.tanh

Body:
No, there's no difference.

In the tensorflow/tensorflow/python/ops/nn.py file (that's where tf.nn is defined) we can find the definition of tanh:

from tensorflow.python.ops.math_ops import tanh

also, there's this TODO here

# TODO(cwhipkey): sigmoid and tanh should not be exposed from tf.nn.

Thus, probably tanh will be removed from the tf.nn package.

Hence tf.tanh (that's defined here) is the one to use.


问:
create relationship between two tables in rails 5
I am trying to establish relationship between two tables in rails so
that I can share data between the two tables. However,am not able to
enter data into the operating tables. Any help would be highly appreciated.     </p>

```<code>#below are models#
class Location < ApplicationRecord
  has_many :operatings
end

class Operating < ApplicationRecord
  belongs_to :location
end

##below are my tables##

enable_extension "plpgsql"

create_table "locations", force: :cascade do |t|
  t.string   "country"
  t.string   "supra_region"
  t.string   "region"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
end

create_table "operatings", force: :cascade do |t|
  t.string   "operating_company_name"
  t.string   "address"
  t.date     "year_formed"
  t.string   "other_operational_countries"
  t.string   "about_company"
  t.string   "current_focus"
  t.string   "incumbent_irm_contractor"
  t.string   "irm_frame_agreements"
  t.text     "estimated_irm_budgets"
  t.integer  "location_id"
  t.datetime "created_at",                  null: false
  t.datetime "updated_at",                  null: false
  t.index ["location_id"], name: "index_operatings_on_location_id", using: :btree
end

add_foreign_key "operatings", "locations"

###below is my operating controller###

def create
  @operating = Operating.new(op_company)
  if @operating.save
    flash[:success] = "A recorded has been successfully Saved"
    redirect_to operatings_path
  else
    render 'new'
  end
end

####routes####
resources :offshores,    :index, :show, :new, :create, :destroy
resources :locations,    :index, :show, :new, :create, :destroy
</code>```

答:
Try

```<code>class Operating < ApplicationRecord
    belongs_to :location, :optional => true
end
</code>```

belongs_to will check is the association present, you can debug by printing the Operating's errors

```<code>operating = Operating.create
operating.errors.messages
</code>```

Body:
I am trying to establish relationship between two tables in rails so
that I can share data between the two tables. However,am not able to
enter data into the operating tables. Any help would be highly appreciated.

#below are models#
class Location < ApplicationRecord
  has_many :operatings
end

class Operating < ApplicationRecord
  belongs_to :location
end

##below are my tables##

enable_extension "plpgsql"

create_table "locations", force: :cascade do |t|
  t.string   "country"
  t.string   "supra_region"
  t.string   "region"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
end

create_table "operatings", force: :cascade do |t|
  t.string   "operating_company_name"
  t.string   "address"
  t.date     "year_formed"
  t.string   "other_operational_countries"
  t.string   "about_company"
  t.string   "current_focus"
  t.string   "incumbent_irm_contractor"
  t.string   "irm_frame_agreements"
  t.text     "estimated_irm_budgets"
  t.integer  "location_id"
  t.datetime "created_at",                  null: false
  t.datetime "updated_at",                  null: false
  t.index ["location_id"], name: "index_operatings_on_location_id", using: :btree
end

add_foreign_key "operatings", "locations"

###below is my operating controller###

def create
  @operating = Operating.new(op_company)
  if @operating.save
    flash[:success] = "A recorded has been successfully Saved"
    redirect_to operatings_path
  else
    render 'new'
  end
end

####routes####
resources :offshores,    :index, :show, :new, :create, :destroy
resources :locations,    :index, :show, :new, :create, :destroy

Body:
Try

class Operating < ApplicationRecord
    belongs_to :location, :optional => true
end

belongs_to will check is the association present, you can debug by printing the Operating's errors

operating = Operating.create
operating.errors.messages


问:
Why are structs so much faster than classes for this specific case?
I have three cases to test the relative performance of classes, classes with inheritence and structs. These are to be used for tight  loops so performance counts. Dot products are used as part of many algorithms in 2D and 3D geometry and I have run the profiler on real code. The below tests are indicative of real world performance problems I have seen.

The results for 100000000 times through the loop and application of the dot product gives

```<code>ControlA 208 ms   ( class with inheritence )
ControlB 201 ms   ( class with no inheritence )
ControlC 85  ms   ( struct )
</code>```

The tests were being run without debugging and optimization turned on. My question is, what is it about classes in this case that cause them to be so slow?

I presumed the JIT would still be able to inline all the calls, class or struct, so in effect the results should be identical. Note that if I disable optimizations then my results are identical.

```<code>ControlA 3239
ControlB 3228
ControlC 3213
</code>```

They are always within 20ms of each other if the test is re-run.

The classes under investigation

```<code>using System;
using System.Diagnostics;

public class PointControlA
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public PointControlA(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public class Point3ControlA : PointControlA
{
    public double Z
    {
        get;
        set;
    }

    public Point3ControlA(double x, double y, double z): base (x, y)
    {
        Z = z;
    }

    public static double Dot(Point3ControlA a, Point3ControlA b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public class Point3ControlB
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlB(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlB a, Point3ControlB b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public struct Point3ControlC
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlC(double x, double y, double z):this()
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlC a, Point3ControlC b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}
</code>```

Test Script

```<code>public class Program
{
    public static void TestStructClass()
    {
        var vControlA = new Point3ControlA(11, 12, 13);
        var vControlB = new Point3ControlB(11, 12, 13);
        var vControlC = new Point3ControlC(11, 12, 13);
        var sw = Stopwatch.StartNew();
        var n = 10000000;
        double acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }

        Console.WriteLine("ControlA " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlB.Dot(vControlB, vControlB);
        }

        Console.WriteLine("ControlB " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

        Console.WriteLine("ControlC " + sw.ElapsedMilliseconds);
    }

    public static void Main()
    {
        TestStructClass();
    }
}
</code>```

This dotnet fiddle is proof of compilation only. It does not show the performance differences.

I am trying to explain to a vendor why their choice to use classes instead of structs for small numeric types is a bad idea. I now have the test case to prove it but I can't understand why.

NOTE : I have tried to set a breakpoint in the debugger with JIT optimizations turned on but the debugger will not break. Looking at the IL with JIT optimizations turned off doesn't tell me anything.

EDIT

After the answer by @pkuderov I took his code and played with it. I changed the code and found that if I forced inlining via

```<code>   [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static double Dot(Point3Class a)
    {
        return a.X * a.X + a.Y * a.Y + a.Z * a.Z;
    }
</code>```

the difference between the struct and class for dot product vanished. Why with some setups the attribute is not needed but for me it was is not clear. However I did not give up. There is still a performance problem with the vendor code and I think the DotProduct is not the best example.

I modified @pkuderov's code to implement Vector Add which will create new instances of the structs and classes. The results are here

https://gist.github.com/bradphelan/9b383c8e99edc38068fcc0dccc8a7b48

In the example I also modifed the code to pick a pseudo random vector from an array to avoid the problem of the instances sticking in the registers ( I hope ).

The results show that:

DotProduct performance is identical or maybe faster for classes

Vector Add, and I assume anything that creates a new object is slower.

Add class/class             2777ms
Add struct/struct           2457ms

DotProd class/class         1909ms
DotProd struct/struct       2108ms

The full code and results are here if anybody wants to try it out.

Edit Again

For the vector add example where an array of vectors is summed together the struct version keeps the accumulator in 3 registers

```<code> var accStruct = new Point3Struct(0, 0, 0);
 for (int i = 0; i < n; i++)
     accStruct = Point3Struct.Add(accStruct, pointStruct[(i + 1) % m]);
</code>```

the asm body is

```<code>// load the next vector into a register
00007FFA3CA2240E  vmovsd      xmm3,qword ptr [rax]
00007FFA3CA22413  vmovsd      xmm4,qword ptr [rax+8]
00007FFA3CA22419  vmovsd      xmm5,qword ptr [rax+10h]
// Sum the accumulator (the accumulator stays in the registers )
00007FFA3CA2241F  vaddsd      xmm0,xmm0,xmm3
00007FFA3CA22424  vaddsd      xmm1,xmm1,xmm4
00007FFA3CA22429  vaddsd      xmm2,xmm2,xmm5
</code>```

but for class based vector version it reads and writes out the accumulator each time to main memory which is inefficient

```<code>var accPC = new Point3Class(0, 0, 0);
for (int i = 0; i < n; i++)
    accPC = Point3Class.Add(accPC, pointClass[(i + 1) % m]);
</code>```

the asm body is

```<code>// Read and add both accumulator X and Xnext from main memory
00007FFA3CA2224A  vmovsd      xmm0,qword ptr [r14+8]
00007FFA3CA22250  vmovaps     xmm7,xmm0
00007FFA3CA22255  vaddsd      xmm7,xmm7,mmword ptr [r12+8]

// Read and add both accumulator Y and Ynext from main memory
00007FFA3CA2225C  vmovsd      xmm0,qword ptr [r14+10h]
00007FFA3CA22262  vmovaps     xmm8,xmm0
00007FFA3CA22267  vaddsd      xmm8,xmm8,mmword ptr [r12+10h]

// Read and add both accumulator Z and Znext from main memory
00007FFA3CA2226E  vmovsd      xmm9,qword ptr [r14+18h]
00007FFA3CA22283  vmovaps     xmm0,xmm9
00007FFA3CA22288  vaddsd      xmm0,xmm0,mmword ptr [r12+18h]

// Move accumulator accumulator X,Y,Z back to main memory.
00007FFA3CA2228F  vmovsd      qword ptr [rax+8],xmm7
00007FFA3CA22295  vmovsd      qword ptr [rax+10h],xmm8
00007FFA3CA2229B  vmovsd      qword ptr [rax+18h],xmm0
</code>```

答:
Update

After spending some time thinking about problem I think I'm aggree with @DavidHaim that memory jump overhead is not the case here because of caching.

Also I've added to your tests more options (and removed first one with inheritance). So I have:

cl = variable of class with 3 points:

Dot(cl, cl) - initial method

Dot(cl) - which is "square product"

Dot(cl.X, cl.Y, cl.Z, cl.X, cl.Y, cl.Z) aka Dot(cl.xyz)- pass fields

st = variable of struct with 3 points:

Dot(st, st) - initial

Dot(st) - square product

Dot(st.X, st.Y, st.Z, st.X, st.Y, st.Z) aka Dot(st.xyz) - pass fields

st6 = vairable of struct with 6 points:

Dot(st6) - wanted to check if size of struct matters

Dot(x, y, z, x, y, z) aka Dot(xyz) - just local const double variables.

Result times are:

Dot(cl.xyz) is the worst ~570ms,

Dot(st6), Dot(st.xyz) is the second worst ~440ms and ~480ms

the others are ~325ms

...And I don't really sure why I see these results.

Maybe for plain primitive types compiler does more aggresive pass by register optimizations, maybe it's more sure of lifetime boundaries or constantness and then more aggressive optimizations again. Maybe some kind of loop unwinding.

I think my expertise is just not enough :) But still, my results counter your results.

Full test code with results on my machine and generated IL code you can find here.

In C# classes are reference types and structs are value types. One major effect is that value types can be (and most of the time are!) allocated on the stack, while reference types are always allocated on the heap.

So every time you get access to the inner state of a reference type variable you need to dereference the pointer to memory in the heap (it's a kind of jump), while for value types it's already on the stack or even optimized out to registers.

I think you see a difference because of this.

P.S. btw, by "most of the time are" I meant boxing; it's a technique used to place value type objects on the heap (e.g. to cast value types to an interface or for dynamic method call binding).

Body:
I have three cases to test the relative performance of classes, classes with inheritence and structs. These are to be used for tight  loops so performance counts. Dot products are used as part of many algorithms in 2D and 3D geometry and I have run the profiler on real code. The below tests are indicative of real world performance problems I have seen.

The results for 100000000 times through the loop and application of the dot product gives

ControlA 208 ms   ( class with inheritence )
ControlB 201 ms   ( class with no inheritence )
ControlC 85  ms   ( struct )

The tests were being run without debugging and optimization turned on. My question is, what is it about classes in this case that cause them to be so slow?

I presumed the JIT would still be able to inline all the calls, class or struct, so in effect the results should be identical. Note that if I disable optimizations then my results are identical.

ControlA 3239
ControlB 3228
ControlC 3213

They are always within 20ms of each other if the test is re-run.

The classes under investigation

using System;
using System.Diagnostics;

public class PointControlA
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public PointControlA(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public class Point3ControlA : PointControlA
{
    public double Z
    {
        get;
        set;
    }

    public Point3ControlA(double x, double y, double z): base (x, y)
    {
        Z = z;
    }

    public static double Dot(Point3ControlA a, Point3ControlA b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public class Point3ControlB
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlB(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlB a, Point3ControlB b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public struct Point3ControlC
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlC(double x, double y, double z):this()
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlC a, Point3ControlC b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

Test Script

public class Program
{
    public static void TestStructClass()
    {
        var vControlA = new Point3ControlA(11, 12, 13);
        var vControlB = new Point3ControlB(11, 12, 13);
        var vControlC = new Point3ControlC(11, 12, 13);
        var sw = Stopwatch.StartNew();
        var n = 10000000;
        double acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }

        Console.WriteLine("ControlA " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlB.Dot(vControlB, vControlB);
        }

        Console.WriteLine("ControlB " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

        Console.WriteLine("ControlC " + sw.ElapsedMilliseconds);
    }

    public static void Main()
    {
        TestStructClass();
    }
}

This dotnet fiddle is proof of compilation only. It does not show the performance differences.

I am trying to explain to a vendor why their choice to use classes instead of structs for small numeric types is a bad idea. I now have the test case to prove it but I can't understand why.

NOTE : I have tried to set a breakpoint in the debugger with JIT optimizations turned on but the debugger will not break. Looking at the IL with JIT optimizations turned off doesn't tell me anything.

EDIT

After the answer by @pkuderov I took his code and played with it. I changed the code and found that if I forced inlining via

   [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static double Dot(Point3Class a)
    {
        return a.X * a.X + a.Y * a.Y + a.Z * a.Z;
    }

the difference between the struct and class for dot product vanished. Why with some setups the attribute is not needed but for me it was is not clear. However I did not give up. There is still a performance problem with the vendor code and I think the DotProduct is not the best example.

I modified @pkuderov's code to implement Vector Add which will create new instances of the structs and classes. The results are here

https://gist.github.com/bradphelan/9b383c8e99edc38068fcc0dccc8a7b48

In the example I also modifed the code to pick a pseudo random vector from an array to avoid the problem of the instances sticking in the registers ( I hope ).

The results show that:

DotProduct performance is identical or maybe faster for classes

Vector Add, and I assume anything that creates a new object is slower.

Add class/class             2777ms
Add struct/struct           2457ms

DotProd class/class         1909ms
DotProd struct/struct       2108ms

The full code and results are here if anybody wants to try it out.

Edit Again

For the vector add example where an array of vectors is summed together the struct version keeps the accumulator in 3 registers

 var accStruct = new Point3Struct(0, 0, 0);
 for (int i = 0; i < n; i++)
     accStruct = Point3Struct.Add(accStruct, pointStruct[(i + 1) % m]);

the asm body is

// load the next vector into a register
00007FFA3CA2240E  vmovsd      xmm3,qword ptr [rax]
00007FFA3CA22413  vmovsd      xmm4,qword ptr [rax+8]
00007FFA3CA22419  vmovsd      xmm5,qword ptr [rax+10h]
// Sum the accumulator (the accumulator stays in the registers )
00007FFA3CA2241F  vaddsd      xmm0,xmm0,xmm3
00007FFA3CA22424  vaddsd      xmm1,xmm1,xmm4
00007FFA3CA22429  vaddsd      xmm2,xmm2,xmm5

but for class based vector version it reads and writes out the accumulator each time to main memory which is inefficient

var accPC = new Point3Class(0, 0, 0);
for (int i = 0; i < n; i++)
    accPC = Point3Class.Add(accPC, pointClass[(i + 1) % m]);

the asm body is

// Read and add both accumulator X and Xnext from main memory
00007FFA3CA2224A  vmovsd      xmm0,qword ptr [r14+8]
00007FFA3CA22250  vmovaps     xmm7,xmm0
00007FFA3CA22255  vaddsd      xmm7,xmm7,mmword ptr [r12+8]

// Read and add both accumulator Y and Ynext from main memory
00007FFA3CA2225C  vmovsd      xmm0,qword ptr [r14+10h]
00007FFA3CA22262  vmovaps     xmm8,xmm0
00007FFA3CA22267  vaddsd      xmm8,xmm8,mmword ptr [r12+10h]

// Read and add both accumulator Z and Znext from main memory
00007FFA3CA2226E  vmovsd      xmm9,qword ptr [r14+18h]
00007FFA3CA22283  vmovaps     xmm0,xmm9
00007FFA3CA22288  vaddsd      xmm0,xmm0,mmword ptr [r12+18h]

// Move accumulator accumulator X,Y,Z back to main memory.
00007FFA3CA2228F  vmovsd      qword ptr [rax+8],xmm7
00007FFA3CA22295  vmovsd      qword ptr [rax+10h],xmm8
00007FFA3CA2229B  vmovsd      qword ptr [rax+18h],xmm0


问:
How to print a list of release versions next to the product in C# .net mvc 5?
Suppose I have a database like this

```<code>Product  Version
a          1.2
a          1.3
a          1.4
a          1.5
b          1.1
b          1.2
c          1.0
</code>```

I want to print this in the view as

```<code>**a** 1.2, 1.3, 1.4 1.5
**b** 1.1, 1.2
**c** 1.0
</code>```

I am able to get the product and version next to each other but in the data base format. How to I print the output as desired. Please help

答:
```<code>   List<ProductVersion> Products=
        listOfProducts.GroupBy(x=>x.Product)
        .Select(y=>new ProductVersion{
            productId = y.Key
        ,   version = y.SelectMany(x=>x. version).ToList()
        });
</code>```

Body:
Suppose I have a database like this

Product  Version
a          1.2
a          1.3
a          1.4
a          1.5
b          1.1
b          1.2
c          1.0

I want to print this in the view as

**a** 1.2, 1.3, 1.4 1.5
**b** 1.1, 1.2
**c** 1.0

I am able to get the product and version next to each other but in the data base format. How to I print the output as desired. Please help


问:
EditText is not showing hint as well as text when typing
EditText is not showing hint as well as text when typing.
Here is code:

```<code><EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>
</code>```

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.

答: Just increase the height value or set it to wrap_content. You are setting height too small so text is not visible to you. You can use hint and text properties at the same time. There is no issue with that .

Body:
EditText is not showing hint as well as text when typing.
Here is code:

<EditText
        android:id="@+id/passwordText"
        android:layout_width="135dp"
        android:layout_height="18dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="46dp"
        android:hint="Enter your password."
        android:text="Enter password"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/emailText"
        tools:text="Enter Password"/>

I also tried to set color by code but it didn't worked:

final EditText passwordText = (EditText)
  findViewById(R.id.passwordText);
          passwordText.setTextColor(Color.BLACK);
          passwordText.setHint("Enter your Password.");
          passwordText.setHintTextColor(Color.BLACK);

Note: I'm using android studio 2.3.3;

Any help will be appreciated.