问:
Android Java Viewpager loads in the same viewPager view position
I'm new in Java/Android programming.

I've got a Fragment with tabLayout and viewPager. This fragment get's a list of groupId/groupName from the server then needs to create one page for each groupId. It sends the value to the adapter (the fragment to show in the viewpager pages is always ContentRoster() but the groupId define the data to show)

My issue is that this ContentRoster() fragment only loads in position 0 of the viewpager. I can swipe and slect the tabs as expected, but all loads in the same view...

If I have two sets of groupId, the first one will load in position 0, then the second one groupId#2 (which is autoloaded to populate next view) update position 0 view and erase groupID#1 view.

```<code>    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);

        TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
        final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        tabLayout.setupWithViewPager(viewPager);

        AdapterViewPager mCustomPagerAdapter = new AdapterViewPager(getChildFragmentManager());

        //add Fragment with specific arguments
        for(int i = 0; i < result.size() ; i++) {
            mCustomPagerAdapter.addFragment(new ContentRoster(), (result.get(i)).get("groupname"), (result.get(i)).get("groupid") );
        }

        //Set adapter if not null
        if (viewPager != null) {
            viewPager.setAdapter(mCustomPagerAdapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }
        });

    }
</code>```

The adapter looks like this :

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AdapterViewPager extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    private final List<String> mFragmentParamsList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title, String params) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
        mFragmentParamsList.add(params);
    }

    public AdapterViewPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        String groupId = mFragmentParamsList.get(position);
        Fragment fragment = ContentRoster.newInstance(groupId);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}
</code>```

and the ContentRoster() Fragment is like this :
I retrieve the groupId from the bundle and 'LoadRosterList().execute(groupId)' charge the data and show only the groupId data in line with the selected tab.

```<code>   public static ContentRoster newInstance(String groupId) {
        ContentRoster ContentRoster = new ContentRoster();

        Bundle args = new Bundle();
        args.putString("groupId", groupId);
        ContentRoster.setArguments(args);

        return ContentRoster;
    }

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

        View view = inflater.inflate(R.layout.content_listview, container, false);

        Bundle args = getArguments();
        groupId = args.getString("groupId");

        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        new LoadRosterList().execute(groupId);

        return view;
    }
</code>```

UPDATE :
Could this be link to the last part where I update the listview in the ContentRoster Fragment (which is shown in the viewPager)
As I get the listview Id from the activity?

```<code>protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
    super.onPostExecute(result);

    try {
        // Getting adapter by passing xml data ArrayList
        ListView mListView;
        mListView = (ListView) getActivity().findViewById(R.id.listView);

        AdapterRoster adapter = new AdapterRoster(getActivity().getApplicationContext(), result);
        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        progressBar.setVisibility(View.GONE); //Effacage du Progress Bar

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                // Send intent to SingleViewActivity
                Intent i = new Intent(getActivity().getApplicationContext(), ActivitySingleGuardian.class);
                // Pass image index
                i.putExtra("psnid", ((TextView) v.findViewById(R.id.psnid)).getText().toString());
                i.putExtra("rank", ((TextView) v.findViewById(R.id.rank)).getText().toString());
                i.putExtra("lastplay", ((TextView) v.findViewById(R.id.lastplay)).getText().toString());
                i.putExtra("bungiename", ((TextView) v.findViewById(R.id.bungiename)).getText().toString());
                i.putExtra("bungieid", ((TextView) v.findViewById(R.id.bungieid)).getText().toString());
                i.putExtra("picpath", ((TextView) v.findViewById(R.id.picpath)).getText().toString());
                i.putExtra("membershipType", ((TextView) v.findViewById(R.id.membershipType)).getText().toString());
                startActivity(i);
            }
        });

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}
</code>```

答:
Alright, you're close, but not yet there.

In your onPostExecute method, consider changing the last line from:

```<code>viewPager.setAdapter(mCustomPagerAdapter);
</code>```

to something like:

```<code>if (viewPager != null) {
        viewPager.setAdapter(mCustomPagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (viewPager != null) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        if (viewPager != null) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    }
});
</code>```

this would result in removing this line as well (more like moving it and adding to it):

```<code>tabLayout.addOnTabSelectedListener(onTabSelectedListener(viewPager));
</code>```

Hope this helps!

Body:
I'm new in Java/Android programming.

I've got a Fragment with tabLayout and viewPager. This fragment get's a list of groupId/groupName from the server then needs to create one page for each groupId. It sends the value to the adapter (the fragment to show in the viewpager pages is always ContentRoster() but the groupId define the data to show)

My issue is that this ContentRoster() fragment only loads in position 0 of the viewpager. I can swipe and slect the tabs as expected, but all loads in the same view...

If I have two sets of groupId, the first one will load in position 0, then the second one groupId#2 (which is autoloaded to populate next view) update position 0 view and erase groupID#1 view.

    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);

        TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
        final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        tabLayout.setupWithViewPager(viewPager);

        AdapterViewPager mCustomPagerAdapter = new AdapterViewPager(getChildFragmentManager());

        //add Fragment with specific arguments
        for(int i = 0; i < result.size() ; i++) {
            mCustomPagerAdapter.addFragment(new ContentRoster(), (result.get(i)).get("groupname"), (result.get(i)).get("groupid") );
        }

        //Set adapter if not null
        if (viewPager != null) {
            viewPager.setAdapter(mCustomPagerAdapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }
        });

    }

The adapter looks like this :

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AdapterViewPager extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    private final List<String> mFragmentParamsList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title, String params) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
        mFragmentParamsList.add(params);
    }

    public AdapterViewPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        String groupId = mFragmentParamsList.get(position);
        Fragment fragment = ContentRoster.newInstance(groupId);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}

and the ContentRoster() Fragment is like this :
I retrieve the groupId from the bundle and 'LoadRosterList().execute(groupId)' charge the data and show only the groupId data in line with the selected tab.

   public static ContentRoster newInstance(String groupId) {
        ContentRoster ContentRoster = new ContentRoster();

        Bundle args = new Bundle();
        args.putString("groupId", groupId);
        ContentRoster.setArguments(args);

        return ContentRoster;
    }

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

        View view = inflater.inflate(R.layout.content_listview, container, false);

        Bundle args = getArguments();
        groupId = args.getString("groupId");

        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        new LoadRosterList().execute(groupId);

        return view;
    }

UPDATE :
Could this be link to the last part where I update the listview in the ContentRoster Fragment (which is shown in the viewPager)
As I get the listview Id from the activity?

protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
    super.onPostExecute(result);

    try {
        // Getting adapter by passing xml data ArrayList
        ListView mListView;
        mListView = (ListView) getActivity().findViewById(R.id.listView);

        AdapterRoster adapter = new AdapterRoster(getActivity().getApplicationContext(), result);
        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        progressBar.setVisibility(View.GONE); //Effacage du Progress Bar

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                // Send intent to SingleViewActivity
                Intent i = new Intent(getActivity().getApplicationContext(), ActivitySingleGuardian.class);
                // Pass image index
                i.putExtra("psnid", ((TextView) v.findViewById(R.id.psnid)).getText().toString());
                i.putExtra("rank", ((TextView) v.findViewById(R.id.rank)).getText().toString());
                i.putExtra("lastplay", ((TextView) v.findViewById(R.id.lastplay)).getText().toString());
                i.putExtra("bungiename", ((TextView) v.findViewById(R.id.bungiename)).getText().toString());
                i.putExtra("bungieid", ((TextView) v.findViewById(R.id.bungieid)).getText().toString());
                i.putExtra("picpath", ((TextView) v.findViewById(R.id.picpath)).getText().toString());
                i.putExtra("membershipType", ((TextView) v.findViewById(R.id.membershipType)).getText().toString());
                startActivity(i);
            }
        });

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

Body:
Alright, you're close, but not yet there.

In your onPostExecute method, consider changing the last line from:

viewPager.setAdapter(mCustomPagerAdapter);

to something like:

if (viewPager != null) {
        viewPager.setAdapter(mCustomPagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (viewPager != null) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        if (viewPager != null) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    }
});

this would result in removing this line as well (more like moving it and adding to it):

tabLayout.addOnTabSelectedListener(onTabSelectedListener(viewPager));

Hope this helps!


来源: stackexchange

问:
Values are duplicated in Rails form for PostgreSQL array
If I save an array to the database, it is persisted properly, but when I look at the form, it puts concatenated values in the array in all array input fields.

E.g. in the form below I have 2 input fields, so you can store 2 nicknames for a Pet inside the array column. I put "a" in field 1 and "b" in field 2 and press save. I inspect in the Rails console and it's stored correctly: nicknames: ["a", "b"]. But when I open up the form, both input fields contain "a b". So the values are concatenated somehow. What am I doing wrong?

To reproduce:

```<code>rails g scaffold Pets
</code>```

Then in the new migration:

```<code>class CreatePets < ActiveRecord::Migration
  def change
    create_table :pets do |t|
      t.string :nicknames, array: true
      t.timestamps null: false
    end
  end
end
</code>```

In the controller:

```<code>def pet_params
  params[:pet].permit(nicknames: [])
