问:
ReyclerView isn't working
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

```<code>  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }
</code>```

答:
Please change your code</p>

```<code>getitemcount()
{
   return 0:
}

to

videosList.size();

public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return "YourList.size()";
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }
</code>```

Title: ReyclerView isn't working

Body:
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }

Body:
Please change your code

getitemcount()
{
   return 0:
}

to

videosList.size();

public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return "YourList.size()";
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }


来源: stackexchange

问:
Counting the number of a specific word inside a php string
I have a php string like as follows :

```<code> $string = 'www absjdjjd www123 dkkd www wwww ghy ww';
</code>```

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

```<code>$val = 'www';
$count = substr_count($string, $val);
</code>```

答:
If you only want to match www, you could use \bwww\b which will look for www between word boundaries \b with preg_match_all.

```<code>$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
preg_match_all('/\bwww\b/', $string, $matches);
var_dump($matches);
</code>```

Will result in:

```<code>array(1) {
    [0]=>
  array(2) {
        [0]=>
    string(3) "www"
        [1]=>
    string(3) "www"
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a php string like as follows :

 $string = 'www absjdjjd www123 dkkd www wwww ghy ww';

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

$val = 'www';
$count = substr_count($string, $val);

Body:
If you only want to match www, you could use \bwww\b which will look for www between word boundaries \b with preg_match_all.

$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
preg_match_all('/\bwww\b/', $string, $matches);
var_dump($matches);

Will result in:

array(1) {
    [0]=>
  array(2) {
        [0]=>
    string(3) "www"
        [1]=>
    string(3) "www"
  }
}


问:
Q: OKTA is artifact binding and unsolicited Identifier Provider access supported?
We have read the OKTA guides, but have two unresolved questions:

does OKTA support Artifact binding https://en.wikipedia.org/wiki/SAML_2.0#HTTP_Artifact_Binding

does OKTA/SAML 2.0 support unsolicited Identity Provider (IdP) artifact binding, or is it mandatory to have to be redirected from the Service Provider (SP)?

Regarding the first question

We face a situation where a large quantity of data would have to be transmitted through the user agent, and we are also motivated by security best-practice.  Our opinion is that artifact binding is the best security model for SAML 2.0; and will also help reduce load on the user agent.  Can OKTA support artifact binding?  We haven't been able to find either a positive or negative confirmation in the documentation.  Many apologies if this is an oversight on our part.

Regarding the second question

The problem we are solving is that we are integrating with an organisation who have a portal of products they recommend and for which they have organised access via their portal.  Each of these products require authentication, making a good case for Single Sign On (SSO).  Both sides of the integration would like the user experience to be: click on the link and be logged in to the service.  This is different to most of the models for any SAML 2.0 modes of working as the workflow starts at the IdP rather than the SP.  Is this possible in OKTA, or at all in SAML 2.0?  Again, many apologies if we have missed this in the documentation.

答:
Doesn't seem that Okta supports this when I check the metadata.

Wikipedia shows what the ArtifactResolutionService item would look like in the metadata:

```<code>  <md:IDPSSODescriptor
    protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
    <md:KeyDescriptor use="signing">
      <ds:KeyInfo>...</ds:KeyInfo>
    </md:KeyDescriptor>
    <md:ArtifactResolutionService isDefault="true" index="0"
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
      Location="https://idp.example.org/SAML2/ArtifactResolution"/>
    <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
    <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
      Location="https://idp.example.org/SAML2/SSO/Redirect"/>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
      Location="https://idp.example.org/SAML2/SSO/POST"/>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
      Location="https://idp.example.org/SAML2/Artifact"/>
    <saml:Attribute
      NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
      Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
      FriendlyName="eduPersonAffiliation">
      <saml:AttributeValue>member</saml:AttributeValue>
      <saml:AttributeValue>student</saml:AttributeValue>
      <saml:AttributeValue>faculty</saml:AttributeValue>
      <saml:AttributeValue>employee</saml:AttributeValue>
      <saml:AttributeValue>staff</saml:AttributeValue>
    </saml:Attribute>
  </md:IDPSSODescriptor>
</code>```

I've looked through Okta's configuration and can't find anyway to enable this so it shows up as an available service.

Body:
Doesn't seem that Okta supports this when I check the metadata.

Wikipedia shows what the ArtifactResolutionService item would look like in the metadata:

  <md:IDPSSODescriptor
    protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
    <md:KeyDescriptor use="signing">
      <ds:KeyInfo>...</ds:KeyInfo>
    </md:KeyDescriptor>
    <md:ArtifactResolutionService isDefault="true" index="0"
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
      Location="https://idp.example.org/SAML2/ArtifactResolution"/>
    <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
    <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
      Location="https://idp.example.org/SAML2/SSO/Redirect"/>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
      Location="https://idp.example.org/SAML2/SSO/POST"/>
    <md:SingleSignOnService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
      Location="https://idp.example.org/SAML2/Artifact"/>
    <saml:Attribute
      NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
      Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
      FriendlyName="eduPersonAffiliation">
      <saml:AttributeValue>member</saml:AttributeValue>
      <saml:AttributeValue>student</saml:AttributeValue>
      <saml:AttributeValue>faculty</saml:AttributeValue>
      <saml:AttributeValue>employee</saml:AttributeValue>
      <saml:AttributeValue>staff</saml:AttributeValue>
    </saml:Attribute>
  </md:IDPSSODescriptor>

I've looked through Okta's configuration and can't find anyway to enable this so it shows up as an available service.


问:
Handle empty response with retrofit and rxjava 2.x
When using rxjava 1.x i used to return Observable<Void> to handle empty response from retrofit:

```<code>@POST( "login" )
Observable<Void> getToken( @Header( "Authorization" ) String authorization,
                                       @Header( "username" ) String username,
                                       @Header( "password" ) String password );
</code>```

But since rxjava 2.x won't emit anything with Void is there any good practice to handle those empty responses?

答:
Another solution is:

```<code>@POST("login")
Observable<Response<Void>> getToken(@Header("Authorization") String authorization,
                                    @Header("username") String username,
                                    @Header("password") String password);
</code>```

Update:
But I would rather use Completable

Body:
When using rxjava 1.x i used to return Observable<Void> to handle empty response from retrofit:

@POST( "login" )
Observable<Void> getToken( @Header( "Authorization" ) String authorization,
                                       @Header( "username" ) String username,
                                       @Header( "password" ) String password );

But since rxjava 2.x won't emit anything with Void is there any good practice to handle those empty responses?

Body:
Another solution is:

@POST("login")
Observable<Response<Void>> getToken(@Header("Authorization") String authorization,
                                    @Header("username") String username,
                                    @Header("password") String password);

Update:
But I would rather use Completable

ContentLicense: CC BY-SA 4.0


问:
Autocomplete from 10 000 items in .NET
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary

答:
The fastest way is to drop those values in a page say in a javascript variable (string array) using for example a literal control  and then use something like this:

http://docs.jquery.com/Plugins/autocomplete#Example

ContentLicense: CC BY-SA 2.5

Title: Autocomplete from 10 000 items in .NET


问:
Build docker image without docker installed
Is it somehow possible to build images without having docker installed. On maven build of my project I'd like to produce docker image, but I don't want to force others to install docker on their machines.

I can think of some virtual box image with docker installed, but it is kind of heavy solution. Is there some way to build the image with some maven plugin only, some Go code or already prepared virtual box image for exactly this purpose?

It boils down to question how to use docker without forcing users to install anything. Either just for build or even for running docker images.

UPDATE

There are some, not really up to date, maven plugins for virtual machine provisioning with vagrant or with vbox. I have found article about building docker images without docker on basel
So far I see two options either I can somehow build the images only or run some VM with docker daemon inside(which can be used not only for builds, but even for integration tests)

答:
I don't want to force others to install docker on their machines.

If by "without Docker installed" you mean without having to install Docker locally on every machine running the build, you can leverage the Docker Engine API which allow you to call a Docker Daemon from a distant host.

The Docker Engine API is a RESTful API accessed by an HTTP client such
  as wget or curl, or the HTTP library which is part of most modern
  programming languages.

For example, the Fabric8 Docker Maven Plugin does just that using the DOCKER_HOST parameter. You'll need a recent Docker version and you'll have to configure at least one Docker Daemon properly so it can securely accept remote requests (there are lot of resources on this subject, such as the official doc, here or here). From then on, your Docker build can be done remotely without having to install Docker locally.


问:
Laravel 5.5 BelongsToMany returns empty
I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty.

I've set up my relation in the Store model like this:

```<code>    public function images()
    {
        return $this->belongsToMany('App\Images', 'images_stores', 'image_id', 'store_id');
    }