end
</code>```

In the form:

```<code><%= simple_form_for(@pet) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
</code>```

Create a new Pet with nicknames "a" and "b". Go to edit the Pet and the inputs now contain "a b" and "a b", but it's stored as 'nicknames: ["a", "b"]' in the database according to the Rails console.

答:
Check if @pet.persisted

if yes, loop through the values and display.

if no, do as you do always for new.

```<code><div class="form-inputs">
  <% if @pet.persisted? && (@pet.nicknames.length > 0) %>
    <% @pet.nicknames.each do |nickname| %>
        <%= f.text_field :nicknames, name: 'pet[nicknames][]', value: nickname %>
    <% end %>
  <% else %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  <% end %>
</div>
</code>```

Here is the documentation for persisted?

ContentLicense: CC BY-SA 3.0

Body:
If I save an array to the database, it is persisted properly, but when I look at the form, it puts concatenated values in the array in all array input fields.

E.g. in the form below I have 2 input fields, so you can store 2 nicknames for a Pet inside the array column. I put "a" in field 1 and "b" in field 2 and press save. I inspect in the Rails console and it's stored correctly: nicknames: ["a", "b"]. But when I open up the form, both input fields contain "a b". So the values are concatenated somehow. What am I doing wrong?

To reproduce:

rails g scaffold Pets

Then in the new migration:

class CreatePets < ActiveRecord::Migration
  def change
    create_table :pets do |t|
      t.string :nicknames, array: true
      t.timestamps null: false
    end
  end
end

In the controller:

def pet_params
  params[:pet].permit(nicknames: [])
end

In the form:

<%= simple_form_for(@pet) do |f| %>
  <%= f.error_notification %>

    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>

    <%= f.button :submit %>

<% end %>

Create a new Pet with nicknames "a" and "b". Go to edit the Pet and the inputs now contain "a b" and "a b", but it's stored as 'nicknames: ["a", "b"]' in the database according to the Rails console.

Body:
Check if @pet.persisted

if yes, loop through the values and display.

if no, do as you do always for new.

<div class="form-inputs">
  <% if @pet.persisted? && (@pet.nicknames.length > 0) %>
    <% @pet.nicknames.each do |nickname| %>
        <%= f.text_field :nicknames, name: 'pet[nicknames][]', value: nickname %>
    <% end %>
  <% else %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  <% end %>
</div>

Here is the documentation for persisted?


问:
retrieving json data fails in php
I'm sending json data to my php and then want to receive data back to my Jquery.ajax success but getting null value.

My code snippet:

```<code>$.ajax({
    type: "POST",
    contentType: "application/json",
    url: postUrl,
    data: queryString,
    dataType: "json",
    success:function(data){
        switch(action) {
          case "edit":
          jsonData = data;
          $("#custEmail").val(jsonData[0].custEmail);
    break;
    //some more code
  }
});
</code>```

In my php i am using this to retrieve data:

```<code>$jsonData = $_POST['action'];
echo $jsonData;
</code>```

Edit:

I see lot of fuss here. Json data which i am sending is

```<code>queryString = '{"action":"' + action+ '", "checkId":"' + id+ '"}';
</code>```

and i am unable to receive using $_POST method.

答:
To receive json post data safest way to use is file_get_contents("php://input").

use:

```<code>$jsonData = json_decode(file_get_contents("php://input")); //get json data
$data = $jsonData->yourdata;
</code>```

Title: retrieving json data fails in php

Body:
I'm sending json data to my php and then want to receive data back to my Jquery.ajax success but getting null value.

My code snippet:

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: postUrl,
    data: queryString,
    dataType: "json",
    success:function(data){
        switch(action) {
          case "edit":
          jsonData = data;
          $("#custEmail").val(jsonData[0].custEmail);
    break;
    //some more code
  }
});

In my php i am using this to retrieve data:

$jsonData = $_POST['action'];
echo $jsonData;

Edit:

I see lot of fuss here. Json data which i am sending is

queryString = '{"action":"' + action+ '", "checkId":"' + id+ '"}';

and i am unable to receive using $_POST method.

Body:
To receive json post data safest way to use is file_get_contents("php://input").

use:

$jsonData = json_decode(file_get_contents("php://input")); //get json data
$data = $jsonData->yourdata;


问:
app-release-unsigned.apk is not signed
I downloaded the zip file of an Android app on github and I'm trying to run it, but I get a dialog with this message

```<code>app-release-unsigned.apk is not signed. Please configure the signing information for the selected flavor using the Project Structure dialog.
</code>```

I'm using Android Studio.
What am I supposed to do?

答:
In  tool window bar select Build Variants
Change Build Variant from Release to Debug</p>

Title: app-release-unsigned.apk is not signed

Body:
I downloaded the zip file of an Android app on github and I'm trying to run it, but I get a dialog with this message

app-release-unsigned.apk is not signed. Please configure the signing information for the selected flavor using the Project Structure dialog.

I'm using Android Studio.
What am I supposed to do?


问:
need help - IWindowsFormsEditorService in WPF? or possible another alternative solution to my issue
I've taken the following code and extended it to my code:

http://www.codeproject.com/KB/vb/PropertyGridEx.aspx

My code is a program written in WPF while the example is in Windows Forms Application

My code-

http://pastebin.com/phshqYwY

My problem-

the "IWindowsFormsEditorService" is only for UserControl windows that made by Windows Forms Application so the following row:

```<code>wfes.DropDownControl(ucUseValue);
</code>```

Shows the following errors:

Error   1   The best overloaded method match for 'System.Windows.Forms.Design.IWindowsFormsEditorService.DropDownControl(System.Windows.Forms.Control)' has some invalid arguments

Error   2   Argument 1: cannot convert from 'Visual_Command_Line.UserControls.ArgumentEditor.UseValueArg' to 'System.Windows.Forms.Control'

So, i thought of two Solutions - tell me if one of them is possible:

Is there any alternative to "IWindowsFormsEditorService" in WPF?

Is there any possible way to convert my UserControl which is "UseValueArg" to a System.Windows.Forms.UserControl type of UserControl?

Creating a UserControl that is of type System.Windows.Forms.Control and not of WPF (something which I already tried and it works, though it's seems stupid to have Windows Forms Application in a WPF)

Thanks in advanced,
Din

答: Though my answer is a little 'off' in the topic, you might want to try: http://wpg.codeplex.com/</p>

Body:
I've taken the following code and extended it to my code:

http://www.codeproject.com/KB/vb/PropertyGridEx.aspx

My code is a program written in WPF while the example is in Windows Forms Application

My code-

http://pastebin.com/phshqYwY

My problem-

the "IWindowsFormsEditorService" is only for UserControl windows that made by Windows Forms Application so the following row:

wfes.DropDownControl(ucUseValue);

Shows the following errors:

Error   1   The best overloaded method match for 'System.Windows.Forms.Design.IWindowsFormsEditorService.DropDownControl(System.Windows.Forms.Control)' has some invalid arguments

Error   2   Argument 1: cannot convert from 'Visual_Command_Line.UserControls.ArgumentEditor.UseValueArg' to 'System.Windows.Forms.Control'

So, i thought of two Solutions - tell me if one of them is possible:

Is there any alternative to "IWindowsFormsEditorService" in WPF?

Is there any possible way to convert my UserControl which is "UseValueArg" to a System.Windows.Forms.UserControl type of UserControl?

Creating a UserControl that is of type System.Windows.Forms.Control and not of WPF (something which I already tried and it works, though it's seems stupid to have Windows Forms Application in a WPF)

Thanks in advanced,
Din

ContentLicense: CC BY-SA 2.5


问:
Cache configurations of FluentNHibernate?
I'm using FluentNhibernate version 2.0.3.0 and I'm trying to configure the cache of it to use with queries, I'm using HQL. I want to one opinion if I did all configurations alright, and I want to know how could I see if cache was activate ?

Connection

```<code>FluentConfiguration _config = Fluently.Configure()
    .Database(
        MySQLConfiguration.Standard.ConnectionString(
            x => x.Server(HOST)
                  .Username(USER)
                  .Password(PASSWORD)
                  .Database(DB)))
    .Cache(c => c.ProviderClass(typeof(NHibernate.Cache.HashtableCacheProvider).AssemblyQualifiedName)
                 .UseQueryCache())
    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UsuarioMap>())
    .ExposeConfiguration(cfg => new SchemaUpdate(cfg)
    .Execute(false, true));
</code>```

Mapping

```<code>public class UsuarioMap : ClassMap<Usuario> {
    public UsuarioMap() {
        Table("USUARIOS");
        Cache.ReadWrite();
        Id(u => u.id).GeneratedBy.Native();
        Map(u => u.nome).Not.Nullable().Length(50);
        Map(u => u.email).Unique().Not.Nullable().Length(255);
        Map(u => u.senha).Not.Nullable();
        Map(u => u.status).CustomType<int>();
        Map(u => u.dtCadastro).CustomType<DateTime>();
        Map(u => u.dtLastLogin).CustomType<DateTime>();
        Map(u => u.tipo).CustomType<int>();
        Map(u => u.imagem);
        Map(u => u.loginBy).CustomType<int>();
        Map(u => u.idFacebook);
    }
}
</code>```

HQL Query

```<code>public class UsuarioDAO : GenericDAO<Usuario>{

    /** retorna todos os objetos */
    public IList<Usuario> findAll(){
        ISession _session = getSession();
        IList<Usuario> list = _session.CreateQuery("FROM Usuario u ORDER BY u.nome")
            .SetCacheable(true).SetCacheMode(CacheMode.Normal)
            .List<Usuario>();
        return list;
    }
</code>```

答:
A UseSecondLevelCache call is very likely missing (xml configuration parameter cache.use_second_level_cache).

HashtableCacheProvider is not intended for production use, only for test. Choose another one.

Transactions do not seem used. At first data change done outside of a transaction, the second level cache will be disabled. Better transacted all session usages.

A cache.default_expiration should be configured. This is an integer, in seconds.

You may use session statistics to check if the cache is used. Enable them on the session factory.

```<code>sessionFactory.Statistics.IsStatisticsEnabled = true;

// Do your stuff then consult the statistics on the session factory.
</code>```

Avoid letting them enabled in production, this incurs some overhead.

Additional notes:

If you have some mapped collection you wish to cache, you will have to enable caching for them in their mapping.

Caching works better with lazy-loading. Eager loading may cause cached entities to be reloaded from database instead of being loaded from cache.

Body:
I'm using FluentNhibernate version 2.0.3.0 and I'm trying to configure the cache of it to use with queries, I'm using HQL. I want to one opinion if I did all configurations alright, and I want to know how could I see if cache was activate ?

Connection

FluentConfiguration _config = Fluently.Configure()
    .Database(
        MySQLConfiguration.Standard.ConnectionString(
            x => x.Server(HOST)
                  .Username(USER)
                  .Password(PASSWORD)
                  .Database(DB)))
    .Cache(c => c.ProviderClass(typeof(NHibernate.Cache.HashtableCacheProvider).AssemblyQualifiedName)
                 .UseQueryCache())
    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UsuarioMap>())
    .ExposeConfiguration(cfg => new SchemaUpdate(cfg)
    .Execute(false, true));

Mapping

public class UsuarioMap : ClassMap<Usuario> {
    public UsuarioMap() {
        Table("USUARIOS");
        Cache.ReadWrite();
        Id(u => u.id).GeneratedBy.Native();
        Map(u => u.nome).Not.Nullable().Length(50);
        Map(u => u.email).Unique().Not.Nullable().Length(255);
        Map(u => u.senha).Not.Nullable();
        Map(u => u.status).CustomType<int>();
        Map(u => u.dtCadastro).CustomType<DateTime>();
        Map(u => u.dtLastLogin).CustomType<DateTime>();
        Map(u => u.tipo).CustomType<int>();
        Map(u => u.imagem);
        Map(u => u.loginBy).CustomType<int>();
        Map(u => u.idFacebook);
    }
}

HQL Query

public class UsuarioDAO : GenericDAO<Usuario>{

    /** retorna todos os objetos */
    public IList<Usuario> findAll(){
        ISession _session = getSession();
        IList<Usuario> list = _session.CreateQuery("FROM Usuario u ORDER BY u.nome")
            .SetCacheable(true).SetCacheMode(CacheMode.Normal)
            .List<Usuario>();
        return list;
    }

Body:
A UseSecondLevelCache call is very likely missing (xml configuration parameter cache.use_second_level_cache).

HashtableCacheProvider is not intended for production use, only for test. Choose another one.

Transactions do not seem used. At first data change done outside of a transaction, the second level cache will be disabled. Better transacted all session usages.

A cache.default_expiration should be configured. This is an integer, in seconds.

You may use session statistics to check if the cache is used. Enable them on the session factory.

sessionFactory.Statistics.IsStatisticsEnabled = true;

// Do your stuff then consult the statistics on the session factory.

Avoid letting them enabled in production, this incurs some overhead.

Additional notes:

If you have some mapped collection you wish to cache, you will have to enable caching for them in their mapping.

Caching works better with lazy-loading. Eager loading may cause cached entities to be reloaded from database instead of being loaded from cache.


问:
how to convert a mixed series to float
How can I convert following pandas series to floats:

```<code>s = pd.Series(['2,3', 5.1, '', '3.2'])
</code>```

I tried s.to_float() but got a ValueError: Unable to parse string "2,3" at position 0

答:
Cast the Series to str if necessary, then str.replace the comma with a decimal, then you can use to_numeric:

```<code>In[24]:
s = pd.to_numeric(s.astype(str).str.replace(',','.'))
s

Out[24]:
0    2.3
1    5.1
2    NaN
3    3.2
dtype: float64
</code>```

If the dtype of the Series is already str then the astype(str) step can be skipped, but I'm assuming you have a more complicated real dataset issue

Title: how to convert a mixed series to float

Body:
How can I convert following pandas series to floats:

s = pd.Series(['2,3', 5.1, '', '3.2'])

I tried s.to_float() but got a ValueError: Unable to parse string "2,3" at position 0

Body:
Cast the Series to str if necessary, then str.replace the comma with a decimal, then you can use to_numeric:

In[24]:
s = pd.to_numeric(s.astype(str).str.replace(',','.'))
s

Out[24]:
0    2.3
1    5.1
2    NaN
3    3.2
dtype: float64

If the dtype of the Series is already str then the astype(str) step can be skipped, but I'm assuming you have a more complicated real dataset issue


问:
Call one script from another (to make GUI wrapper for analysis)?
I'm not experienced in OOP nor am I a programmer by trade, so I apologize if this is something I should have been able to find. I currently have a python program which I have written to do some complex data analysis - it consists of functions and then script which calls those functions (no main sentinel etc. etc.). No classes or anything.

It would be really helpful if I could package analysis in one program, data visualization in another, et cetera, and then just call the programs I want from a GUI. Therefore I'm trying to write a simple GUI (in Tkinter) which will allow me to set some parameters and filepaths etc. before running that program.

I'm accustomed to other "languages" which encourage packaging different components of your programs as sub-programs which call each other. In python my functions either get really really long (tons of indentation, hard to maintain) or I end up with a million functions which call each other (tons of functions, hard to keep track of).

If I tried to do this all in one .py it would be very long with no organization. In the interest of saving time and complexity I would like to have the GUI program in one .py program, and have its widgets call other programs (or functions from them) as necessary. I have a feeling this is going to involve importing the functions of my analysis program and then calling them. How can I do this? Do any routines I want to call need to be packaged as functions and then imported somehow?

Essentially I'm trying to get away from having 10 levels of indentation. Any advice would be appreciated. I would also be interested in packaging this program in some sort of deployable fashion, but that might be well above my pay grade so to speak.

答:
It is usually preferred to have more shorter functions than one long function.

This gets harder to maintain the more functions there are. Because of this, you should put functions that belong together (e.g. all operate on some objects) into their own module (or class). E.g. if you have multiple functions that do some math, put them into a file math_utils.py. In your main script you can then do e.g. this (if you defined a cube root funciton in math_utils, of course):

```<code>from math_utils import cube_root
</code>```

This works, as long as the two scripts are in the same folder.

In the same vein you can create multiple files that hold utility functions. In addition to this, your functions should all have docstrings describing what they do and what the expect as parameters and what they return. This makes this a lot more maintainable. You should also add module docstrings that describe what the functions in each file do.

So you would have:

File math_utils.py

```<code>"""This module contains multiple utility functions performing some math"""

import math

def cube_root(x):
    """Return the cube root of the input `x`"""
    return pow(x, 1./3)

...
</code>```

Body:
It is usually preferred to have more shorter functions than one long function.

This gets harder to maintain the more functions there are. Because of this, you should put functions that belong together (e.g. all operate on some objects) into their own module (or class). E.g. if you have multiple functions that do some math, put them into a file math_utils.py. In your main script you can then do e.g. this (if you defined a cube root funciton in math_utils, of course):

from math_utils import cube_root

This works, as long as the two scripts are in the same folder.

In the same vein you can create multiple files that hold utility functions. In addition to this, your functions should all have docstrings describing what they do and what the expect as parameters and what they return. This makes this a lot more maintainable. You should also add module docstrings that describe what the functions in each file do.

So you would have:

File math_utils.py

"""This module contains multiple utility functions performing some math"""

import math

def cube_root(x):
    """Return the cube root of the input `x`"""
    return pow(x, 1./3)

...


问:
Background color seeping into body when expanded on height
I've got an angular application I'm working on right now that implements angular-pdf.

The controller and view work absolutely fine and the pdf is displayed just fine, with one problem. As the PDF is higher than the min-height of the module it expands the height of it.

This seems to make the background color into the color of the modules background.
Usually the background is grey-ish, but as the height expands the module's background color seems to seep into the body (the page is a placeholder. I have no affiliation with them!):

As you can see the background is different about 80% down the webpage.

I'd like to have the same background-color all the way down.

As it stands now I set the background-color in a stylesheet and refer to body:

```<code>body {
    background-color: #D2D5D3;
    -webkit-font-smoothing: antialiased;
}
</code>```

Other than that I do nothing with the body's background. The only other background I have is taken from md-content:

```<code><div ng-controller="pdfpageController as vm">
    <md-content id="pdfpage" layout-padding>
        <md-toolbar>
            <div class="md-toolbar-tools">
                <md-button class="md-primary md-raised" ng-click="goback()">
                    <md-icon md-svg-icon="../resources/img/arrow_left.svg"></md-icon>
                    <span class="orange"><b>Back</b></span>
                </md-button>
                <h2 flex md-truncate class="text-center">Shifts</h2>
            </div>
        </md-toolbar>
        <md-toolbar class="md-wan md-hue-2" style="border-top: 0.5px solid black">
            <h1>{{pdfName}}</h1>
        </md-toolbar>

            <ng-pdf template-url="app/views/partials/viewer.html" scale="page-fit"></ng-pdf>
            <canvas id="pdf-canvas"></canvas>d="test-canvas"></canvas>-->

        <hr />
        <div layout="row" layout-align="start center">
            <div class="container">
                <span><b>Signature:</b></span>
                <signature-pad accept="accept" clear="clear" height="220" width="568" dataurl="dataurl"></signature-pad>
                <div layout="row">
                    <md-button ng-model="signature" class="md-raised md-primary" ng-click="signature = accept()">Use signature</md-button>
                    <md-button ng-model="clearSig" class="md-warn md-raised md-hue-2" ng-click="clearSig = clear()">Clear signature</md-button>
                </div>
            </div>
        </div>

        <!--<iframe style="width: 400px; height: 400px;"></iframe>-->
    </md-content>
</div>
</code>```

Does anyone have a suggestion on how I stop the md-colors background from seeping into the body's background?

答:
Try the following:

```<code>html,body {
height: 100%;
}

#pdfpage {
height: auto !important;
min-height: 100%;
}
</code>```

I'm assuming that #pdfpage is the container element of the PDF viewer in this case.

Body:
I've got an angular application I'm working on right now that implements angular-pdf.

The controller and view work absolutely fine and the pdf is displayed just fine, with one problem. As the PDF is higher than the min-height of the module it expands the height of it.

This seems to make the background color into the color of the modules background.
Usually the background is grey-ish, but as the height expands the module's background color seems to seep into the body (the page is a placeholder. I have no affiliation with them!):

As you can see the background is different about 80% down the webpage.

I'd like to have the same background-color all the way down.

As it stands now I set the background-color in a stylesheet and refer to body:

body {
    background-color: #D2D5D3;
    -webkit-font-smoothing: antialiased;
}

Other than that I do nothing with the body's background. The only other background I have is taken from md-content:

    <md-content id="pdfpage" layout-padding>
        <md-toolbar>

                <md-button class="md-primary md-raised" ng-click="goback()">
                    <md-icon md-svg-icon="../resources/img/arrow_left.svg"></md-icon>
                    Back
                </md-button>

Shifts

        </md-toolbar>
        <md-toolbar class="md-wan md-hue-2" style="border-top: 0.5px solid black">

{{pdfName}}

        </md-toolbar>

            <ng-pdf template-url="app/views/partials/viewer.html" scale="page-fit"></ng-pdf>
            <canvas id="pdf-canvas"></canvas>d="test-canvas"></canvas>-->

                Signature:
                <signature-pad accept="accept" clear="clear" height="220" width="568" dataurl="dataurl"></signature-pad>

                    <md-button ng-model="signature" class="md-raised md-primary" ng-click="signature = accept()">Use signature</md-button>
                    <md-button ng-model="clearSig" class="md-warn md-raised md-hue-2" ng-click="clearSig = clear()">Clear signature</md-button>

    </md-content>

Does anyone have a suggestion on how I stop the md-colors background from seeping into the body's background?

Body:
Try the following:

html,body {
height: 100%;
}

#pdfpage {
height: auto !important;
min-height: 100%;
}

I'm assuming that #pdfpage is the container element of the PDF viewer in this case.


问:
VSTO support for VS 2015 community edition
I have installed VS 2015 community edition. I am looking forward to develop outlook add-in for outlook 2010 or on wards. I can't find any outlook add-in option in project template of VS. Any help would be highly appreciated.

答:
Luckily for you I ran into this recently and found this very helpful page.

How to install Office Developper Tools for VS Community Edition ? (sic)

Download and install Visual Studio 2015 Update3 Community

Download and Install Microsoft Web Platform Installer

Open Microsoft Web Platform Installer and search with “Office Tools”

Then install Microsoft Office Developer Tools Update2 for Visual Studio 2015

ContentLicense: CC BY-SA 4.0


问:
Select most recent increase in value column by ID
I am attempting a simple subset but am having a little trouble with simultaneously applying both of my conditions. I am looking to select, for each unique ID, the most recent record where the value column increased. For example, here is a simplified version of my data.

```<code>ID| Date | Value
A  1/1/17  100
A  1/2/17  185
A  1/3/17  40
A  1/4/17  100
A  1/5/17  30
B  1/3/17  40
B  1/4/17  30
B  1/5/17  65
B  1/6/17  80
B  1/7/17  0
B  1/8/17  0
</code>```

While my desired output would be the row where the last increase of Value took place for each ID

```<code>ID| Date | Value
A  1/4/17  100
A  1/6/17  80
</code>```

Does anybody have some insight on how I can achieve my desired output? Thanks.

答:
Two steps:

```<code>select t.*
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from (select t.*,
                   max(value) over (partition by id order by date rows between 1 preceding and 1 preceding) as prev_value
            from t
           ) t
      where prev_value < value
     ) t