</code>```

When i test the relationship it returns no error just a empty collection although it's not. This is the way i access the data:

```<code>    public function edit($id)
    {
        $store = Store::find($id);
        dd($store->images);

        return view('admin.pages.store.edit', compact('store'));
    }
</code>```

But it would just return a empty collection, i hope someone could help me out with this. These are my migration file's but i don't think the problem is inside the migration files.

```<code>    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('path');
        $table->timestamps();
    });
    // pivot table
    Schema::create('images_stores', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('image_id')->unsigned()->nullable();
        $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');

        $table->integer('store_id')->unsigned()->nullable();
        $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');

        $table->timestamps();
    });
    // store table
    Schema::create('stores', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('location');
        $table->string('email');
        $table->timestamps();
    });
</code>```

Thanks guys.

答:
I think the ids are inverted. Try this:

```<code>public function images()
{
    return $this->belongsToMany('App\Images', 'images_stores', 'store_id', 'image_id');
}
</code>```

Title: Laravel 5.5 BelongsToMany returns empty

Body:
I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty.

I've set up my relation in the Store model like this:

    public function images()
    {
        return $this->belongsToMany('App\Images', 'images_stores', 'image_id', 'store_id');
    }

When i test the relationship it returns no error just a empty collection although it's not. This is the way i access the data:

    public function edit($id)
    {
        $store = Store::find($id);
        dd($store->images);

        return view('admin.pages.store.edit', compact('store'));
    }

But it would just return a empty collection, i hope someone could help me out with this. These are my migration file's but i don't think the problem is inside the migration files.

    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('path');
        $table->timestamps();
    });
    // pivot table
    Schema::create('images_stores', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('image_id')->unsigned()->nullable();
        $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');

        $table->integer('store_id')->unsigned()->nullable();
        $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');

        $table->timestamps();
    });
    // store table
    Schema::create('stores', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('location');
        $table->string('email');
        $table->timestamps();
    });

Thanks guys.

Body:
I think the ids are inverted. Try this:

public function images()
{
    return $this->belongsToMany('App\Images', 'images_stores', 'store_id', 'image_id');
}


问:
Fit WPF Label in User Control to the width of its Content
I have a WPF User Control that contains a simple label and rectangle on a grid, looking like this:

```<code>   <Grid x:Name="Pressbutton">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="14"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Rectangle x:Name="LayerColour" Grid.Column="0" Fill="#FFF4F4F5" Width="10" Height="10" Margin="0" Stroke="Black" VerticalAlignment="Center" MinWidth="10" MinHeight="10" Visibility="Visible" HorizontalAlignment="Center"/>
        <Label x:Name="DisplayNameLabel" Grid.Column="1" Content="Label"  Margin="0" VerticalAlignment="Center" Height="26" Visibility="Visible" />
    </Grid>
</code>```

Then I am laying these out in a StackPanel, which works fine and using a GridSplitter to divide this list of labels from the other part of the window.

My window looks a little like this:

```<code>==========================================x
| StackPanel           |   Other Stuff    |
|    PressButton1      |                  |
|    PressButton2      |                  |
|    PressButton3      |                  |
===========================================
</code>```

My problem is that currently the GridSplitter only wants to render in the centre of the Window, and I want the label list to be significantly more narrow. The ideal starting width for the label panel is as wide as the widest label.

I have tried measuring the ActualWidth of my User Controls but that is always being set to the width of the containing StackPanel. If I try and measure the width of the Labels those too seem determined to stretch to their maximum possible width. It seems ridiculous that I would have to go through the whole rigmarole of pre-rendering the text of my labels just to get an idea of how wide my labels are supposed to be when the text is right there on the label already, so I assume I am doing something wrong.

How do I find the width of the text on my label, so I can move the GridSplitter to fit the left pane snugly?

答:
I assume based on your "drawing" that you have a Grid with two columns. You can set the first column to Auto width and place your stackpanel there.
Set the second column to width 1*, create a GridSplitter and set its Grid.Column to 1, set a fixed width for it(i usually set it to 10) and set HorizontalAlignment to Left and VerticalAlignment to Stretch.
Should do the trick.</p>

Body:
I have a WPF User Control that contains a simple label and rectangle on a grid, looking like this:

   <Grid x:Name="Pressbutton">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="14"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Rectangle x:Name="LayerColour" Grid.Column="0" Fill="#FFF4F4F5" Width="10" Height="10" Margin="0" Stroke="Black" VerticalAlignment="Center" MinWidth="10" MinHeight="10" Visibility="Visible" HorizontalAlignment="Center"/>

    </Grid>

Then I am laying these out in a StackPanel, which works fine and using a GridSplitter to divide this list of labels from the other part of the window.

My window looks a little like this:

==========================================x
| StackPanel           |   Other Stuff    |
|    PressButton1      |                  |
|    PressButton2      |                  |
|    PressButton3      |                  |
===========================================

My problem is that currently the GridSplitter only wants to render in the centre of the Window, and I want the label list to be significantly more narrow. The ideal starting width for the label panel is as wide as the widest label.

I have tried measuring the ActualWidth of my User Controls but that is always being set to the width of the containing StackPanel. If I try and measure the width of the Labels those too seem determined to stretch to their maximum possible width. It seems ridiculous that I would have to go through the whole rigmarole of pre-rendering the text of my labels just to get an idea of how wide my labels are supposed to be when the text is right there on the label already, so I assume I am doing something wrong.

How do I find the width of the text on my label, so I can move the GridSplitter to fit the left pane snugly?


问:
Stopping execution in refactored php code?
I have just refactored a php page to make it slightly easier to extend and maintain in the future and gotten stuck on quite a simple problem.

I have broken one method up into 3.

largemethod() has become something like this:

```<code>nowsmallmethod(){
  doSomeChecks();
  assignProduct();
  giveFeedbacktoUser();
}
</code>```

This is all good and well, the problem I am having is with doSomeChecks();

```<code>doSomeChecks(){
 if(something that shouldnt be true is true){
    return Controller->redirectBk();
 }
}
</code>```

The crux of the problem is that Controller-redirectBk first redirects when nowsmallmethod() has been completed. This means that the user is assigned a product even if a test fails. I am using a php framework called Silverstripe so I cant really change the behavior of Controller->redirectBk(). If I didnt have the checks in their own method then everything would work fine because the "return Controller->redirectBk();" would stop execution and redirect back. Whats the best way to stop execution in nowsmallmethod() when a test fails? I realise i could return a status code for an error and then stop execution but it seems an ugly way. Is there not a more elegant way? Another option would be if i could return something like this in doSomeChecks(), "return (return $controller->redirectBk())" but this is not valid php syntax and not particularly easy to read. Any help would be hugely appreciated.

Enjoy your weekend!
Cheers
Nick

答:
Use exceptions to handle situations like that:

```<code><?php
try {
    // some code
    if (!$check) {
         throw new Exception('Check has failed!');
    }
    // code after 'throw' will not be executed
}
catch(Exception $e) {
    //this is executed when exception is caught
}
?>
</code>```

If the exception is thrown in child method, the stack will roll back to the very first try/catch block. read more about the exceptions: http://php.net/manual/en/language.exceptions.php

Also, you can combine exceptions with transaction mechanism to handle database integrity.

Body:
I have just refactored a php page to make it slightly easier to extend and maintain in the future and gotten stuck on quite a simple problem.

I have broken one method up into 3.

largemethod() has become something like this:

nowsmallmethod(){
  doSomeChecks();
  assignProduct();
  giveFeedbacktoUser();
}

This is all good and well, the problem I am having is with doSomeChecks();

doSomeChecks(){
 if(something that shouldnt be true is true){
    return Controller->redirectBk();
 }
}

The crux of the problem is that Controller-redirectBk first redirects when nowsmallmethod() has been completed. This means that the user is assigned a product even if a test fails. I am using a php framework called Silverstripe so I cant really change the behavior of Controller->redirectBk(). If I didnt have the checks in their own method then everything would work fine because the "return Controller->redirectBk();" would stop execution and redirect back. Whats the best way to stop execution in nowsmallmethod() when a test fails? I realise i could return a status code for an error and then stop execution but it seems an ugly way. Is there not a more elegant way? Another option would be if i could return something like this in doSomeChecks(), "return (return $controller->redirectBk())" but this is not valid php syntax and not particularly easy to read. Any help would be hugely appreciated.

Enjoy your weekend!
Cheers
Nick

Body:
Use exceptions to handle situations like that:

<?php
try {
    // some code
    if (!$check) {
         throw new Exception('Check has failed!');
    }
    // code after 'throw' will not be executed
}
catch(Exception $e) {
    //this is executed when exception is caught
}
?>

If the exception is thrown in child method, the stack will roll back to the very first try/catch block. read more about the exceptions: http://php.net/manual/en/language.exceptions.php

Also, you can combine exceptions with transaction mechanism to handle database integrity.


问:
How to change the color of an element of a recyclerview?
I want to change color of my cardview in Recyclerview if a string matches a string from QR code. I am able to display a toast if string matches, but I also want to change color of that particular element in Recyclerview.

here is the code of selecting an item for scanning

```<code>recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                   tempString = passengerDataModelList.get(position).getPnr();
                   tempClickPosi = position;
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, 0);

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