where seqnum = 1;
</code>```

In Teradata, you can also use qualify to remove one level of subqueries.

Body:
I am attempting a simple subset but am having a little trouble with simultaneously applying both of my conditions. I am looking to select, for each unique ID, the most recent record where the value column increased. For example, here is a simplified version of my data.

ID| Date | Value
A  1/1/17  100
A  1/2/17  185
A  1/3/17  40
A  1/4/17  100
A  1/5/17  30
B  1/3/17  40
B  1/4/17  30
B  1/5/17  65
B  1/6/17  80
B  1/7/17  0
B  1/8/17  0

While my desired output would be the row where the last increase of Value took place for each ID

ID| Date | Value
A  1/4/17  100
A  1/6/17  80

Does anybody have some insight on how I can achieve my desired output? Thanks.

Body:
Two steps:

select t.*
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from (select t.*,
                   max(value) over (partition by id order by date rows between 1 preceding and 1 preceding) as prev_value
            from t
           ) t
      where prev_value < value
     ) t
where seqnum = 1;

In Teradata, you can also use qualify to remove one level of subqueries.


问:
Get thumbnail image of video from video url
Is it possible to get the thumbnail image from a video Url? I need to thumbnails of videos in a list view.</p>

答:
It's very important to identify the components of a problem. I'd actually say you have two separate problems:

Downloading a file from an URL.

Creating a thumbnail image from an incomplete video file.

Look into those two separately, you'll find plenty of information.


问:
Braintree Drop-In UI in ASP.NET web form with submit button method is not called when clicked
I have created a simple payment form where contains fields that accept amount, the drop-in UI and the submit button.

```<code><form id="form1" runat="server">
<div>
  <label>Amount:</label>
  <asp:TextBox ID="txtAmount" runat="server" />
</div>
<div id="dropin-container"></div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
  braintree.setup("<%= this.ClientToken %>", "dropin", { container: "dropin-container" });
</script>
</code>```

and the code behind

```<code>protected string ClientToken = String.Empty;

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GenerateClientToken();
    }
}

protected void GenerateClientToken()
{
    var gateway = new BraintreeGateway
    {
        Environment = Braintree.Environment.SANDBOX,
        MerchantId = "merchant-id",
        PublicKey = "public-key",
        PrivateKey = "private-key"
    };

    this.ClientToken = gateway.ClientToken.generate();
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    var gateway = new BraintreeGateway
    {
        Environment = Braintree.Environment.SANDBOX,
        MerchantId = "merchant-id",
        PublicKey = "public-key",
        PrivateKey = "private-key"
    };

    var request = new TransactionRequest
    {
        Amount = Convert.ToDecimal(this.txtAmount.Text),
        PaymentMethodNonce = Request.Form["payment_method_nonce"]
    };

    Result<Transaction> result = gateway.Transaction.Sale(request);
}
</code>```

After I load the page in the browser, I can see the form that accept amount and also the drop-in ui form which accept credit card and/or PayPal.

The issue is when I click Submit button, the method btnSubmit_Click doesn't get called. The page looks like it post back correctly but I cannot see any line of code within the btnSubmit_Click is executed.

I follow the instruction from this page:
https://www.braintreepayments.com/features/drop-in

But I really can't think of anything that I miss.

Anyone can help me with this issue would be very appreciated. Thank you so much.

Knott

答:
You just needed to put your transaction request code in a method and then call that sub on a post back rather than page load.

This way the auto submit won't interrupt with things.

```<code>Protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
    GetClientToken();
} else {
    Pay();
}
}

protected void Pay() {
    PaymentMethodNonce = Request.Form["payment_method_nonce"]
    //Build request string etc.
}
</code>```

Body:
I have created a simple payment form where contains fields that accept amount, the drop-in UI and the submit button.

<form id="form1" runat="server">

  Amount:
  <asp:TextBox ID="txtAmount" runat="server" />

<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />

and the code behind

protected string ClientToken = String.Empty;

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GenerateClientToken();
    }
}

protected void GenerateClientToken()
{
    var gateway = new BraintreeGateway
    {
        Environment = Braintree.Environment.SANDBOX,
        MerchantId = "merchant-id",
        PublicKey = "public-key",
        PrivateKey = "private-key"
    };

    this.ClientToken = gateway.ClientToken.generate();
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    var gateway = new BraintreeGateway
    {
        Environment = Braintree.Environment.SANDBOX,
        MerchantId = "merchant-id",
        PublicKey = "public-key",
        PrivateKey = "private-key"
    };

    var request = new TransactionRequest
    {
        Amount = Convert.ToDecimal(this.txtAmount.Text),
        PaymentMethodNonce = Request.Form["payment_method_nonce"]
    };

    Result<Transaction> result = gateway.Transaction.Sale(request);
}

After I load the page in the browser, I can see the form that accept amount and also the drop-in ui form which accept credit card and/or PayPal.

The issue is when I click Submit button, the method btnSubmit_Click doesn't get called. The page looks like it post back correctly but I cannot see any line of code within the btnSubmit_Click is executed.

I follow the instruction from this page:
https://www.braintreepayments.com/features/drop-in

But I really can't think of anything that I miss.

Anyone can help me with this issue would be very appreciated. Thank you so much.

Knott

Body:
You just needed to put your transaction request code in a method and then call that sub on a post back rather than page load.

This way the auto submit won't interrupt with things.

Protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
    GetClientToken();
} else {
    Pay();
}
}

protected void Pay() {
    PaymentMethodNonce = Request.Form["payment_method_nonce"]
    //Build request string etc.
}


问:
How to get Sampler Body data from beanshell Pre-Processor - JMeter
I have Http Sampler body as follows,
{"Uname":"admin","Signature":"${Sign}","LoginTime":"${LogTime}","Action":"Do_Action"}

I have to get the value of "Action" from the above body, and that value nned to be sent to Pre-processor which will be useful to do further action.

Help me out of this...!!

Thanks!

答:
I would recommend switching to JSR223 PreProcessor and Groovy language as:

Groovy has built-in JSON support

Groovy performs much better than Beanshell

Example Groovy code to extract "Action" from the request body and store it into ${action} JMeter Variable will look like:

```<code>def body = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
vars.put('action', body.Action)
</code>```

See Groovy is the New Black article for more details.

Body:
I would recommend switching to JSR223 PreProcessor and Groovy language as:

Groovy has built-in JSON support

Groovy performs much better than Beanshell

Example Groovy code to extract "Action" from the request body and store it into ${action} JMeter Variable will look like:

def body = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
vars.put('action', body.Action)

See Groovy is the New Black article for more details.


问:
how to send json data to server and get Json response in android?
how to send json data to server and get json response in android using HttpURLConnection (get, post, put, delete)?
the url like = http://maxxapi.webname.com/oauth/token_access</p>

答:
Note : Since question doesn't ask for a specific error, this is a simple basic code to show how to send JSON data to a server (given IP)

Lets assume that we have 3 text fields with f_name, l_name, age & also a button which will trigger onClick method on button press.

Below is the code

This should be in the activity which the button is in.

```<code>public void onClick(View v) {
    JSONObject payLoad = new JSONObject();
    try {
        payLoad.put("first_name", f_name.getText().toString());
        payLoad.put("last_name", l_name.getText().toString());
        payLoad.put("age", age.getText().toString());

        new SendPostRequest.execute("http://123.456.789.78:8080/address1/address2", postData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

This is a new Class that responsible for send the response.

```<code>private class SendPostRequest extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String postData = "";

        HttpURLConnection httpConnection= null;
        try {

            httpConnection= (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            DataOutputStream outputStream= new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.writeBytes("PostData=" + params[1]);
            outputStream.flush();
            outputStream.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char currentData = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                postData += currentData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpConnection!= null) {
                httpURLConnection.disconnect();
            }
        }
        return postData;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}
</code>```

Body:
Note : Since question doesn't ask for a specific error, this is a simple basic code to show how to send JSON data to a server (given IP)

Lets assume that we have 3 text fields with f_name, l_name, age & also a button which will trigger onClick method on button press.

Below is the code

This should be in the activity which the button is in.

public void onClick(View v) {
    JSONObject payLoad = new JSONObject();
    try {
        payLoad.put("first_name", f_name.getText().toString());
        payLoad.put("last_name", l_name.getText().toString());
        payLoad.put("age", age.getText().toString());

        new SendPostRequest.execute("http://123.456.789.78:8080/address1/address2", postData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

This is a new Class that responsible for send the response.

private class SendPostRequest extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String postData = "";

        HttpURLConnection httpConnection= null;
        try {

            httpConnection= (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            DataOutputStream outputStream= new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.writeBytes("PostData=" + params[1]);
            outputStream.flush();
            outputStream.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char currentData = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                postData += currentData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpConnection!= null) {
                httpURLConnection.disconnect();
            }
        }
        return postData;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}


问:
How to replace any text between html tags
i have text between html tags. For example:

```<code><td>vip</td>
</code>```

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

答:
```<code>d=$'<td>vip</td>\n<table>vip</table>\n<td>more data here</td>'
echo "$d"
<td>vip</td>
<table>vip</table>
<td>more data here</td>

awk '/<td>/{match($0,/(<.*>)(.*)(<\/.*>)/,t);print t[1] "something" t[3];next}1' <<<"$d"
<td>something</td>
<table>vip</table>
<td>something</td>

awk '/<table>/{match($0,/(<.*>)(.*)(<\/.*>)/,t);print t[1] "something" t[3];next}1' <<<"$d"
<td>vip</td>
<table>something</table>
<td>more data here</td>
</code>```

Body:
i have text between html tags. For example:

vip

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip


问:
Tensorflow print all placeholder variable names from meta graph

I have a tensorflow model for which I have the .meta and the checkpoint files. I am trying to print all the placeholders that the model requires, without looking at the code that constructed the model, so that I can construct a input feed_dict  without knowing how the model was created. For reference, here is the model construction code (in another file)

def save():
    import tensorflow as tf
    v1 = tf.placeholder(tf.float32, name="v1")
    v2 = tf.placeholder(tf.float32, name="v2")
    v3 = tf.multiply(v1, v2)
    vx = tf.Variable(10.0, name="vx")
    v4 = tf.add(v3, vx, name="v4")
    saver = tf.train.Saver()
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    sess.run(vx.assign(tf.add(vx, vx)))
    result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
    print(result)
    saver.save(sess, "./model_ex1")
```

<p>Now in another file, I have the following code to restore</p>

<pre class="lang-py prettyprint-override"><code>def restore():
    import tensorflow as tf
    saver = tf.train.import_meta_graph("./model_ex1.meta")
    print(tf.get_default_graph().get_all_collection_keys())
    for v in tf.get_default_graph().get_collection("variables"):
        print(v)
    for v in tf.get_default_graph().get_collection("trainable_variables"):
        print(v)
    sess = tf.Session()
    saver.restore(sess, "./model_ex1")
    result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 4.0})
    print(result)
</code>```

However, when I print all the variables as above, I do not see "v1:0" and "v2:0" as variable names anywhere. How to identify what tensor names placeholders had without looking at the code for creating the model?

答:
The tensors v1:0 and v2:0 were created from tf.placeholder() ops, whereas only tf.Variable objects are added to the "variables" (or "trainable_variables") collections. There is no general collection to which tf.placeholder() ops are added, so your options are:

Add the tf.placeholder() ops to a collection (using tf.add_to_collection() when constructing the original graph. You might need to add more metadata in order to suggest how the placeholders should be used.

Use [x for x in tf.get_default_graph().get_operations() if x.type == "PlaceholderV2"] to get a list of placeholder ops after you import the metagraph.

Body:
I have a tensorflow model for which I have the .meta and the checkpoint files. I am trying to print all the placeholders that the model requires, without looking at the code that constructed the model, so that I can construct a input feed_dict  without knowing how the model was created. For reference, here is the model construction code (in another file)

def save():
    import tensorflow as tf
    v1 = tf.placeholder(tf.float32, name="v1")
    v2 = tf.placeholder(tf.float32, name="v2")
    v3 = tf.multiply(v1, v2)
    vx = tf.Variable(10.0, name="vx")
    v4 = tf.add(v3, vx, name="v4")
    saver = tf.train.Saver()
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    sess.run(vx.assign(tf.add(vx, vx)))
    result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
    print(result)
    saver.save(sess, "./model_ex1")

Now in another file, I have the following code to restore

def restore():
    import tensorflow as tf
    saver = tf.train.import_meta_graph("./model_ex1.meta")
    print(tf.get_default_graph().get_all_collection_keys())
    for v in tf.get_default_graph().get_collection("variables"):
        print(v)
    for v in tf.get_default_graph().get_collection("trainable_variables"):
        print(v)
    sess = tf.Session()
    saver.restore(sess, "./model_ex1")
    result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 4.0})
    print(result)

However, when I print all the variables as above, I do not see "v1:0" and "v2:0" as variable names anywhere. How to identify what tensor names placeholders had without looking at the code for creating the model?


问:
Getting Error Accessing Twitter Data While Using LinqToTwitter
I'm using this code to get name from screen name of twitter users:

```<code>    var users =
        (from user in twitterCtx.User
         where user.Type == UserType.Lookup &&
               user.ScreenName == "JoeMayo,LinqToTweeter"
         select user)
         .ToList();

    users.ForEach(user => Console.WriteLine("Name: " + user.Name));
</code>```

but I received this error message:

System.AggregateException: One or more errors occurred. —-> System.ArgumentException: Query must contain one of either ScreenNameList or UserIdList parameters, but not both.

How can resolve this problem ?

答:
You're close - all you need to do is replace user.ScreenName with user.ScreenNameList, like this:

```<code>var users =
    (from user in twitterCtx.User
     where user.Type == UserType.Lookup &&
           user.ScreenNameList == "JoeMayo,LinqToTweeter"
     select user)
    .ToList();

users.ForEach(user => Console.WriteLine("Name: " + user.Name));
</code>```

You can find a running Demo in the source code. There's documentation available too.

Body:
I'm using this code to get name from screen name of twitter users:

    var users =
        (from user in twitterCtx.User
         where user.Type == UserType.Lookup &&
               user.ScreenName == "JoeMayo,LinqToTweeter"
         select user)
         .ToList();

    users.ForEach(user => Console.WriteLine("Name: " + user.Name));

but I received this error message:

System.AggregateException: One or more errors occurred. —-> System.ArgumentException: Query must contain one of either ScreenNameList or UserIdList parameters, but not both.

How can resolve this problem ?

Body:
You're close - all you need to do is replace user.ScreenName with user.ScreenNameList, like this:

var users =
    (from user in twitterCtx.User
     where user.Type == UserType.Lookup &&
           user.ScreenNameList == "JoeMayo,LinqToTweeter"
     select user)
    .ToList();

users.ForEach(user => Console.WriteLine("Name: " + user.Name));

You can find a running Demo in the source code. There's documentation available too.


问:
@Query Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: topic is not mapped error
```<code>@Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
    @Query(value = "SELECT u from topic u where u.name = ?1")
    List<Topic> findEverything(String name);
}
</code>```

According to the spring documentation, I can do the above @query. However, it gives me Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: topic is not mapped error.

However, when i do this below, it works.

```<code>@Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
    @Query(value="SELECT * FROM topic WHERE topic.name = ?1", nativeQuery = true)
    List<Topic> findEverything(String name);
}
</code>```

I am using mySQL database. I need to know why. please help me thank you.

答:
if you're using a JPQL query, try to annotate and name your param, instead of relying on positional params, like so:</p>

```<code>@Query(value = "SELECT u from topic u where u.name = :name")
List<Topic> findEverything(@Param("name")String name);
</code>```

Body:
@Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
    @Query(value = "SELECT u from topic u where u.name = ?1")
    List<Topic> findEverything(String name);
}

According to the spring documentation, I can do the above @query. However, it gives me Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: topic is not mapped error.

However, when i do this below, it works.

@Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
    @Query(value="SELECT * FROM topic WHERE topic.name = ?1", nativeQuery = true)
    List<Topic> findEverything(String name);
}

I am using mySQL database. I need to know why. please help me thank you.

Body:
if you're using a JPQL query, try to annotate and name your param, instead of relying on positional params, like so:

@Query(value = "SELECT u from topic u where u.name = :name")
List<Topic> findEverything(@Param("name")String name);


问:
Prime number in java 8
I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

```<code>import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}
</code>```

答:
Your isPrime() is inefficient.  First, you do not need to divide by any even numbers greater than 2, since an initial division by 2 will catch all even non-primes.  Second, you terminate your loop at number / 2 instead of the more efficient sqrt(number).

You could rewrite your method something like this:

```<code>public static boolean isPrime(int number) {

    // Low numbers
    if (number < 2) {
      return false;
    }

    // Even numbers
    if (number % 2 == 0) {
        return number == 2;
    }

    // Odd numbers
    int limit = (int)(0.1 + Math.sqrt(number));
    for (int i = 3; i <= limit; i += 2) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}
</code>```

The Sieve of Eratosthenes would be more efficient still, but that might be overkill for a relatively small problem.

Title: Prime number in java 8

Body:
I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Body:
Your isPrime() is inefficient.  First, you do not need to divide by any even numbers greater than 2, since an initial division by 2 will catch all even non-primes.  Second, you terminate your loop at number / 2 instead of the more efficient sqrt(number).

You could rewrite your method something like this:

public static boolean isPrime(int number) {

    // Low numbers
    if (number < 2) {
      return false;
    }

    // Even numbers
    if (number % 2 == 0) {
        return number == 2;
    }

    // Odd numbers
    int limit = (int)(0.1 + Math.sqrt(number));
    for (int i = 3; i <= limit; i += 2) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

The Sieve of Eratosthenes would be more efficient still, but that might be overkill for a relatively small problem.


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
A minor correction in your code, adding a flag. Also you don't need to run the inner loop i times, infact only i/2 times is sufficient. This is simple mathematics, but will save significant number of CPU cycles (~5000 iterations lesser in your case)</p>

```<code>#include <iostream>

int main()
{
    int n = 10;
    for(int i=2; i<=n; i++){
        bool isPrime = true;
        for(int j=2; j<=i/2; j++){
            if(i!=j && i%j==0){
                isPrime = false;
                break;
            }
        }
        if(isPrime)
            std::cout << i << " ";
    }
    return 0;
}
</code>```

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}

Body:
A minor correction in your code, adding a flag. Also you don't need to run the inner loop i times, infact only i/2 times is sufficient. This is simple mathematics, but will save significant number of CPU cycles (~5000 iterations lesser in your case)

#include <iostream>

int main()
{
    int n = 10;
    for(int i=2; i<=n; i++){
        bool isPrime = true;
        for(int j=2; j<=i/2; j++){
            if(i!=j && i%j==0){
                isPrime = false;
                break;
            }
        }
        if(isPrime)
            std::cout << i << " ";
    }
    return 0;
}


问:
bash: get path from current directory given sub-directory name
Trying to write a script to clean up environment files after a resource is deleted. The problem is all the script is given as input is the name of the resource (this cannot be changed) with zero identifying information beyond that. How can I find the path of the directory the resource is sitting in?

The directory is set up a bit like the following, although much more extensive. All of these are directories, not files. There can be as many as 40+ directories to search, but the desired one is generally not more than 2-3 directories deep.

```<code>foo
    aaa
       aaa_green
       aaa_blue
    bbb
    ccc
       ccc_green
bar
    ddd
    eee
       eee_green
       eee_blue
    fff
       fff_green
       fff_blue
       fff_pink
</code>```

I might be handed input like aaa_green or just ddd.

As an example, given eee_blue as input, I need to know eee_blue's path from the working directory so I can cd there and delete the directory. IE, I would expect to return bar/eee/eee_blue/ or bar/eee/, either is acceptable.

The "best" option I can see currently is to cd into the lowest level of each directory via multiple greps, get each's contents and look for a match, and when it does (eventually) match save that cd'ing as the path. This frankly sounds awful and inefficient.

The only other alternative method I could think of was a straight recursive grep, but I tested it and at 8 minutes it still hadn't finished running.

This script needs to run on both mac and linux, although in a desperate pinch I could go linux only.

答:
The standard Unix tool for doing this sort of task is the find command.  The GNU version of find has more extensive options than the POSIX specification (by quite a margin).  The version on macOS Sierra (and Mac OS X) is similar to the GNU version.  I found an online manual for OS X 10.9 at Apple find, but there's probably a better location somewhere.

It looks like you might want to run:

```<code>find . -name 'eee_blue'
</code>```

which will print the names of matching files or directories, or perhaps:

```<code>find . -name 'eee_blue' -exec rm -fr {} +
</code>```

which will run the rm -fr command on each name.  You can run a custom script you create in place of rm -fr if you prefer; if the logic is complex, it's what I do.

Be extremely cautious before using rm -fr automatically!

Body:
Trying to write a script to clean up environment files after a resource is deleted. The problem is all the script is given as input is the name of the resource (this cannot be changed) with zero identifying information beyond that. How can I find the path of the directory the resource is sitting in?

The directory is set up a bit like the following, although much more extensive. All of these are directories, not files. There can be as many as 40+ directories to search, but the desired one is generally not more than 2-3 directories deep.

foo
    aaa
       aaa_green
       aaa_blue
    bbb
    ccc
       ccc_green
bar
    ddd
    eee
       eee_green
       eee_blue
    fff
       fff_green
       fff_blue
       fff_pink

I might be handed input like aaa_green or just ddd.

As an example, given eee_blue as input, I need to know eee_blue's path from the working directory so I can cd there and delete the directory. IE, I would expect to return bar/eee/eee_blue/ or bar/eee/, either is acceptable.

The "best" option I can see currently is to cd into the lowest level of each directory via multiple greps, get each's contents and look for a match, and when it does (eventually) match save that cd'ing as the path. This frankly sounds awful and inefficient.

The only other alternative method I could think of was a straight recursive grep, but I tested it and at 8 minutes it still hadn't finished running.

This script needs to run on both mac and linux, although in a desperate pinch I could go linux only.

Body:
The standard Unix tool for doing this sort of task is the find command.  The GNU version of find has more extensive options than the POSIX specification (by quite a margin).  The version on macOS Sierra (and Mac OS X) is similar to the GNU version.  I found an online manual for OS X 10.9 at Apple find, but there's probably a better location somewhere.

It looks like you might want to run:

find . -name 'eee_blue'

which will print the names of matching files or directories, or perhaps:

find . -name 'eee_blue' -exec rm -fr {} +

which will run the rm -fr command on each name.  You can run a custom script you create in place of rm -fr if you prefer; if the logic is complex, it's what I do.

Be extremely cautious before using rm -fr automatically!


问:
How to use PullToRefresh without RecyclerView in android
I want use PullToRefresh but in my application I don't use recyclerview, and use this widget : android.support.v4.widget.NestedScrollView.

I should set pull to refresh to load new data in my application, how can I it?

Please don't offer to me for use RecyclerView, because I haven't use RecyclerView.

I want use android.support.v4.widget.NestedScrollView .

How can I it?

答:
Use SwipeRefreshLayout

```<code>this.srl1 = (SwipeRefreshLayout) findViewById(R.id.srl);
        if (srl1 != null) {
            srl1.setColorSchemeResources(R.color.red, R.color.green, R.color.blue);
            srl1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    Refresh();
                }
            });
        }
</code>```

XML CODE

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/srl"
    >

</android.support.v4.widget.SwipeRefreshLayout>
</code>```

Body:
Use SwipeRefreshLayout

this.srl1 = (SwipeRefreshLayout) findViewById(R.id.srl);
        if (srl1 != null) {
            srl1.setColorSchemeResources(R.color.red, R.color.green, R.color.blue);
            srl1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    Refresh();
                }
            });
        }

XML CODE

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/srl"
    >

</android.support.v4.widget.SwipeRefreshLayout>


问:
SAPUI5 - Seach field on a table with column list items
EDIT: Silly me, was pointing at the wrong property. Should have been pointing it at ArticleDescription instead of value.

I require a search field on a table with custom list items. The table brings through the data fine, but a requirement now is to add a search field for easy searching due to sometimes the table can get large.

Following the SAPUI5 explored page, I cannot seem to get this to work.

Ideally I would like it to use the liveChange property so this is done on the fly. I've got it to the point where that's doing it's job but I'm not ring back the search data.

Any help would be appreciated.

Table image

main.view.xml

```<code><!-- Search box -->
                    <SearchField liveChange="onSearch" width="100%" class="sapUiMediumMarginBottom"/>

                    <!-- Table -->
                    <Table id="stock_table" itemPress="onOrderClicked" items="{stock>/Items}" keyboardMode="Edit" showFullScreenButton="true">
                        <infoToolbar>
                            <Toolbar>
                                <ToolbarSpacer/>
                                <Label text="{ path:'stock>/CurrentDate', formatter:'.tableHeader'}"/>
                                <ToolbarSpacer/>
                            </Toolbar>
                        </infoToolbar>
                        <columns>
                            <Column minScreenWidth="Tablet" demandPopin="true">
                                <Text text="{i18n>Article}"/>
                            </Column>
                            <Column minScreenWidth="Tablet" width="10em" demandPopin="true">
                                <Text text="{i18n>UnitOfMeasure}"/>
                            </Column>
                            <Column minScreenWidth="Tablet" width="8em" demandPopin="true">
                                <Text text="{i18n>Quantity}"/>
                            </Column>
                        </columns>
                        <items>
                            <ColumnListItem class="sapUiSizeCompact">
                                <customData>
                                    <core:CustomData key="mydata" value="{stock>_errorStateClass}"
                                                     writeToDom="true"/>
                                </customData>

                                <HBox>
                                    <core:Icon src="sap-icon://message-information"
                                               tooltip="{i18n>ArticleNumber}: {stock>ArticleNumber}"
                                               class="sapUiSmallMarginEnd greggslightblue"/>
                                    <Text text="{stock>ArticleDescription}"/>
                                </HBox>
                                <Text text="{stock>UnitOfMeasureDescription}"/>
                                <HBox>
                                    <Input id="quantity_input" valueLiveUpdate="true" value="{stock>_Quantity}"
                                           liveChange="onQuantityAmountChanged"
                                           class="CanHaveInteraction green_enter" width="5rem"/>
                                    <core:Icon src="sap-icon://message-error"
                                               tooltip="{stock>_ErrorMessage}"
                                               class="sapUiSmallMarginEnd greggsred input-warning-icon"
                                               visible="{stock>_ErrorStatus}" press="onErrorIconPressed"/>
                                    <core:Icon src="sap-icon://message-warning"
                                               tooltip="{stock>_ErrorMessage}"
                                               class="sapUiSmallMarginEnd greggsred input-warning-icon"
                                               visible="{stock>_WarningStatus}"/>
                                </HBox>
                            </ColumnListItem>
                        </items>
                    </Table>
</code>```

main.controller.js

```<code>onSearch : function (oEvt) {

        // add filter for search
        var aFilters = [];
        var sQuery = oEvt.getSource().getValue();
        if (sQuery && sQuery.length > 0) {
            var filter = new Filter("Name", sap.ui.model.FilterOperator.Contains, sQuery);
            aFilters.push(filter);
        }

        // update list binding
        var list = this.getView().byId("stock_table");
        var binding = list.getBinding("items");
        binding.filter(aFilters, "Application");
    }
</code>```

答:
are you sure the following line contains a valid search query:

```<code>var sQuery = oEvt.getSource().getValue();
</code>```

As documented in the API https://openui5.hana.ondemand.com/#docs/api/symbols/sap.m.SearchField.html#event:liveChange you have to use the event source parameter 'newValue':

```<code>var sQuery = oEvt.getParameter("newValue");
</code>```

Update

Please show your data structure as you try to filter on path 'Name'. But within the table column binding I cannot see any attribute called 'Name'. Rather you can try to filter on attribute 'ArticleDescription':

```<code>var filter = new Filter("ArticleDescription", sap.ui.model.FilterOperator.Contains, sQuery);
</code>```

Body:
EDIT: Silly me, was pointing at the wrong property. Should have been pointing it at ArticleDescription instead of value.

I require a search field on a table with custom list items. The table brings through the data fine, but a requirement now is to add a search field for easy searching due to sometimes the table can get large.

Following the SAPUI5 explored page, I cannot seem to get this to work.

Ideally I would like it to use the liveChange property so this is done on the fly. I've got it to the point where that's doing it's job but I'm not ring back the search data.

Any help would be appreciated.

Table image

main.view.xml

                    <SearchField liveChange="onSearch" width="100%" class="sapUiMediumMarginBottom"/>

/Items}" keyboardMode="Edit" showFullScreenButton="true">
                        <infoToolbar>
                            <Toolbar>
                                <ToolbarSpacer/>
                                /CurrentDate', formatter:'.tableHeader'}"/>
                                <ToolbarSpacer/>
                            </Toolbar>
                        </infoToolbar>
                        <columns>
                            <Column minScreenWidth="Tablet" demandPopin="true">
                                <Text text="{i18n>Article}"/>
                            </Column>
                            <Column minScreenWidth="Tablet" width="10em" demandPopin="true">
                                <Text text="{i18n>UnitOfMeasure}"/>
                            </Column>
                            <Column minScreenWidth="Tablet" width="8em" demandPopin="true">
                                <Text text="{i18n>Quantity}"/>
                            </Column>
                        </columns>
                        <items>
                            <ColumnListItem class="sapUiSizeCompact">
                                <customData>
                                    <core:CustomData key="mydata" value="{stock>_errorStateClass}"
                                                     writeToDom="true"/>
                                </customData>

                                <HBox>
                                    <core:Icon src="sap-icon://message-information"
                                               tooltip="{i18n>ArticleNumber}: {stock>ArticleNumber}"
                                               class="sapUiSmallMarginEnd greggslightblue"/>
                                    <Text text="{stock>ArticleDescription}"/>
                                </HBox>
                                <Text text="{stock>UnitOfMeasureDescription}"/>
                                <HBox>
                                    <Input id="quantity_input" valueLiveUpdate="true" value="{stock>_Quantity}"
                                           liveChange="onQuantityAmountChanged"
                                           class="CanHaveInteraction green_enter" width="5rem"/>
                                    <core:Icon src="sap-icon://message-error"
                                               tooltip="{stock>_ErrorMessage}"
                                               class="sapUiSmallMarginEnd greggsred input-warning-icon"
                                               visible="{stock>_ErrorStatus}" press="onErrorIconPressed"/>
                                    <core:Icon src="sap-icon://message-warning"
                                               tooltip="{stock>_ErrorMessage}"
                                               class="sapUiSmallMarginEnd greggsred input-warning-icon"
                                               visible="{stock>_WarningStatus}"/>
                                </HBox>
                            </ColumnListItem>
                        </items>

main.controller.js

onSearch : function (oEvt) {

        // add filter for search
        var aFilters = [];
        var sQuery = oEvt.getSource().getValue();
        if (sQuery && sQuery.length > 0) {
            var filter = new Filter("Name", sap.ui.model.FilterOperator.Contains, sQuery);
            aFilters.push(filter);
        }

        // update list binding
        var list = this.getView().byId("stock_table");
        var binding = list.getBinding("items");
        binding.filter(aFilters, "Application");
    }

Body:
are you sure the following line contains a valid search query:

var sQuery = oEvt.getSource().getValue();

As documented in the API https://openui5.hana.ondemand.com/#docs/api/symbols/sap.m.SearchField.html#event:liveChange you have to use the event source parameter 'newValue':

var sQuery = oEvt.getParameter("newValue");

Update

Please show your data structure as you try to filter on path 'Name'. But within the table column binding I cannot see any attribute called 'Name'. Rather you can try to filter on attribute 'ArticleDescription':

var filter = new Filter("ArticleDescription", sap.ui.model.FilterOperator.Contains, sQuery);


问:
What is the best unit testing tool for a mix of managed and unmanaged C++?
I am going to start implementing some unit tests for a codebase that is a mix of managed and unmanaged C++. Can NUnit hack it with unmanaged code? Is there a better alternative?</p>

答:
It's possible to use NUnit to test unmanaged code, example:</p>

```<code>// Tests.h

#pragma once

#include <cmath>

using namespace System;
using namespace NUnit::Framework;

namespace Tests {

    [TestFixture]
    public ref class UnitTest
    {
    public:
        UnitTest(void) {}

        [Test]
        void TestCos()
        {
            Assert::AreEqual(1, cos(0.0));
        }

    };
}
</code>```

OwnerDisplayName: brian

Body:
It's possible to use NUnit to test unmanaged code, example:

// Tests.h

#pragma once

#include <cmath>

using namespace System;
using namespace NUnit::Framework;

namespace Tests {

    [TestFixture]
    public ref class UnitTest
    {
    public:
        UnitTest(void) {}

        [Test]
        void TestCos()
        {
            Assert::AreEqual(1, cos(0.0));
        }

    };
}

OwnerDisplayName: Dmitriy Matveev


问:
How to generate RSA key using sha512 for JWT?
I understand that RSA keys can be generated using different sha algorithms. Using openssl, I don't seem to have the option of specifying what algorithm the key generator should use. I suspect it's using sha256.

How can I generate RSA keys using different sha algorithms (such as sha512) in either a bash shell or in Ruby? Does the openssl library support generating RSA keys using different algorithms? If not, does anyone know of another library I can use? (In ruby, OpenSSL::PKey::RSA doesn't seem to allow for choosing an algorithm, but the documentation is hard for me to follow soo...?)

Apologies if this question has already been answered, but I haven't been able to find an answer.

Maybe I should also note (in case I am wrong): it is my understanding that choosing a size for the generated RSA key (i.e. RSA 2048) is separate from choosing the hashing algorithm (i.e. sha512).

UPDATE - Some background

I want to sign Java Web Tokens with an RSA key. The JWT library I'm using gives me the impression that RSA keys can be generated using different hashing algorithms (RS256, RS384, RS512). Generating a key using openssl doesn't seem to let me choose what hashing algorithm is used though.

Thanks!!

答:
RSA keys, and "the RSA algorithm" don't have any notion of a hash algorithm.

An RSA key is just two prime numbers and one other number (from the (p, q, e) triplet all the other values can be derived). e is usually chosen as 0x010001 (though other reasonable values exist) and p and q are generated randomly (while almost any CSPRNG is going to have a backing hash algorithm the CSPRNG itself is usually considered a black box that just emits randomness).

Where a hash algorithm comes into play is in RSA Signatures.

For an RSA Signature the original data is hashed under an algorithm and then the hash value, algorithm identifier, and private key are used to produce a signature (for PKCS v1.5 signatures... for PSS there's also a second (effectively fixed) identifier and some more random bytes).

RS256 is the JWA (JSON Web Algorithms) identifier for "RSASSA-PKCS1-v1_5 using SHA(-2)-256".

JWA section 3.3 says

This section defines the use of the RSASSA-PKCS1-v1_5 digital
signature algorithm as defined in Section 8.2 of RFC 3447 [RFC3447]
(commonly known as PKCS #1), using SHA-2 [SHS] hash functions.

A key of size 2048 bits or larger MUST be used with these algorithms.

The RSASSA-PKCS1-v1_5 SHA-256 digital signature is generated as
follows: generate a digital signature of the JWS Signing Input using
RSASSA-PKCS1-v1_5-SIGN and the SHA-256 hash function with the desired
private key.  This is the JWS Signature value.

(emphasis mine)

So no requirement is made on the RSA key, other than that the spec was written in 2015 so they mandated a 2015-compatible minimum keysize.


问:
Rhino: Prototype chaining not working for host objects?
Invoking on a child a method defined in parent, where parent is a host object, gives EcmaError: method called on incompatible object.

Host object defined in Java:

```<code>public class HostObject extends ScriptableObject {

    public HostObject() {}

    @Override
    public String getClassName() {
        return "HostObject";
    }

    public void jsFunction_sayHi() {
        System.out.println("Hi!");
    }
}
</code>```

Test script #1 run in Rhino:

```<code>var foo = new HostObject();
foo.sayHi();
</code>```

Works fine.

Test script #2:

```<code>function Bar() {}
Bar.prototype = new HostObject();
var bar = new Bar();
bar.sayHi();
</code>```

Throws an exception:

org.mozilla.javascript.EcmaError: TypeError: Method "sayHi" called on incompatible object.

Found a way around this issue (kind of...) - by using an alternative form of defining a method - a static method with parameters (Context cx, Scriptable thisObj, Object[] args, Function funObj) and then explicitly using the prototype whenever I need to access members:

```<code>HostObject ho = (HostObject)thisObj.getPrototype();
</code>```

Thing is there are situations when sayHi() is invoked on the original object and then getPrototype() refers to Javascript Object, so I would need to perform an extra check to make this work in both cases. I would've thought that with prototype chaining the original example should work just fine. Is that a possible bug here? Or am I doing something wrong?

I'm using Rhino 1.7R2.

答:
Instead of using:

```<code>HostObject ho = (HostObject)thisObj.getPrototype();
</code>```

use something like:

```<code>Scriptable obj = thisObj;
while(obj != null && !(obj instanceof HostObject)) {
    obj = obj.getPrototype();
}
HostObject ho = (HostObject)ho;
</code>```

This will find the right prototype in the chain of prototypes.

Body:
Invoking on a child a method defined in parent, where parent is a host object, gives EcmaError: method called on incompatible object.

Host object defined in Java:

public class HostObject extends ScriptableObject {

    public HostObject() {}

    @Override
    public String getClassName() {
        return "HostObject";
    }

    public void jsFunction_sayHi() {
        System.out.println("Hi!");
    }
}

Test script #1 run in Rhino:

var foo = new HostObject();
foo.sayHi();

Works fine.

Test script #2:

function Bar() {}
Bar.prototype = new HostObject();
var bar = new Bar();
bar.sayHi();

Throws an exception:

org.mozilla.javascript.EcmaError: TypeError: Method "sayHi" called on incompatible object.

Found a way around this issue (kind of...) - by using an alternative form of defining a method - a static method with parameters (Context cx, Scriptable thisObj, Object[] args, Function funObj) and then explicitly using the prototype whenever I need to access members:

HostObject ho = (HostObject)thisObj.getPrototype();

Thing is there are situations when sayHi() is invoked on the original object and then getPrototype() refers to Javascript Object, so I would need to perform an extra check to make this work in both cases. I would've thought that with prototype chaining the original example should work just fine. Is that a possible bug here? Or am I doing something wrong?

I'm using Rhino 1.7R2.

Body:
Instead of using:

HostObject ho = (HostObject)thisObj.getPrototype();

use something like:

Scriptable obj = thisObj;
while(obj != null && !(obj instanceof HostObject)) {
    obj = obj.getPrototype();
}
HostObject ho = (HostObject)ho;

This will find the right prototype in the chain of prototypes.


问:
AngularFire2 Retrieve Child node Data As Object
I want to retrieve data in child node as a Object using angularfire2

```<code>     getPostEditData(uid:any,key:any){

     this.dataObject = this.af.database.object('/webPosts/'+uid+key) as
     FirebaseObjectObservable<postVal>
     return this.dataObject; }
</code>```

I used this but its not working. How I suppose to do that?
My Structure

答:
You need another slash (/) with your reference.

```<code>getPostEditData(uid:any,key:any) {
    this.dataObject =
        this.af.database.object('/webPosts/' + uid + '/' + key) as FirebaseObjectObservable<postVal>
    return this.dataObject;
}
</code>```

Wrong: uid + key

Right: uid + '/' + key

Body:
I want to retrieve data in child node as a Object using angularfire2

     getPostEditData(uid:any,key:any){

     this.dataObject = this.af.database.object('/webPosts/'+uid+key) as
     FirebaseObjectObservable<postVal>
     return this.dataObject; }

I used this but its not working. How I suppose to do that?
My Structure

Body:
You need another slash (/) with your reference.

getPostEditData(uid:any,key:any) {
    this.dataObject =
        this.af.database.object('/webPosts/' + uid + '/' + key) as FirebaseObjectObservable<postVal>
    return this.dataObject;
}

Wrong: uid + key

Right: uid + '/' + key


问:
How to autofill a form in Access with data from an Excel spreadsheet
I was given an enormous Excel spreadsheet that I have to port to an Access database. There are roughly 40 fields in the spreadsheet per entry. Is it possible to create a form in Access, and use the data from the Excel spreadsheet to automatically populate the form, and in turn, the database?</p>

答:
Using a form for this item by item is a complete waste of time.

On the External Data Tab, you can Import From Excel. If you have a weird layout that doesn't play nice with the Import tool, you can add the Microsoft Excel Object Library and use VBA to open and control Excel Workbook Objects and Worksheet Objects to pull the data in a custom way. Using the second method, I would use a form, but the only purpose for it would be to hold a button that would execute the VBA to import.