Now on ActivityResult I will get the result:

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                    if(contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
///// Here I want to change the color of that item in recycler view
                    }else if(!contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String NOT MATCHED", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(this, "Error in scanning", Toast.LENGTH_SHORT).show();
                    }

                }
            }

        }
</code>```

So please help me to change the color of that particular item from activity. If need more info kindly comment.
Thank You

答:
According to my understanding, I guess You want to make background colorful if String is match. In RecyclerView you are inflating rows so your rows must have a Layout which You can use like below if your string is matched. The below code is only for understanding purpose. Customize it accordingly.  Here I am changing color of Recycler Item,  based on condition so i wrote this condition. You can modify it

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position==0){
    holder.itemView.setBackgroundColor(Color.BLACK);
}else{
    holder.itemView.setBackgroundColor(Color.GREY);
}
holder.mTextView.setText(mDataArray.get(position));
</code>```

}

Body:
I want to change color of my cardview in Recyclerview if a string matches a string from QR code. I am able to display a toast if string matches, but I also want to change color of that particular element in Recyclerview.

here is the code of selecting an item for scanning

recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                   tempString = passengerDataModelList.get(position).getPnr();
                   tempClickPosi = position;
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, 0);

                }
            }));

Now on ActivityResult I will get the result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
            if (requestCode == 0) {
                if (resultCode == RESULT_OK) {
                    String contents = intent.getStringExtra("SCAN_RESULT");
                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                    if(contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String MATCHED", Toast.LENGTH_SHORT).show();
///// Here I want to change the color of that item in recycler view
                    }else if(!contents.equalsIgnoreCase(tempString)){
                        Toast.makeText(this, "String NOT MATCHED", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(this, "Error in scanning", Toast.LENGTH_SHORT).show();
                    }

                }
            }

        }

So please help me to change the color of that particular item from activity. If need more info kindly comment.
Thank You

Body:
According to my understanding, I guess You want to make background colorful if String is match. In RecyclerView you are inflating rows so your rows must have a Layout which You can use like below if your string is matched. The below code is only for understanding purpose. Customize it accordingly.  Here I am changing color of Recycler Item,  based on condition so i wrote this condition. You can modify it

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position==0){
    holder.itemView.setBackgroundColor(Color.BLACK);
}else{
    holder.itemView.setBackgroundColor(Color.GREY);
}
holder.mTextView.setText(mDataArray.get(position));

}


问:
C++ pimpI mutex preventing usage of std::condicition_variable
C++/CLI is known to block the mutex header when a project is compiled using the -clr:pure or clr flag.
The error is reported here
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d4d082ff-ce43-478d-8386-0effed04b108/ccli-and-stdmutex?forum=vclanguage

The recommended solution seems to be to use the pimpI pattern. See here
Turn off clr option for header file with std::mutex

The problem I see is when using other std functions.
For example consider the std::condition_variable

```<code>mutexPimpI _mut;
std::unique_lock<mutexPimpI> lk(_mut); //Fine std::unique_lock is templated.
std::condition_variable _gate1;
_gate1.wait(lk); //Error wait expects std::unique_lock<std::mutex> as argument
</code>```

Is there any easy way to resolve / work around this problem?

答:
you can try using recursive__mutex class since objects wont be locked.
https://msdn.microsoft.com/en-us/library/hh921466.aspx refer this as well.</p>

Body:
C++/CLI is known to block the mutex header when a project is compiled using the -clr:pure or clr flag.
The error is reported here
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d4d082ff-ce43-478d-8386-0effed04b108/ccli-and-stdmutex?forum=vclanguage

The recommended solution seems to be to use the pimpI pattern. See here
Turn off clr option for header file with std::mutex

The problem I see is when using other std functions.
For example consider the std::condition_variable

mutexPimpI _mut;
std::unique_lock<mutexPimpI> lk(_mut); //Fine std::unique_lock is templated.
std::condition_variable _gate1;
_gate1.wait(lk); //Error wait expects std::unique_lock<std::mutex> as argument

Is there any easy way to resolve / work around this problem?


问:
How to make this function work despite the fact that a parameter is empty?
I have the following loop :

```<code>for i=1:size(voisins1_TSP,1)
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
end
</code>```

However, voisins1_Star(i,:) can be empty and MATLAB is not happy with that:

Index exceeds matrix dimensions.

   Error in Mainipulation (line 38)

```<code>cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
</code>```

How would it be possible to avoid this situation?

答:
You would need to post CalculCost to get a proper answer.

But going based on what you have posted, a solution to your problem is to make two functions, CalculCost and CalculCostEmpty, and put a check in the for loop:

```<code>for i=1:size(voisins1_TSP,1)
  if isempty(voisins1_TSP(i,:))
    cout(i)=CalculCostEmpty(voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  else
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  end
end
</code>```

Body:
I have the following loop :

for i=1:size(voisins1_TSP,1)
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
end

However, voisins1_Star(i,:) can be empty and MATLAB is not happy with that:

Index exceeds matrix dimensions.

   Error in Mainipulation (line 38)

cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);

How would it be possible to avoid this situation?

Body:
You would need to post CalculCost to get a proper answer.

But going based on what you have posted, a solution to your problem is to make two functions, CalculCost and CalculCostEmpty, and put a check in the for loop:

for i=1:size(voisins1_TSP,1)
  if isempty(voisins1_TSP(i,:))
    cout(i)=CalculCostEmpty(voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  else
    cout(i)=CalculCost(voisins1_TSP(i,:),voisins1_Indexes(i,:),voisins1_Star(i,:),ring_costs,star_costs);
  end
end


问:
Android:Kotlin TypeCastException: null cannot be cast to non-null type kotlin.String
I am new to Kotlin and I'm trying to develop a music app.

I'm getting this bug which I'm not able to solve. When I open my app the song list is displayed ,on clicking a song its redirecting to nowplaying screen but on clicking next or previous button my app crashes.

The logcat is giving an TypeCast error which I dont understand.

The Code is below:

```<code>class SongPlayingFragment : Fragment() {

var myActivity: Activity? = null
var mediaplayer: MediaPlayer? = null
var startTimeText: TextView? = null
var endTimeText: TextView? = null
var playpauseImageButton: ImageButton? = null
var previousImageButton: ImageButton? = null
var nextImageButton: ImageButton? = null
var loopImageButton: ImageButton? = null
var seekbar: SeekBar? = null
var songArtistView: TextView? = null
var songTitleView: TextView? = null
var shuffleImageButton: ImageButton? = null
var currentPosition: Int = 0
var fetchSongs: ArrayList<Songs>? = null
var currentSongHelper: CurrentSongHelper? = null
var audioVisualization: AudioVisualization? = null
var g1view: GLAudioVisualizationView? = null

object Staticated {
    var MY_PREFS_SHUFFLE = "Shuffle Feature"
    var MY_PREFS_LOOP = "Loop Feature"
}

var updateSongTime = object : Runnable {
    override fun run() {
        val getcurrent = mediaplayer?.currentPosition
        startTimeText?.setText(String.format("%d:%d",
                TimeUnit.MILLISECONDS.toMinutes(getcurrent?.toLong() as Long),
                TimeUnit.MILLISECONDS.toSeconds(getcurrent?.toLong() as Long) -
                        TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getcurrent?.toLong() as Long)
                        )))
        seekbar?.setProgress(getcurrent?.toInt() as Int)
        Handler().postDelayed(this, 1000)
    }
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    var view = inflater!!.inflate(R.layout.fragment_song_playing, container, false)
    seekbar = view?.findViewById(R.id.seekBar)
    startTimeText = view?.findViewById(R.id.startTime)
    endTimeText = view?.findViewById(R.id.endTime)
    playpauseImageButton = view?.findViewById(R.id.playPauseButton)
    nextImageButton = view?.findViewById(R.id.nextButton)
    previousImageButton = view?.findViewById(R.id.previousButton)
    loopImageButton = view?.findViewById(R.id.LoopButton)
    shuffleImageButton = view?.findViewById(R.id.shuffleButton)
    songArtistView = view?.findViewById(R.id.songArtist)
    songTitleView = view?.findViewById(R.id.songTitle)
    g1view = view?.findViewById(R.id.visualizer_view)

    return view
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    audioVisualization = g1view as AudioVisualization
}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    myActivity = context as Activity
}

override fun onAttach(activity: Activity?) {
    super.onAttach(activity)
    myActivity = activity
}

override fun onResume() {
    super.onResume()
    audioVisualization?.onResume()
}

override fun onPause() {
    audioVisualization?.onPause()
    super.onPause()
}

override fun onDestroyView() {
    audioVisualization?.release()
    super.onDestroyView()
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    currentSongHelper = CurrentSongHelper()
    currentSongHelper?.isPlaying = true
    currentSongHelper?.isLoop = false
    currentSongHelper?.isShuffle = false
    var path: String? = null
    var songTitle: String? = null
    var songArtist: String? = null
    var songId: Long = 0
    try {
        path = arguments.getString("path")
        songTitle = arguments.getString("songTitle")
        songArtist = arguments.getString("songArtist")
        songId = arguments.getInt("songId").toLong()
        currentPosition = arguments.getInt("songPosition")
        fetchSongs = arguments.getParcelableArrayList("songData")

        currentSongHelper?.songPath = path
        currentSongHelper?.songTitle = songTitle
        currentSongHelper?.songArtist = songArtist
        currentSongHelper?.songId = songId
        currentSongHelper?.currentPosition = currentPosition

        updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
    } catch(e: Exception) {
        e.printStackTrace()
    }
    mediaplayer = MediaPlayer()
    mediaplayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
    try {
        mediaplayer?.setDataSource(myActivity, Uri.parse(path))
        mediaplayer?.prepare()
    } catch (e: Exception) {
        e.printStackTrace()
    }

    mediaplayer?.start()
    processInformation(mediaplayer as MediaPlayer)
    if (currentSongHelper?.isPlaying as Boolean) {
        playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
    } else {
        playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
    }
    mediaplayer?.setOnCompletionListener {
        onSongComplete()

    }
    clickHandler()
    var visualizationHandler = DbmHandler.Factory.newVisualizerHandler(myActivity as Context, 0)
    audioVisualization?.linkTo(visualizationHandler)

    var prefsForShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)
    var isShuffleAllowed = prefsForShuffle?.getBoolean("feature", false)
    if (isShuffleAllowed as Boolean) {
        currentSongHelper?.isShuffle = true
        currentSongHelper?.isLoop = false
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)

        loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
    } else {
        currentSongHelper?.isShuffle = false
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
    }
    var prefsForLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)
    var isLoopAllowed = prefsForShuffle?.getBoolean("feature", false)
    if (isLoopAllowed as Boolean) {
        currentSongHelper?.isShuffle = false
        currentSongHelper?.isLoop = true
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)

        loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
    } else {
        loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
        currentSongHelper?.isLoop = false

    }
enter code here
}

fun clickHandler() {

    shuffleImageButton?.setOnClickListener({
        var editorShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
        var editorLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
        if (currentSongHelper?.isShuffle as Boolean) {
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
            currentSongHelper?.isShuffle = false
            editorShuffle?.putBoolean("feature", false)
            editorShuffle?.apply()
        } else {
            currentSongHelper?.isShuffle = true
            currentSongHelper?.isLoop = false
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
            editorShuffle?.putBoolean("feature", true)
            editorShuffle?.apply()
            editorLoop?.putBoolean("feature", false)
            editorLoop?.apply()
        }
    })
    nextImageButton?.setOnClickListener({
        currentSongHelper?.isPlaying = true
        if (currentSongHelper?.isShuffle as Boolean) {
            playNext("PlayNextLikeNormalShuffle")
        } else {
            playNext("PlayNextNormal")
        }
    })
    previousImageButton?.setOnClickListener({
        currentSongHelper?.isPlaying = true
        if (currentSongHelper?.isLoop as Boolean) {
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
        }
        playPrevious()
    })
    loopImageButton?.setOnClickListener({
        var editorShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
        var editorLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
        if (currentSongHelper?.isLoop as Boolean) {
            currentSongHelper?.isLoop = false
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
            editorLoop?.putBoolean("feature", false)
            editorLoop?.apply()
        } else {
            currentSongHelper?.isLoop = true
            currentSongHelper?.isShuffle = false
            loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
            editorShuffle?.putBoolean("feature", false)
            editorShuffle?.apply()
            editorLoop?.putBoolean("feature", true)
            editorLoop?.apply()
        }
    })
    playpauseImageButton?.setOnClickListener({
        if (mediaplayer?.isPlaying as Boolean) {
            mediaplayer?.pause()
            currentSongHelper?.isPlaying = false
            playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
        } else {
            mediaplayer?.start()
            currentSongHelper?.isPlaying = true
            playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
        }

    })

}

fun playNext(check: String) {
    if (check.equals("PlayNextNormal", true)) {
        currentPosition = currentPosition + 1

    } else if (check.equals("PlayNextLikeNormalShuffle", true)) {
        var randomObject = Random()
        var randomPosition = randomObject.nextInt(fetchSongs?.size?.plus(1) as Int)
        currentPosition = randomPosition

    }
    if (currentPosition == fetchSongs?.size) {
        currentPosition = 0
    }
    currentSongHelper?.isLoop = false
    var nextSong = fetchSongs?.get(currentPosition)
    currentSongHelper?.songPath = nextSong?.songData
    currentSongHelper?.songTitle = nextSong?.songTitle
    currentSongHelper?.currentPosition = currentPosition
    currentSongHelper?.songId = nextSong?.songId as Long

    updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
    mediaplayer?.reset()
    try {
        mediaplayer?.setDataSource(myActivity, Uri.parse(currentSongHelper?.songPath))
        mediaplayer?.prepare()
        mediaplayer?.start()
        processInformation(mediaplayer as MediaPlayer)
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

fun playPrevious() {
    currentPosition = currentPosition - 1

    if (currentPosition == -1) {
        currentPosition = 0
    }
    if (currentSongHelper?.isPlaying as Boolean) {
        playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
    } else {
        playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
    }
    currentSongHelper?.isLoop = false
    var nextSong = fetchSongs?.get(currentPosition)
    currentSongHelper?.songPath = nextSong?.songData
    currentSongHelper?.songTitle = nextSong?.songTitle
    currentSongHelper?.currentPosition = currentPosition
    currentSongHelper?.songId = nextSong?.songId as Long

    updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)

    mediaplayer?.reset()
    try {
        mediaplayer?.setDataSource(activity, Uri.parse(currentSongHelper?.songPath))
        mediaplayer?.prepare()
        mediaplayer?.start()
        processInformation(mediaplayer as MediaPlayer)
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

fun onSongComplete() {
    if (currentSongHelper?.isShuffle as Boolean) {
        playNext("PlayNextLikeNormalShuffle")
        currentSongHelper?.isPlaying = true
    } else {
        if (currentSongHelper?.isLoop as Boolean) {
            currentSongHelper?.isPlaying = true
            var nextSong = fetchSongs?.get(currentPosition)

            currentSongHelper?.songTitle = nextSong?.songTitle
            currentSongHelper?.songPath = nextSong?.songData
            currentSongHelper?.currentPosition = currentPosition
            currentSongHelper?.songId = nextSong?.songId as Long

            updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
            mediaplayer?.reset()
            try {
                mediaplayer?.setDataSource(myActivity, Uri.parse(currentSongHelper?.songPath))
                mediaplayer?.prepare()
                mediaplayer?.start()

            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else {
            playNext("PlayNextNormal")
            currentSongHelper?.isPlaying = true
        }
    }

}

fun updateTextViews(songtitle: String, songArtist: String) {
    songTitleView?.setText(songtitle)
    songArtistView?.setText(songArtist)
}

fun processInformation(mediaPlayer: MediaPlayer) {
    val finalTime = mediaPlayer.duration
    val startTime = mediaPlayer.currentPosition
    seekbar?.max = finalTime
    startTimeText?.setText(String.format("%d: %d",
            TimeUnit.MILLISECONDS.toMinutes(startTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(startTime.toLong()) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(startTime?.toLong()))
    ))
    endTimeText?.setText(String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(finalTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(finalTime.toLong()) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(finalTime?.toLong())))
    )
    seekbar?.setProgress(startTime)
    Handler().postDelayed(updateSongTime, 1000)
}
</code>```

}

LOGS:

```<code>12-07 20:30:27.447 28230-28230/com.example.sanjanaadmin.echo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sanjanaadmin.echo, PID: 28230
    kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String
        at com.example.sanjanaadmin.echo.fragments.SongPlayingFragment.playNext(SongPlayingFragment.kt:314)
        at com.example.sanjanaadmin.echo.fragments.SongPlayingFragment$clickHandler$2.onClick(SongPlayingFragment.kt:250)
        at android.view.View.performClick(View.java:5268)
        at android.view.View$PerformClick.run(View.java:21550)
        at android.os.Handler.handleCallback(Handler.java:822)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5811)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
</code>```

答:
You can also try one of this solutions:

provide default value

currentSongHelper?.songTitle?:"default song title"

throw inline exception

currentSongHelper?.songTitle?: throw NullpointerException("title is null")

safe cast

currentSongHelper?.songTitle as? String

Body:
I am new to Kotlin and I'm trying to develop a music app.

I'm getting this bug which I'm not able to solve. When I open my app the song list is displayed ,on clicking a song its redirecting to nowplaying screen but on clicking next or previous button my app crashes.

The logcat is giving an TypeCast error which I dont understand.

The Code is below:

class SongPlayingFragment : Fragment() {

var myActivity: Activity? = null
var mediaplayer: MediaPlayer? = null
var startTimeText: TextView? = null
var endTimeText: TextView? = null
var playpauseImageButton: ImageButton? = null
var previousImageButton: ImageButton? = null
var nextImageButton: ImageButton? = null
var loopImageButton: ImageButton? = null
var seekbar: SeekBar? = null
var songArtistView: TextView? = null
var songTitleView: TextView? = null
var shuffleImageButton: ImageButton? = null
var currentPosition: Int = 0
var fetchSongs: ArrayList<Songs>? = null
var currentSongHelper: CurrentSongHelper? = null
var audioVisualization: AudioVisualization? = null
var g1view: GLAudioVisualizationView? = null

object Staticated {
    var MY_PREFS_SHUFFLE = "Shuffle Feature"
    var MY_PREFS_LOOP = "Loop Feature"
}

var updateSongTime = object : Runnable {
    override fun run() {
        val getcurrent = mediaplayer?.currentPosition
        startTimeText?.setText(String.format("%d:%d",
                TimeUnit.MILLISECONDS.toMinutes(getcurrent?.toLong() as Long),
                TimeUnit.MILLISECONDS.toSeconds(getcurrent?.toLong() as Long) -
                        TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getcurrent?.toLong() as Long)
                        )))
        seekbar?.setProgress(getcurrent?.toInt() as Int)
        Handler().postDelayed(this, 1000)
    }
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    var view = inflater!!.inflate(R.layout.fragment_song_playing, container, false)
    seekbar = view?.findViewById(R.id.seekBar)
    startTimeText = view?.findViewById(R.id.startTime)
    endTimeText = view?.findViewById(R.id.endTime)
    playpauseImageButton = view?.findViewById(R.id.playPauseButton)
    nextImageButton = view?.findViewById(R.id.nextButton)
    previousImageButton = view?.findViewById(R.id.previousButton)
    loopImageButton = view?.findViewById(R.id.LoopButton)
    shuffleImageButton = view?.findViewById(R.id.shuffleButton)
    songArtistView = view?.findViewById(R.id.songArtist)
    songTitleView = view?.findViewById(R.id.songTitle)
    g1view = view?.findViewById(R.id.visualizer_view)

    return view
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    audioVisualization = g1view as AudioVisualization
}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    myActivity = context as Activity
}

override fun onAttach(activity: Activity?) {
    super.onAttach(activity)
    myActivity = activity
}

override fun onResume() {
    super.onResume()
    audioVisualization?.onResume()
}

override fun onPause() {
    audioVisualization?.onPause()
    super.onPause()
}

override fun onDestroyView() {
    audioVisualization?.release()
    super.onDestroyView()
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    currentSongHelper = CurrentSongHelper()
    currentSongHelper?.isPlaying = true
    currentSongHelper?.isLoop = false
    currentSongHelper?.isShuffle = false
    var path: String? = null
    var songTitle: String? = null
    var songArtist: String? = null
    var songId: Long = 0
    try {
        path = arguments.getString("path")
        songTitle = arguments.getString("songTitle")
        songArtist = arguments.getString("songArtist")
        songId = arguments.getInt("songId").toLong()
        currentPosition = arguments.getInt("songPosition")
        fetchSongs = arguments.getParcelableArrayList("songData")

        currentSongHelper?.songPath = path
        currentSongHelper?.songTitle = songTitle
        currentSongHelper?.songArtist = songArtist
        currentSongHelper?.songId = songId
        currentSongHelper?.currentPosition = currentPosition

        updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
    } catch(e: Exception) {
        e.printStackTrace()
    }
    mediaplayer = MediaPlayer()
    mediaplayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
    try {
        mediaplayer?.setDataSource(myActivity, Uri.parse(path))
        mediaplayer?.prepare()
    } catch (e: Exception) {
        e.printStackTrace()
    }

    mediaplayer?.start()
    processInformation(mediaplayer as MediaPlayer)
    if (currentSongHelper?.isPlaying as Boolean) {
        playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
    } else {
        playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
    }
    mediaplayer?.setOnCompletionListener {
        onSongComplete()

    }
    clickHandler()
    var visualizationHandler = DbmHandler.Factory.newVisualizerHandler(myActivity as Context, 0)
    audioVisualization?.linkTo(visualizationHandler)

    var prefsForShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)
    var isShuffleAllowed = prefsForShuffle?.getBoolean("feature", false)
    if (isShuffleAllowed as Boolean) {
        currentSongHelper?.isShuffle = true
        currentSongHelper?.isLoop = false
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)

        loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
    } else {
        currentSongHelper?.isShuffle = false
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
    }
    var prefsForLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)
    var isLoopAllowed = prefsForShuffle?.getBoolean("feature", false)
    if (isLoopAllowed as Boolean) {
        currentSongHelper?.isShuffle = false
        currentSongHelper?.isLoop = true
        shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)

        loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
    } else {
        loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
        currentSongHelper?.isLoop = false

    }
enter code here
}

fun clickHandler() {

    shuffleImageButton?.setOnClickListener({
        var editorShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
        var editorLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
        if (currentSongHelper?.isShuffle as Boolean) {
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
            currentSongHelper?.isShuffle = false
            editorShuffle?.putBoolean("feature", false)
            editorShuffle?.apply()
        } else {
            currentSongHelper?.isShuffle = true
            currentSongHelper?.isLoop = false
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
            editorShuffle?.putBoolean("feature", true)
            editorShuffle?.apply()
            editorLoop?.putBoolean("feature", false)
            editorLoop?.apply()
        }
    })
    nextImageButton?.setOnClickListener({
        currentSongHelper?.isPlaying = true
        if (currentSongHelper?.isShuffle as Boolean) {
            playNext("PlayNextLikeNormalShuffle")
        } else {
            playNext("PlayNextNormal")
        }
    })
    previousImageButton?.setOnClickListener({
        currentSongHelper?.isPlaying = true
        if (currentSongHelper?.isLoop as Boolean) {
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
        }
        playPrevious()
    })
    loopImageButton?.setOnClickListener({
        var editorShuffle = myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
        var editorLoop = myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
        if (currentSongHelper?.isLoop as Boolean) {
            currentSongHelper?.isLoop = false
            loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
            editorLoop?.putBoolean("feature", false)
            editorLoop?.apply()
        } else {
            currentSongHelper?.isLoop = true
            currentSongHelper?.isShuffle = false
            loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
            shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
            editorShuffle?.putBoolean("feature", false)
            editorShuffle?.apply()
            editorLoop?.putBoolean("feature", true)
            editorLoop?.apply()
        }
    })
    playpauseImageButton?.setOnClickListener({
        if (mediaplayer?.isPlaying as Boolean) {
            mediaplayer?.pause()
            currentSongHelper?.isPlaying = false
            playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
        } else {
            mediaplayer?.start()
            currentSongHelper?.isPlaying = true
            playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
        }

    })

}

fun playNext(check: String) {
    if (check.equals("PlayNextNormal", true)) {
        currentPosition = currentPosition + 1

    } else if (check.equals("PlayNextLikeNormalShuffle", true)) {
        var randomObject = Random()
        var randomPosition = randomObject.nextInt(fetchSongs?.size?.plus(1) as Int)
        currentPosition = randomPosition

    }
    if (currentPosition == fetchSongs?.size) {
        currentPosition = 0
    }
    currentSongHelper?.isLoop = false
    var nextSong = fetchSongs?.get(currentPosition)
    currentSongHelper?.songPath = nextSong?.songData
    currentSongHelper?.songTitle = nextSong?.songTitle
    currentSongHelper?.currentPosition = currentPosition
    currentSongHelper?.songId = nextSong?.songId as Long

    updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
    mediaplayer?.reset()
    try {
        mediaplayer?.setDataSource(myActivity, Uri.parse(currentSongHelper?.songPath))
        mediaplayer?.prepare()
        mediaplayer?.start()
        processInformation(mediaplayer as MediaPlayer)
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

fun playPrevious() {
    currentPosition = currentPosition - 1

    if (currentPosition == -1) {
        currentPosition = 0
    }
    if (currentSongHelper?.isPlaying as Boolean) {
        playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
    } else {
        playpauseImageButton?.setBackgroundResource(R.drawable.play_icon)
    }
    currentSongHelper?.isLoop = false
    var nextSong = fetchSongs?.get(currentPosition)
    currentSongHelper?.songPath = nextSong?.songData
    currentSongHelper?.songTitle = nextSong?.songTitle
    currentSongHelper?.currentPosition = currentPosition
    currentSongHelper?.songId = nextSong?.songId as Long

    updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)

    mediaplayer?.reset()
    try {
        mediaplayer?.setDataSource(activity, Uri.parse(currentSongHelper?.songPath))
        mediaplayer?.prepare()
        mediaplayer?.start()
        processInformation(mediaplayer as MediaPlayer)
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

fun onSongComplete() {
    if (currentSongHelper?.isShuffle as Boolean) {
        playNext("PlayNextLikeNormalShuffle")
        currentSongHelper?.isPlaying = true
    } else {
        if (currentSongHelper?.isLoop as Boolean) {
            currentSongHelper?.isPlaying = true
            var nextSong = fetchSongs?.get(currentPosition)

            currentSongHelper?.songTitle = nextSong?.songTitle
            currentSongHelper?.songPath = nextSong?.songData
            currentSongHelper?.currentPosition = currentPosition
            currentSongHelper?.songId = nextSong?.songId as Long

            updateTextViews(currentSongHelper?.songTitle as String, currentSongHelper?.songArtist as String)
            mediaplayer?.reset()
            try {
                mediaplayer?.setDataSource(myActivity, Uri.parse(currentSongHelper?.songPath))
                mediaplayer?.prepare()
                mediaplayer?.start()

            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else {
            playNext("PlayNextNormal")
            currentSongHelper?.isPlaying = true
        }
    }

}

fun updateTextViews(songtitle: String, songArtist: String) {
    songTitleView?.setText(songtitle)
    songArtistView?.setText(songArtist)
}

fun processInformation(mediaPlayer: MediaPlayer) {
    val finalTime = mediaPlayer.duration
    val startTime = mediaPlayer.currentPosition
    seekbar?.max = finalTime
    startTimeText?.setText(String.format("%d: %d",
            TimeUnit.MILLISECONDS.toMinutes(startTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(startTime.toLong()) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(startTime?.toLong()))
    ))
    endTimeText?.setText(String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(finalTime.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(finalTime.toLong()) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(finalTime?.toLong())))
    )
    seekbar?.setProgress(startTime)
    Handler().postDelayed(updateSongTime, 1000)
}

}

LOGS:

12-07 20:30:27.447 28230-28230/com.example.sanjanaadmin.echo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sanjanaadmin.echo, PID: 28230
    kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String
        at com.example.sanjanaadmin.echo.fragments.SongPlayingFragment.playNext(SongPlayingFragment.kt:314)
        at com.example.sanjanaadmin.echo.fragments.SongPlayingFragment$clickHandler$2.onClick(SongPlayingFragment.kt:250)
        at android.view.View.performClick(View.java:5268)
        at android.view.View$PerformClick.run(View.java:21550)
        at android.os.Handler.handleCallback(Handler.java:822)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5811)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)


答:
10'000 objects really isn't much.

The below should suffice.

```<code>foreach(cItem Item in ItemList)
{
     if(regex.match(Item.Name, "expression"))
         //Add Item to autocomplete results;

         //Break if more than 10 matches

}

for(i = 0; i < 10 && i < autocomplete_results.Length; ++i)
{
          // display first 10 matches
}
</code>```

Title: Autocomplete from 10 000 items in .NET

Body:
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary

Body:
10'000 objects really isn't much.

The below should suffice.

foreach(cItem Item in ItemList)
{
     if(regex.match(Item.Name, "expression"))
         //Add Item to autocomplete results;

         //Break if more than 10 matches

}

for(i = 0; i < 10 && i < autocomplete_results.Length; ++i)
{
          // display first 10 matches
}


问:
Knockout foreach with a where clause
This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..

```<code>Where ItemStatus.Active is 0 in an enum in c# ( backend )

@foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{
  <div class="someclass”>
  <span class="label">Name:</span>
  <span class="value">@employee.Name</span>
  </div>
}
</code>```

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

Thank you

答:
Razor runs server-side. So, you can't use Employees with knockout bindings which are apllied client-side. You need to hand over this Employees data to a javascript variable, and then bind that using knockout which will run client-side, after the page loads.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script>
    // cretes a js array of active employees
    var activeEmployees = @Html.Raw(JsonConvert.SerializeObject(Employees.Where(x => x.Status == ItemStatus.Active)));

    var viewModel = {
      Employees: ko.observableArray(activeEmployees)
    }

    ko.applyBindings(viewModel);
</script>
</code>```

Use the foreach binding in your HTML like this (Here Employees refers to the property of your knockout viewModel, not MVC)

```<code><!-- ko foreach: Employees -->
<div class="someclass">
  <span class="label">Name:</span>
  <span class="value" data-bind="text:Name"></span>
</div>
<!-- /ko -->
</code>```

You also need to add @using Newtonsoft.Json to the top your cshtml file for JsonConvert

Title: Knockout foreach with a where clause

Body:
This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..

Where ItemStatus.Active is 0 in an enum in c# ( backend )

@foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{

  Name:
  @employee.Name

}

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

Thank you

Body:
Razor runs server-side. So, you can't use Employees with knockout bindings which are apllied client-side. You need to hand over this Employees data to a javascript variable, and then bind that using knockout which will run client-side, after the page loads.

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script>
    // cretes a js array of active employees
    var activeEmployees = @Html.Raw(JsonConvert.SerializeObject(Employees.Where(x => x.Status == ItemStatus.Active)));

    var viewModel = {
      Employees: ko.observableArray(activeEmployees)
    }

    ko.applyBindings(viewModel);
</script>

Use the foreach binding in your HTML like this (Here Employees refers to the property of your knockout viewModel, not MVC)

<!-- ko foreach: Employees -->
<div class="someclass">
  <span class="label">Name:</span>
  <span class="value" data-bind="text:Name"></span>
</div>
<!-- /ko -->

You also need to add @using Newtonsoft.Json to the top your cshtml file for JsonConvert


问:
How to write in twig template view?
PHP code for Drupal 7:

```<code><?php foreach ($rows as $row_number => $columns): ?>
    <?php foreach ($columns as $column_number => $item): ?>
        <?php print $item; ?>
    <?php endforeach; ?>
<?php endforeach; ?>
</code>```

I wrote this, but i'm getting error in Drupal 8. Code:

```<code>{% foreach row_number, columns in rows %}
    {% foreach column_number, item in columns %}
        {{ item }}
    {% endforeach %}
{% endforeach %}
</code>```

答:
Use for in twig instead of foreach

```<code>{% for row_number, columns in rows %}

    {% for column_number, item in columns %}

        {{ item }}

    {% endfor %}

{% endfor %}
</code>```

Title: How to write in twig template view?

Body:
PHP code for Drupal 7:

<?php foreach ($rows as $row_number => $columns): ?>
    <?php foreach ($columns as $column_number => $item): ?>
        <?php print $item; ?>
    <?php endforeach; ?>
<?php endforeach; ?>

I wrote this, but i'm getting error in Drupal 8. Code:

{% foreach row_number, columns in rows %}
    {% foreach column_number, item in columns %}
        {{ item }}
    {% endforeach %}
{% endforeach %}

Body:
Use for in twig instead of foreach

{% for row_number, columns in rows %}

    {% for column_number, item in columns %}

        {{ item }}

    {% endfor %}

{% endfor %}


问:
Getting the sum of 2 different indices from 2 separate arrays
Very new to Java, so please bear with me here. I have to write a program based on the resident status of a student to determine the total cost for the term.  I must use Abstract methods (separate class), and then create classes based on Tuition for Full time and Part Time. The full and part-time classes must use arrays.  I probably wrote the array list wrong, but this is what I have so far, and I need to create an object "county" so I can calculate the cost for the student who resides in the county.

How do I call the tuition and capital fee to add them together for the index C only? Or, would it be easier if I write an array for just county with the tuition and capital fee then sum those together, then add that total to the other costs listed?  Also, when I try to create the object under county, it comes up with an error.  I will be using Radio Buttons to determine what the resident status of the student is, (not sure if that changes things for my calculations). Any help is appreciated.

The abstract class:

```<code>package collegecost1;

public abstract class collegeAbMain {
    public abstract double tuition();
    public abstract double capitalFee();
    public abstract double accidentIns();
    public abstract double collegeFee();

    //public abstract double county();
    //public abstract double outCounty();
    //public abstract double outState();

}
</code>```

fullTime class:

```<code> package collegecost1;

 public class fullTime extends collegeAbMain {
     double  C;
     double OC;
     double OS;
     double Ins;
     double fee;
     double total;

     @Override
     public double tuition() {
         double resident = 3;
         double [] tuition = new double [(int) resident];

         // I have to use the variables C, OC, and OS
         tuition[0] = C;
         C = 1571.25;

         tuition[1] = OC;
         OC = 3142.50;

         tuition[2] = OS;
         OS = 4713.75;
         return resident;
     }

     @Override
     public double capitalFee() {
         double resident = 3;
         double[] capitalFee = new double [(int) resident];

         capitalFee[0] = C;
         C = 0.00;

         capitalFee[1] = OC;
         OC = 78.00;

         capitalFee[2] = OS;
         OS = 78.00;

         return resident ;
     }

     @Override
     public double accidentIns() {
        Ins = 0.00;
        return Ins;
    }

    @Override
    public double collegeFee() {
        fee = 50.40;
        return fee;
    }

    public double county() {
     county total = new county()
    //ERROR (wants me to create class or interface for the 1st word county
    // have written objects the exact same way in other programs and never
    // had an issue.
        {
          //NOT THE ACTUAL CODE

                  //total = (index[0] from resident tution +
          //index [0] from resident caplitalFee)
                  //+ (Ins) + (fee);

              return total();
        }

    }
}
</code>```

答:
The full and part time classes must use Array's

I will be using Radio Buttons to determine what the resident status of the student is

You have not explained enough for us to know how your methods should act or what it can mean that "classes must use arrays". But since you are going to input "to determine what the resident status of the student is", presumably you must tell some object what county you are interested in so that it can give the right info. So the object state involves info for each county. That suggests arrays to represent the object state. Also there must be some way to input that information. (Although not necessarily through an interface/object accessible to all users of the four methods you list & a method giving what county they are to report about.) It seems that you do not have a clear idea of what you are supposed to do. So find out.

Body:
Very new to Java, so please bear with me here. I have to write a program based on the resident status of a student to determine the total cost for the term.  I must use Abstract methods (separate class), and then create classes based on Tuition for Full time and Part Time. The full and part-time classes must use arrays.  I probably wrote the array list wrong, but this is what I have so far, and I need to create an object "county" so I can calculate the cost for the student who resides in the county.

How do I call the tuition and capital fee to add them together for the index C only? Or, would it be easier if I write an array for just county with the tuition and capital fee then sum those together, then add that total to the other costs listed?  Also, when I try to create the object under county, it comes up with an error.  I will be using Radio Buttons to determine what the resident status of the student is, (not sure if that changes things for my calculations). Any help is appreciated.

The abstract class:

package collegecost1;

public abstract class collegeAbMain {
    public abstract double tuition();
    public abstract double capitalFee();
    public abstract double accidentIns();
    public abstract double collegeFee();

    //public abstract double county();
    //public abstract double outCounty();
    //public abstract double outState();

}

fullTime class:

 package collegecost1;

 public class fullTime extends collegeAbMain {
     double  C;
     double OC;
     double OS;
     double Ins;
     double fee;
     double total;

     @Override
     public double tuition() {
         double resident = 3;
         double [] tuition = new double [(int) resident];

         // I have to use the variables C, OC, and OS
         tuition[0] = C;
         C = 1571.25;

         tuition[1] = OC;
         OC = 3142.50;

         tuition[2] = OS;
         OS = 4713.75;
         return resident;
     }

     @Override
     public double capitalFee() {
         double resident = 3;
         double[] capitalFee = new double [(int) resident];

         capitalFee[0] = C;
         C = 0.00;

         capitalFee[1] = OC;
         OC = 78.00;

         capitalFee[2] = OS;
         OS = 78.00;

         return resident ;
     }

     @Override
     public double accidentIns() {
        Ins = 0.00;
        return Ins;
    }

    @Override
    public double collegeFee() {
        fee = 50.40;
        return fee;
    }

    public double county() {
     county total = new county()
    //ERROR (wants me to create class or interface for the 1st word county
    // have written objects the exact same way in other programs and never
    // had an issue.
        {
          //NOT THE ACTUAL CODE

                  //total = (index[0] from resident tution +
          //index [0] from resident caplitalFee)
                  //+ (Ins) + (fee);

              return total();
        }

    }
}


问:
difference between kotlin also, apply, let, use, takeIf and takeUnless in Kotlin
I read many Kotlin documents about these items. But I can't understand so clearly.

What is the use of Kotlin let, also, takeIf and takeUnless in detail?

I need an example of each item. Please don't post the Kotlin documentation. I need a real-time example and use cases of these items.

答:
let, also, apply, takeIf, takeUnless are extension functions in Kotlin.

To understand these function you have to understand Extension functions and Lambda functions in Kotlin.

Extension Function:

By the use of extension function, we can create a function for a class without inheriting a class.

Kotlin, similar to C# and Gosu, provides the ability to extend a class
with new functionality without having to inherit from the class or use
any type of design pattern such as Decorator. This is done via special
declarations called extensions. Kotlin supports extension functions
and extension properties.

So, to find if only numbers in the String, you can create a method like below without inheriting String class.

```<code>fun String.isNumber(): Boolean = this.matches("[0-9]+".toRegex())
</code>```

you can use the above extension function like this,

```<code>val phoneNumber = "8899665544"
println(phoneNumber.isNumber())
</code>```

which is prints true.

Lambda Functions:

Lambda functions are just like Interface (contains only one method. Also called as Single Abstract Method) in Java. From Java 8 lambdas are available in java also. In Kotlin lambdas used everywhere. Mostly lambdas passed as a parameter in a function.

Example:

```<code>fun String.isNumber(block: () -> Unit): Boolean {
    return if (this.matches("[0-9]+".toRegex())) {
        block()
        true
    } else false
}
</code>```

You can see, the block is a lambda function and it is passed as a parameter. You can use the above function like this,

```<code>val phoneNumber = "8899665544"
phoneNumber.isNumber {
   println("Block executed")
}
</code>```

The above function will print like this,

```<code>Block executed
</code>```

I hope, now you got an idea about Extension functions and Lambda functions. Now we can go to Extension functions one by one.

let

```<code>public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
</code>```

Two Types T and R used in the above function.

```<code>T.let
</code>```

T could be any object like String, number, or any type. So you can invoke this function with any objects.

```<code>block: (T) -> R
</code>```

You can see the lambda function In parameter of let the invoking object is passed as a parameter of the function. So you can use the invoking class object inside the function. then it returns the R (another object).

Example:

```<code>val phoneNumber = "8899665544"
val numberAndCount: Pair<Int, Int> = phoneNumber.let { it.toInt() to it.count() }
</code>```

In above example let takes String as a parameter of its lambda function and it returns Pair in return.

In the same way, other extension functions works.

also

```<code>public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
</code>```

extension function also takes the invoking class as a lambda function parameter and returns nothing.

Example:

```<code>val phoneNumber = "8899665544"
phoneNumber.also { number ->
    println(number.contains("8"))
    println(number.length)
 }
</code>```

apply

```<code>public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
</code>```

Same as also but the same invoking object passed as the function so you can use the functions and other properties without calling it or parameter name.

Example:

```<code>val phoneNumber = "8899665544"
phoneNumber.apply {
    println(contains("8"))
    println(length)
 }
</code>```

You can see in the above example the functions of String class directly invoked inside the lambda funtion.

takeIf

```<code>public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
</code>```

Example:

```<code>val phoneNumber = "8899665544"
val number = phoneNumber.takeIf { it.matches("[0-9]+".toRegex()) }
</code>```

In above example number will have a string of phoneNumber only it matches the regex. Otherwise, it will be null.

takeUnless

```<code>public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null
</code>```

It is the reverse of takeIf.

Example:

```<code>val phoneNumber = "8899665544"
val number = phoneNumber.takeUnless { it.matches("[0-9]+".toRegex()) }
</code>```

number will have a string of phoneNumber only if not matches the regex. Otherwise, it will be null.

Body:
let, also, apply, takeIf, takeUnless are extension functions in Kotlin.

To understand these function you have to understand Extension functions and Lambda functions in Kotlin.

Extension Function:

By the use of extension function, we can create a function for a class without inheriting a class.

Kotlin, similar to C# and Gosu, provides the ability to extend a class
with new functionality without having to inherit from the class or use
any type of design pattern such as Decorator. This is done via special
declarations called extensions. Kotlin supports extension functions
and extension properties.

So, to find if only numbers in the String, you can create a method like below without inheriting String class.

fun String.isNumber(): Boolean = this.matches("[0-9]+".toRegex())

you can use the above extension function like this,

val phoneNumber = "8899665544"
println(phoneNumber.isNumber())

which is prints true.

Lambda Functions:

Lambda functions are just like Interface (contains only one method. Also called as Single Abstract Method) in Java. From Java 8 lambdas are available in java also. In Kotlin lambdas used everywhere. Mostly lambdas passed as a parameter in a function.

Example:

fun String.isNumber(block: () -> Unit): Boolean {
    return if (this.matches("[0-9]+".toRegex())) {
        block()
        true
    } else false
}

You can see, the block is a lambda function and it is passed as a parameter. You can use the above function like this,

val phoneNumber = "8899665544"
phoneNumber.isNumber {
   println("Block executed")
}

The above function will print like this,

Block executed

I hope, now you got an idea about Extension functions and Lambda functions. Now we can go to Extension functions one by one.

let

public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

Two Types T and R used in the above function.

T.let

T could be any object like String, number, or any type. So you can invoke this function with any objects.

block: (T) -> R

You can see the lambda function In parameter of let the invoking object is passed as a parameter of the function. So you can use the invoking class object inside the function. then it returns the R (another object).

Example:

val phoneNumber = "8899665544"
val numberAndCount: Pair<Int, Int> = phoneNumber.let { it.toInt() to it.count() }

In above example let takes String as a parameter of its lambda function and it returns Pair in return.

In the same way, other extension functions works.

also

public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

extension function also takes the invoking class as a lambda function parameter and returns nothing.

Example:

val phoneNumber = "8899665544"
phoneNumber.also { number ->
    println(number.contains("8"))
    println(number.length)
 }

apply

public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

Same as also but the same invoking object passed as the function so you can use the functions and other properties without calling it or parameter name.

Example:

val phoneNumber = "8899665544"
phoneNumber.apply {
    println(contains("8"))
    println(length)
 }

You can see in the above example the functions of String class directly invoked inside the lambda funtion.

takeIf

public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null

Example:

val phoneNumber = "8899665544"
val number = phoneNumber.takeIf { it.matches("[0-9]+".toRegex()) }

In above example number will have a string of phoneNumber only it matches the regex. Otherwise, it will be null.

takeUnless

public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null

It is the reverse of takeIf.

Example:

val phoneNumber = "8899665544"
val number = phoneNumber.takeUnless { it.matches("[0-9]+".toRegex()) }

number will have a string of phoneNumber only if not matches the regex. Otherwise, it will be null.