问:
Shared elements transition between fragments not animating
The desired shared elements don't animate, they just appear/fade in instead of moving from one view to the other. What can possibly be wrong? I've read multiple tutorials and none of them has worked. It surely is a small thing though...
I'm testing on a AVD 6.0.

Thanks for your help!

The app starts through MainActivity loading the starting fragment

```<code>public void openFindDancerFragment() {
    FindDancerFragment findDancerFragment = new FindDancerFragment();
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.main_fragment_container, findDancerFragment)
            .addToBackStack(null)
            .commit();
}
</code>```

Which brings you to the Starting fragment

Start fragment.java

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_find_dancer, container, false);
    DancerItemAdapter adapter = new DancerItemAdapter(getContext(), dancers);
    ListView dancersView = (ListView)v.findViewById(R.id.dancersListView);

    dancersView.setAdapter(adapter);
    dancersView.setOnItemClickListener(this);
    return v;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ImageView imageView = (ImageView) view.findViewById(R.id.dancerIcon);
    TextView textView = (TextView) view.findViewById(R.id.dancerName);
    String imageTransitionName = getString(R.string.dancer_icon_transition);
    String textTransitionName = getString(R.string.dancer_name_transition);
    DancerDetailsFragment detailsFragment = new DancerDetailsFragment();

    Bundle bundle = new Bundle();
    bundle.putString("NAME_TEXT", textView.getText().toString());
    bundle.putParcelable("IMAGE", ((BitmapDrawable) imageView.getDrawable()).getBitmap());
    detailsFragment.setArguments(bundle);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setSharedElementReturnTransition(TransitionInflater.from(
                getActivity()).inflateTransition(android.R.transition.fade));
        setExitTransition(TransitionInflater.from(
                getActivity()).inflateTransition(android.R.transition.fade));

        detailsFragment.setSharedElementEnterTransition(TransitionInflater.from(
                getActivity()).inflateTransition(R.transition.dancer_item_transition));
        detailsFragment.setEnterTransition(TransitionInflater.from(
                getActivity()).inflateTransition(R.transition.dancer_item_transition));
    }

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .addToBackStack(null)
            .addSharedElement(imageView, imageTransitionName)
            .addSharedElement(textView, textTransitionName)
            .replace(R.id.find_dancer_fragment, detailsFragment)
            .commit();
}
</code>```

Start fragment XML

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/find_dancer_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
tools:context="com.example.ginold.dance.Fragments.FindDancerFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">
    <ListView
        android:id="@+id/dancersListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

Clicking on an list item brings you to the end fragment:

End fragment

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(R.transition.dancer_item_transition));
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle bundle = getArguments();
    Bitmap imageBitmap = null;
    String dancerName = "";
    View view = inflater.inflate(R.layout.fragment_dancer_details, container, false);

    if (bundle != null) {
        imageBitmap = bundle.getParcelable("IMAGE");
        dancerName = bundle.getString("NAME_TEXT");
    }

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        view.findViewById(R.id.dancerImageDetails).setTransitionName(getString(R.string.dancer_icon_transition));
        view.findViewById(R.id.dancerNameDetails).setTransitionName(getString(R.string.dancer_name_transition));
    }

    ((ImageView) view.findViewById(R.id.dancerImageDetails)).setImageBitmap(imageBitmap);
    ((TextView) view.findViewById(R.id.dancerNameDetails)).setText(dancerName);

    return view;
}
</code>```

end fragment XML

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context="com.example.ginold.dance.Fragments.DancerDetailsFragment">

<TextView
    android:id="@+id/dancerNameDetails"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_marginStart="113dp"
    android:text="chuhj"
    android:textColor="@color/colorAccent"
    android:textSize="50dp"
    android:transitionName="@string/dancer_name_transition" />

<ImageView
    android:id="@+id/dancerImageDetails"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_marginStart="12dp"
    android:layout_marginTop="103dp"
    android:transitionName="@string/dancer_icon_transition" />
</code>```

dancer item transition XML

```<code><?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeTransform/>
    <changeBounds/>
</transitionSet>
</code>```

答:
You have already added transitionName into End Fragment xml so no need set again remove the code it will work. It should be like this: </p>

```<code>        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
          Bundle bundle = getArguments();
          Bitmap imageBitmap = null;
          String dancerName = "";
          View view = inflater.inflate(R.layout.fragment_dancer_details, container, false);

          if (bundle != null) {
              imageBitmap = bundle.getParcelable("IMAGE");
              dancerName = bundle.getString("NAME_TEXT");
          }

          ((ImageView) view.findViewById(R.id.dancerImageDetails)).setImageBitmap(imageBitmap);
          ((TextView) view.findViewById(R.id.dancerNameDetails)).setText(dancerName);

          return view;
      }
</code>```

Body:
The desired shared elements don't animate, they just appear/fade in instead of moving from one view to the other. What can possibly be wrong? I've read multiple tutorials and none of them has worked. It surely is a small thing though...
I'm testing on a AVD 6.0.

Thanks for your help!

The app starts through MainActivity loading the starting fragment

public void openFindDancerFragment() {
    FindDancerFragment findDancerFragment = new FindDancerFragment();
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.main_fragment_container, findDancerFragment)
            .addToBackStack(null)
            .commit();
}

Which brings you to the Starting fragment

Start fragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_find_dancer, container, false);
    DancerItemAdapter adapter = new DancerItemAdapter(getContext(), dancers);
    ListView dancersView = (ListView)v.findViewById(R.id.dancersListView);

    dancersView.setAdapter(adapter);
    dancersView.setOnItemClickListener(this);
    return v;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ImageView imageView = (ImageView) view.findViewById(R.id.dancerIcon);
    TextView textView = (TextView) view.findViewById(R.id.dancerName);
    String imageTransitionName = getString(R.string.dancer_icon_transition);
    String textTransitionName = getString(R.string.dancer_name_transition);
    DancerDetailsFragment detailsFragment = new DancerDetailsFragment();

    Bundle bundle = new Bundle();
    bundle.putString("NAME_TEXT", textView.getText().toString());
    bundle.putParcelable("IMAGE", ((BitmapDrawable) imageView.getDrawable()).getBitmap());
    detailsFragment.setArguments(bundle);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setSharedElementReturnTransition(TransitionInflater.from(
                getActivity()).inflateTransition(android.R.transition.fade));
        setExitTransition(TransitionInflater.from(
                getActivity()).inflateTransition(android.R.transition.fade));

        detailsFragment.setSharedElementEnterTransition(TransitionInflater.from(
                getActivity()).inflateTransition(R.transition.dancer_item_transition));
        detailsFragment.setEnterTransition(TransitionInflater.from(
                getActivity()).inflateTransition(R.transition.dancer_item_transition));
    }

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .addToBackStack(null)
            .addSharedElement(imageView, imageTransitionName)
            .addSharedElement(textView, textTransitionName)
            .replace(R.id.find_dancer_fragment, detailsFragment)
            .commit();
}

Start fragment XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/find_dancer_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
tools:context="com.example.ginold.dance.Fragments.FindDancerFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">
    <ListView
        android:id="@+id/dancersListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Clicking on an list item brings you to the end fragment:

End fragment

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(R.transition.dancer_item_transition));
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle bundle = getArguments();
    Bitmap imageBitmap = null;
    String dancerName = "";
    View view = inflater.inflate(R.layout.fragment_dancer_details, container, false);

    if (bundle != null) {
        imageBitmap = bundle.getParcelable("IMAGE");
        dancerName = bundle.getString("NAME_TEXT");
    }

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        view.findViewById(R.id.dancerImageDetails).setTransitionName(getString(R.string.dancer_icon_transition));
        view.findViewById(R.id.dancerNameDetails).setTransitionName(getString(R.string.dancer_name_transition));
    }

    ((ImageView) view.findViewById(R.id.dancerImageDetails)).setImageBitmap(imageBitmap);
    ((TextView) view.findViewById(R.id.dancerNameDetails)).setText(dancerName);

    return view;
}

end fragment XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context="com.example.ginold.dance.Fragments.DancerDetailsFragment">

<TextView
    android:id="@+id/dancerNameDetails"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_marginStart="113dp"
    android:text="chuhj"
    android:textColor="@color/colorAccent"
    android:textSize="50dp"
    android:transitionName="@string/dancer_name_transition" />

<ImageView
    android:id="@+id/dancerImageDetails"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_marginStart="12dp"
    android:layout_marginTop="103dp"
    android:transitionName="@string/dancer_icon_transition" />

dancer item transition XML

<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeTransform/>
    <changeBounds/>
</transitionSet>

Body:
You have already added transitionName into End Fragment xml so no need set again remove the code it will work. It should be like this:

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
          Bundle bundle = getArguments();
          Bitmap imageBitmap = null;
          String dancerName = "";
          View view = inflater.inflate(R.layout.fragment_dancer_details, container, false);

          if (bundle != null) {
              imageBitmap = bundle.getParcelable("IMAGE");
              dancerName = bundle.getString("NAME_TEXT");
          }

          ((ImageView) view.findViewById(R.id.dancerImageDetails)).setImageBitmap(imageBitmap);
          ((TextView) view.findViewById(R.id.dancerNameDetails)).setText(dancerName);

          return view;
      }


来源: stackexchange

问:
How to restrict multiple user logins at same time using JavaScript / jQuery
I have developed an ASP.NET MVC Application using JavaScript, jQuery.

I have implemented to be restrict multiple user logins at same time using onbeforeunload/beforeunloadevent.

It works fine, but sometimes not working in onbeforeunload/beforeunloadevent.

```<code>var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
    if (!validNavigation)
    {
        $.ajax({
            url: '@Url.Action("ClearSession", "Account")',
            type: 'Post',
            data: "",
            dataType: "json",
            success: function (data)
            {
                console.log("onbeforeunload Success")
            },
            error: function (data) {
                console.log("onbeforeunload Error")
            }
        });
    }

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

答:
There is one also function in AJAX - jQuery is called complete: function(){};
This function checks weather request is running for same user id and password on browser or not,  Like this here

```<code>complete: function() {
        $(this).data('requestRunning', false);
    }
</code>```

Whole AJAX-jQuery implementation here see and implement accordingly, I hope it will work fine for you

Code Here

```<code>$('#do-login').click(function(e) {
    var me = $(this);
    e.preventDefault();

    if ( me.data('requestRunning') ) {
        return;
    }

    me.data('requestRunning', true);

    $.ajax({
        type: "POST",
        url: "/php/auth/login.php",
        data: $("#login-form").serialize(),
        success: function(msg) {
            //stuffs
        },
        complete: function() {
            me.data('requestRunning', false);
        }
    });
});
</code>```

See this me.data('requestRunning', false); if it will get any request running for same user id and password it returns false and cancel login.

For more help see here link Duplicate, Ajax prevent multiple request on click

This is not perfect solution but you can implement like this

ContentLicense: CC BY-SA 3.0

Body:
I have developed an ASP.NET MVC Application using JavaScript, jQuery.

I have implemented to be restrict multiple user logins at same time using onbeforeunload/beforeunloadevent.

It works fine, but sometimes not working in onbeforeunload/beforeunloadevent.

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
    if (!validNavigation)
    {
        $.ajax({
            url: '@Url.Action("ClearSession", "Account")',
            type: 'Post',
            data: "",
            dataType: "json",
            success: function (data)
            {
                console.log("onbeforeunload Success")
            },
            error: function (data) {
                console.log("onbeforeunload Error")
            }
        });
    }

    return null;
});

Body:
There is one also function in AJAX - jQuery is called complete: function(){};
This function checks weather request is running for same user id and password on browser or not,  Like this here

complete: function() {
        $(this).data('requestRunning', false);
    }

Whole AJAX-jQuery implementation here see and implement accordingly, I hope it will work fine for you

Code Here

$('#do-login').click(function(e) {
    var me = $(this);
    e.preventDefault();

    if ( me.data('requestRunning') ) {
        return;
    }

    me.data('requestRunning', true);

    $.ajax({
        type: "POST",
        url: "/php/auth/login.php",
        data: $("#login-form").serialize(),
        success: function(msg) {
            //stuffs
        },
        complete: function() {
            me.data('requestRunning', false);
        }
    });
});

See this me.data('requestRunning', false); if it will get any request running for same user id and password it returns false and cancel login.

For more help see here link Duplicate, Ajax prevent multiple request on click

This is not perfect solution but you can implement like this


问:
Android: TextView: Remove spacing and padding on top and bottom
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

```<code>android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"
</code>```

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?

答: This annoyed me too, and the answer I found was that there is actually additional space in the font itself, not the TextView. It is rather irritating, coming from a document publishing background, the limited amount of control you have with Android over typographic elements. I'd recommend using a custom typeface (such as Bitstream Vera Sans, which is licensed for redistribution) that may not have this issue. I'm not sure specifically whether or not it does, though.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?

ContentLicense: CC BY-SA 2.5


问:
Error:1722 Getting session names
I am trying to check if anybody is connected to the server in my team with the following command: query session /server:<SERVERNAME>. But Every time I end up getting the following error:

Error:1722 getting session names.

Error[1722]: The RPC sever is unavailable.

I have already tried with qwinsta but i get the same issue in there too.
Is there anyway to get around the issue and get the required?

答:
For me, the one Windows Server 2012 R2 giving this error was fixed by adding the following rule. None of the 97 other had the issue.</p>

```<code>netsh advfirewall firewall add rule name="Open Port 135 RPC" dir=in action=allow protocol=TCP localport=135
netsh advfirewall firewall add rule name="Open Port 135 RPC" dir=in action=allow protocol=UDP localport=135
netsh advfirewall firewall add rule name="Open Port 445 RPC" dir=in action=allow protocol=TCP localport=445
netsh advfirewall firewall add rule name="Open Port 445 RPC" dir=in action=allow protocol=UDP localport=445
</code>```

Title: Error:1722 Getting session names

Body:
For me, the one Windows Server 2012 R2 giving this error was fixed by adding the following rule. None of the 97 other had the issue.

netsh advfirewall firewall add rule name="Open Port 135 RPC" dir=in action=allow protocol=TCP localport=135
netsh advfirewall firewall add rule name="Open Port 135 RPC" dir=in action=allow protocol=UDP localport=135
netsh advfirewall firewall add rule name="Open Port 445 RPC" dir=in action=allow protocol=TCP localport=445
netsh advfirewall firewall add rule name="Open Port 445 RPC" dir=in action=allow protocol=UDP localport=445


问:
CrudRepository custom find by current timestamp
I have table Bound

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "boundId", unique = true, nullable = false)
private long boundId;

@Column
@Basic
private Timestamp startTimeStamp;

@Column
@Basic
private Timestamp endTimeStamp;
</code>```

And i created query :

```<code>public interface BoundsDataRepository extends CrudRepository<Bound, Long> {
   @Query("from Bound b where b.startTimeStamp s <=:currentTimeStamp and b.endTimeStamp e>=:currentTimeStamp")
   List<Bound> findByCurrentTimeStamp(Timestamp currentTimeStamp);
}
</code>```

I's give me an error. How should I name this query and how can I resolve this question?

Thanks for help!

答:
I think you have some problems in your query :

You don't need to use alias in the columns names b.endTimeStamp e

You use parameters :currentTimeStamp but you don't pass any one in the query

Your query should look like :

```<code>@Query("from Bound b where b.startTimeStamp <= :currentTimeStamp and "
        + "b.endTimeStamp >= :currentTimeStamp")
List<Bound> findByCurrentTimeStamp(@Param("currentTimeStamp") Timestamp currentTimeStamp);
</code>```

Body:
I have table Bound

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "boundId", unique = true, nullable = false)
private long boundId;

@Column
@Basic
private Timestamp startTimeStamp;

@Column
@Basic
private Timestamp endTimeStamp;

And i created query :

public interface BoundsDataRepository extends CrudRepository<Bound, Long> {
   @Query("from Bound b where b.startTimeStamp s <=:currentTimeStamp and b.endTimeStamp e>=:currentTimeStamp")
   List<Bound> findByCurrentTimeStamp(Timestamp currentTimeStamp);
}

I's give me an error. How should I name this query and how can I resolve this question?

Thanks for help!

Body:
I think you have some problems in your query :

You don't need to use alias in the columns names b.endTimeStamp e

You use parameters :currentTimeStamp but you don't pass any one in the query

Your query should look like :

@Query("from Bound b where b.startTimeStamp <= :currentTimeStamp and "
        + "b.endTimeStamp >= :currentTimeStamp")
List<Bound> findByCurrentTimeStamp(@Param("currentTimeStamp") Timestamp currentTimeStamp);


问:
Laravel Dompdf- Change photography size
I have a serie of photos taken with a mobile. I am trying to print a complete document in PDF (done by DOMPDF in Laravel), with text and a photo inserted in it. It works perfect, except for the photos, it got printed very very small.

I had same problem with background, but I designed it with the exact A4 size (in print point).

My question is how to modify the photographies in order to get them printed in the PDF at the size I want.

PHP Code:

```<code>$cliente = Cliente::findOrFail($id);
$view = \View::make('cpanel.pdf.curriculum', compact('cliente'))->render();
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($view);
return $pdf->download('cv-'.$cliente->nombre." ".$cliente->apellidos."-".Date('d-m-Y').'.pdf');
</code>```

I tried with css rules, but DOMPDF ignores it for images

```<code><img style="width: 125pt;border: 1px solid red;" src="{{URL::asset('/images/candidatos/'.$cliente->foto)}}" />
</code>```

答: there is a semicolon after style= replace it with double quotes</p>

Title: Laravel Dompdf- Change photography size

Body:
I have a serie of photos taken with a mobile. I am trying to print a complete document in PDF (done by DOMPDF in Laravel), with text and a photo inserted in it. It works perfect, except for the photos, it got printed very very small.

I had same problem with background, but I designed it with the exact A4 size (in print point).

My question is how to modify the photographies in order to get them printed in the PDF at the size I want.

PHP Code:

$cliente = Cliente::findOrFail($id);
$view = \View::make('cpanel.pdf.curriculum', compact('cliente'))->render();
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($view);
return $pdf->download('cv-'.$cliente->nombre." ".$cliente->apellidos."-".Date('d-m-Y').'.pdf');

I tried with css rules, but DOMPDF ignores it for images

foto)}}" />


问:
Writing and Reading an ArrayList<model>
So I am pretty much new at this but I have built a library project that has an ArrayList BookList which in return has elements such as String Title, String Author, and int Quantity. I have an add method and a display method and  I want to create a method that I am able to save and load the BookList when I I give the appropriate input to do so. Moreover I want to do so, so when I load the BookList I can make changes to the elements in the ArrayList and it's not just reading from the file.

```<code>public class Library implements Serializable{...}
</code>```

Inside this class are my methods of saving and loading which are called in the main as well as the constructors for the ArrayList.

Save

```<code>   public void save(){
       try{
           FileOutputStream fileOut = new FileOutputStream("BookList.tmp");
           ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
           objOut.writeObject(BookList);
           objOut.close();
       }catch(Exception ev){}
   }//end of save()
</code>```

Load

```<code>    public void load(){
        try{
            FileInputStream fileInput = new FileInputStream("BookList.tmp");
            ObjectInputStream objInput = new ObjectInputStream(fileInput);
            List<Book> BookList = (List<Book>) objInput.readObject();
            objInput.close();
        }
        catch (Exception ev){}
    }//end of load()
</code>```

Display

```<code>    public void displayBooks(){
        String t;
        String a;
        int q;
        String s;
        Book bo = new Book();
        for(int i = 0; i<BookList.size(); i++){
            bo = BookList.get(i);
            t = bo.gettitle();
            a = bo.getauthor();
            q = bo.getquantity();
            System.out.println(i + "." + t + " " + a + " " + q);
        }//end of loop
    }//end of displayBooks()
</code>```

But so far through the display method I have I am not able to see the BookList so I don't know if the save method works in the first place as well. So I want to know if the problem lies here or somewhere else.

答:
The problem is in your load(), you read the book list from the ObjectInputStream, but you simply assigned to a local variable.  I believe (though poorly named) your BookList is an instance variable.

So your load() should look like

```<code>public void load(){
    try{
        ObjectInputStream objInput = new ObjectInputStream(FileInputStream("BookList.tmp"));
        this.books = (List<Book>) objInput.readObject();
        objInput.close();
    }
    catch (Exception ignored){
        // please add some handling please!
    }
}
</code>```

Title: Writing and Reading an ArrayList<model>

Body:
So I am pretty much new at this but I have built a library project that has an ArrayList BookList which in return has elements such as String Title, String Author, and int Quantity. I have an add method and a display method and  I want to create a method that I am able to save and load the BookList when I I give the appropriate input to do so. Moreover I want to do so, so when I load the BookList I can make changes to the elements in the ArrayList and it's not just reading from the file.

public class Library implements Serializable{...}

Inside this class are my methods of saving and loading which are called in the main as well as the constructors for the ArrayList.

Save

   public void save(){
       try{
           FileOutputStream fileOut = new FileOutputStream("BookList.tmp");
           ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
           objOut.writeObject(BookList);
           objOut.close();
       }catch(Exception ev){}
   }//end of save()

Load

    public void load(){
        try{
            FileInputStream fileInput = new FileInputStream("BookList.tmp");
            ObjectInputStream objInput = new ObjectInputStream(fileInput);
            List<Book> BookList = (List<Book>) objInput.readObject();
            objInput.close();
        }
        catch (Exception ev){}
    }//end of load()

Display

    public void displayBooks(){
        String t;
        String a;
        int q;
        String s;
        Book bo = new Book();
        for(int i = 0; i<BookList.size(); i++){
            bo = BookList.get(i);
            t = bo.gettitle();
            a = bo.getauthor();
            q = bo.getquantity();
            System.out.println(i + "." + t + " " + a + " " + q);
        }//end of loop
    }//end of displayBooks()

But so far through the display method I have I am not able to see the BookList so I don't know if the save method works in the first place as well. So I want to know if the problem lies here or somewhere else.

Body:
The problem is in your load(), you read the book list from the ObjectInputStream, but you simply assigned to a local variable.  I believe (though poorly named) your BookList is an instance variable.

So your load() should look like

public void load(){
    try{
        ObjectInputStream objInput = new ObjectInputStream(FileInputStream("BookList.tmp"));
        this.books = (List<Book>) objInput.readObject();
        objInput.close();
    }
    catch (Exception ignored){
        // please add some handling please!
    }
}


问:
SqlBulkCopy takes long time to insert datatable records into SQL Server table
We are trying to insert 20000 or more records using SqlBulkCopy.WriteToServer method, but it is taking 140 sec to insert into the table.

Is there any way we can improve the time using SqlBulkCopy as this is widely used for bulk insertion?

Calling code:

```<code>using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dConn))
{
    bulkCopy.ColumnMappings.Add("SamplingFileId", "SamplingFileId");
    /*... 74 more columns ...*/
    bulkCopy.BulkCopyTimeout = 500; //Assign Destination Table Name
    bulkCopy.DestinationTableName = "cvr_ReviewSamplingLoans";
    bulkCopy.BatchSize = 5000;
    bulkCopy.WriteToServer(dtLoansToUpload);
}
</code>```

Sql Table Definition:

```<code>CREATE TABLE [dbo].[ReviewSamplingLoans](
[Id] [int] IDENTITY(1000,1) NOT NULL,
[SamplingFileId] [int] NOT NULL,
[ReviewId] [int] NOT NULL,
[LoanType] [nvarchar](10) NOT NULL,
[LoanNumber] [nvarchar](50) NOT NULL,
[BorrowerName] [nvarchar](150) NOT NULL,
[OriginalUPB] [money] NOT NULL,
[CurrentUPB] [money] NOT NULL,
[OriginalMonthlyPayment] [money] NULL,
[CurrentMonthlyP&I] [money] NULL,
[PaymentFrequency] [nvarchar](2) NULL,
[OriginalNoteRate] [float] NULL,
[CurrentInterestRate] [float] NULL,
[OriginationDate] [date] NULL,
[MaturityDate] [date] NULL,
[FirstPaymentDate] [date] NULL,
[InterestPaidThruDate] [date] NULL,
[NextPaymentDate] [date] NULL,
[DelinquencyStatus] [nvarchar](10) NULL,
[LatePaymentCount] [int] NULL,
[StatedTerm] [int] NULL,
[OriginalAmortizationTerm] [int] NULL,
[NoteType] [nvarchar](10) NULL,
[RateType] [nvarchar](10) NULL,
[LoanProductType] [nvarchar](10) NULL,
[BalloonDueDate] [date] NULL,
[BalloonPaymentAmount] [money] NULL,
[PropertyCity] [nvarchar](50) NULL,
[PropertyState] [nchar](2) NULL,
[PropertyZipcode] [nvarchar](10) NULL,
[PropertyType] [nvarchar](10) NULL,
[PropertyTypeDescription] [nvarchar](50) NULL,
[LienPosition] [tinyint] NULL,
[OriginalLTV] [float] NULL,
[CurrentLTV] [float] NULL,
[SeniorLienBalance] [money] NULL,
[OriginalCommitmentAmount] [money] NULL,
[CurrentCommitmentAmount] [money] NULL,
[OriginalCombinedLTV] [float] NULL,
[CurrentCombinedLTV] [float] NULL,
[OriginalPropertyValue] [money] NULL,
[CurrentPropertyValue] [money] NULL,
[AppraisalDate] [date] NULL,
[AppraisalType] [nvarchar](10) NULL,
[PMI] [nchar](1) NULL,
[LoanPurpose] [nchar](1) NULL,
[OccupancyType] [nchar](1) NULL,
[DocumentationType] [nvarchar](10) NULL,
[OriginalFICO] [smallint] NULL,
[CurrentFICO] [smallint] NULL,
[LastFICOUpdatedDate] [date] NULL,
[DebtToIncomeRatio] [float] NULL,
[InterestOnlyPeriod] [smallint] NULL,
[Modication] [nchar](1) NULL,
[Foreclosure] [nchar](1) NULL,
[ArmProductType] [nvarchar](10) NULL,
[ArmMargin] [float] NULL,
[ArmIndexType] [nvarchar](10) NULL,
[FirstRateAdjustmentDate] [date] NULL,
[NextRateAdjustmentDate] [date] NULL,
[LifeFloor] [float] NULL,
[LifeCeiling] [float] NULL,
[InitialRateCap] [float] NULL,
[PeriodicRateCap] [float] NULL,
[InternalRiskRating] [nvarchar](10) NULL,
[CurrentDebtServiceRatio] [float] NULL,
[CurrentNetOperIncome] [float] NULL,
[OriginalDebtServiceRatio] [float] NULL,
[OriginalNetOperIncome] [float] NULL,
[CurrentOccupancy] [float] NULL,
[PropertyTotalSquareFootage] [int] NULL,
[UnitCount] [smallint] NULL,
[PrepaymentPenalty] [nchar](1) NULL,
[PrepaymentPenaltyType] [int] NULL,
[PrepaymentPenaltyTerm] [smallint] NULL,
CONSTRAINT [PK_ReviewSamplingLoans] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[ReviewSamplingLoans]  WITH NOCHECK ADD  CONSTRAINT [FK_ReviewSamplingLoans_ReviewCollateralTypes] FOREIGN KEY([LoanType])
REFERENCES [dbo].[ReviewSamplingLoans] ([Code])
GO

ALTER TABLE [dbo].[ReviewSamplingLoans] CHECK CONSTRAINT [FK_ReviewSamplingLoans_ReviewCollateralTypes]
GO

ALTER TABLE [dbo].[ReviewSamplingLoans]  WITH NOCHECK ADD  CONSTRAINT [FK_ReviewSamplingLoans_ReviewSamplingFiles] FOREIGN KEY([ReviewId])
REFERENCES [dbo].[Reviews] ([Id])
GO

ALTER TABLE [dbo].[ReviewSamplingLoans] CHECK CONSTRAINT [FK_ReviewSamplingLoans_ReviewSamplingFiles]
GO
</code>```

Regarding Size, excel file contains 20000 rows which are added to datatable upon validation and using sqlbulkcopy inserting into table.

答:
SqlBulkCopy can be performed faster when you enable the Tablelock on the options.

Have a look here SqlBulkCopyOptions Enumeration

But keep in mind that once the operation has started, no one will be able to use the table until it is finished. Microsoft says that this tenchnique improves the speed when inserting large amounts of data.

Body:
We are trying to insert 20000 or more records using SqlBulkCopy.WriteToServer method, but it is taking 140 sec to insert into the table.

Is there any way we can improve the time using SqlBulkCopy as this is widely used for bulk insertion?

Calling code:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dConn))
{
    bulkCopy.ColumnMappings.Add("SamplingFileId", "SamplingFileId");
    /*... 74 more columns ...*/
    bulkCopy.BulkCopyTimeout = 500; //Assign Destination Table Name
    bulkCopy.DestinationTableName = "cvr_ReviewSamplingLoans";
    bulkCopy.BatchSize = 5000;
    bulkCopy.WriteToServer(dtLoansToUpload);
}

Sql Table Definition:

CREATE TABLE [dbo].[ReviewSamplingLoans](
[Id] [int] IDENTITY(1000,1) NOT NULL,
[SamplingFileId] [int] NOT NULL,
[ReviewId] [int] NOT NULL,
[LoanType] [nvarchar](10) NOT NULL,
[LoanNumber] [nvarchar](50) NOT NULL,
[BorrowerName] [nvarchar](150) NOT NULL,
[OriginalUPB] [money] NOT NULL,
[CurrentUPB] [money] NOT NULL,
[OriginalMonthlyPayment] [money] NULL,
[CurrentMonthlyP&I] [money] NULL,
[PaymentFrequency] [nvarchar](2) NULL,
[OriginalNoteRate] [float] NULL,
[CurrentInterestRate] [float] NULL,
[OriginationDate] [date] NULL,
[MaturityDate] [date] NULL,
[FirstPaymentDate] [date] NULL,
[InterestPaidThruDate] [date] NULL,
[NextPaymentDate] [date] NULL,
[DelinquencyStatus] [nvarchar](10) NULL,
[LatePaymentCount] [int] NULL,
[StatedTerm] [int] NULL,
[OriginalAmortizationTerm] [int] NULL,
[NoteType] [nvarchar](10) NULL,
[RateType] [nvarchar](10) NULL,
[LoanProductType] [nvarchar](10) NULL,
[BalloonDueDate] [date] NULL,
[BalloonPaymentAmount] [money] NULL,
[PropertyCity] [nvarchar](50) NULL,
[PropertyState] [nchar](2) NULL,
[PropertyZipcode] [nvarchar](10) NULL,
[PropertyType] [nvarchar](10) NULL,
[PropertyTypeDescription] [nvarchar](50) NULL,
[LienPosition] [tinyint] NULL,
[OriginalLTV] [float] NULL,
[CurrentLTV] [float] NULL,
[SeniorLienBalance] [money] NULL,
[OriginalCommitmentAmount] [money] NULL,
[CurrentCommitmentAmount] [money] NULL,
[OriginalCombinedLTV] [float] NULL,
[CurrentCombinedLTV] [float] NULL,
[OriginalPropertyValue] [money] NULL,
[CurrentPropertyValue] [money] NULL,
[AppraisalDate] [date] NULL,
[AppraisalType] [nvarchar](10) NULL,
[PMI] [nchar](1) NULL,
[LoanPurpose] [nchar](1) NULL,
[OccupancyType] [nchar](1) NULL,
[DocumentationType] [nvarchar](10) NULL,
[OriginalFICO] [smallint] NULL,
[CurrentFICO] [smallint] NULL,
[LastFICOUpdatedDate] [date] NULL,
[DebtToIncomeRatio] [float] NULL,
[InterestOnlyPeriod] [smallint] NULL,
[Modication] [nchar](1) NULL,
[Foreclosure] [nchar](1) NULL,
[ArmProductType] [nvarchar](10) NULL,
[ArmMargin] [float] NULL,
[ArmIndexType] [nvarchar](10) NULL,
[FirstRateAdjustmentDate] [date] NULL,
[NextRateAdjustmentDate] [date] NULL,
[LifeFloor] [float] NULL,
[LifeCeiling] [float] NULL,
[InitialRateCap] [float] NULL,
[PeriodicRateCap] [float] NULL,
[InternalRiskRating] [nvarchar](10) NULL,
[CurrentDebtServiceRatio] [float] NULL,
[CurrentNetOperIncome] [float] NULL,
[OriginalDebtServiceRatio] [float] NULL,
[OriginalNetOperIncome] [float] NULL,
[CurrentOccupancy] [float] NULL,
[PropertyTotalSquareFootage] [int] NULL,
[UnitCount] [smallint] NULL,
[PrepaymentPenalty] [nchar](1) NULL,
[PrepaymentPenaltyType] [int] NULL,
[PrepaymentPenaltyTerm] [smallint] NULL,
CONSTRAINT [PK_ReviewSamplingLoans] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[ReviewSamplingLoans]  WITH NOCHECK ADD  CONSTRAINT [FK_ReviewSamplingLoans_ReviewCollateralTypes] FOREIGN KEY([LoanType])
REFERENCES [dbo].[ReviewSamplingLoans] ([Code])
GO

ALTER TABLE [dbo].[ReviewSamplingLoans] CHECK CONSTRAINT [FK_ReviewSamplingLoans_ReviewCollateralTypes]
GO

ALTER TABLE [dbo].[ReviewSamplingLoans]  WITH NOCHECK ADD  CONSTRAINT [FK_ReviewSamplingLoans_ReviewSamplingFiles] FOREIGN KEY([ReviewId])
REFERENCES [dbo].[Reviews] ([Id])
GO

ALTER TABLE [dbo].[ReviewSamplingLoans] CHECK CONSTRAINT [FK_ReviewSamplingLoans_ReviewSamplingFiles]
GO

Regarding Size, excel file contains 20000 rows which are added to datatable upon validation and using sqlbulkcopy inserting into table.


问:
Show div using button and hide it if click outside the div
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
  <button id="close-add">Close Div</button>
  <p> Show Me </p>
</div></code>```

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

答:
There is already a solution provided at W3Schools.

Check Here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

Snippet

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}</code>```

Modal Example

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

```

Body:
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});

<button id="new-shipping'">Open Div</button>

  <button id="close-add">Close Div</button>

 Show Me

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

Body:
There is already a solution provided at W3Schools.

Check Here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

Snippet

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>


问:
I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python
I have a below CSV file with the header(A,B,C,D):

```<code>A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6
</code>```

I want output after removing top 5 lines but not header:

```<code>A,B,C,D
1,1,7,3
2,9,5,6
</code>```

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

答:
I'd advise against even parsing the file or reading it whole in memory just to slice it. If you just want to do away with some lines in the middle all you need is to read the input file line by line and decide which lines to write to the output file and which ones to skip:

```<code>skip_lines = range(1, 6)  # the range is zero-indexed

with open("input.csv") as f_in, open("output.csv", "w") as f_out:
    current_line = 0  # keep a line counter
    for line in f_in:  # read the input file line by line
        if current_line not in skip_lines:
            f_out.write(line)  # not in our skip range, write the line
        current_line += 1  # increase the line counter
</code>```

Body:
I have a below CSV file with the header(A,B,C,D):

A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6

I want output after removing top 5 lines but not header:

A,B,C,D
1,1,7,3
2,9,5,6

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

Body:
I'd advise against even parsing the file or reading it whole in memory just to slice it. If you just want to do away with some lines in the middle all you need is to read the input file line by line and decide which lines to write to the output file and which ones to skip:

skip_lines = range(1, 6)  # the range is zero-indexed

with open("input.csv") as f_in, open("output.csv", "w") as f_out:
    current_line = 0  # keep a line counter
    for line in f_in:  # read the input file line by line
        if current_line not in skip_lines:
            f_out.write(line)  # not in our skip range, write the line
        current_line += 1  # increase the line counter


问:
Visual studio 2017 cross platform library linking

I am trying to compile some code using visual studios cross platform feature, but I am having some issues, I copied over the include files like they say you should and intellisense works fine. during compiling at the linking stage I get the can not find lib...

```<code>Linking objects
1>  Invoking ld
1>  g++ -o "/home/pi/projects/PiLedTestSetup/bin/ARM/Debug/PiLedTestSetup.out" -Wl,--no-undefined -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/camera.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/cameracontrol.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/main.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/Serial.o -lwiringPi -llibmmal_core -llibmmal_util -llibmmal_vc_client -llibvcos -llibbcm_host -llibbrcmGLESv2 -llibbrcmEGL.so
1>  /usr/bin/ld: cannot find -llibmmal_core
1>  /usr/bin//usr/bin/ld: cannot find -llibmmal_core
1>  /usr/bin/ld: cannot find -llibmmal_util
1>  /usr/bin/ld: cannot find -llibmmal_vc_client
1>  /usr/bin/ld: cannot find -llibvcos
1>  /usr/bin/ld: cannot find -llibbcm_host
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  collect2: error: ld returned 1 exit status
</code>```

using the make file I originally used(compiling with make on the pi works fine!) it links to the lib folder like this link_directories(/opt/vc/lib) so in vs I added that just like the include Directories in VC++ Directories->Library directory

so I was wondering am I missing something? How do you all add you libraries.

Edit:
so I found out how to add the lib folder, go to properties-general-additional library directory

so now it gives the -L (-L/opt/vc/lib) parameter in the build string or what you call it but its still not finding it. I even tried with file extension but that does not help ether

```<code>1>Target Link:
1>  Linking objects
1>  Invoking ld
1>  g++ -o "/home/pi/projects/PiLedTestSetup/bin/ARM/Debug/PiLedTestSetup.out" -Wl,--stats -Wl,--no-undefined -Wl,-L/opt/vc/lib -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/camera.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/cameracontrol.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/main.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/Serial.o -lwiringPi -llibmmal_core.so -llibmmal_util.so -llibmmal_vc_client.so -llibvcos.so -llibbcm_host.so -llibbrcmGLESv2.so -llibbrcmEGL.so
1>  /usr/bin/ld: cannot find -llibmmal_core.so
1>  /usr/bin/ld: /usr/bin/ld: cannot find -llibmmal_core.so
1>  /usr/bin/ld: cannot find -llibmmal_util.so
1>  /usr/bin/ld: cannot find -llibmmal_vc_client.so
1>  /usr/bin/ld: cannot find -llibvcos.so
1>  /usr/bincannot find -llibmmal_util.so
1>  /usr/bin/ld: cannot find -llibmmal_vc_client.so
1>  /usr/bin/ld: cannot find -llibvcos.so
1>  /usr/bin/ld: cannot find -llibbcm_host.so
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2.so
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  /ld: cannot find -llibbcm_host.so
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2.so
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  collect2: error: ld returned 1 exit status
</code>```

The make file on the pi has this and it compile and links no problem. am I missing something ?

```<code>cmake_minimum_required(VERSION 2.8)
project( picamdemo )
SET(COMPILE_DEFINITIONS -Werror)
include_directories(/opt/vc/include)
link_directories(/opt/vc/lib)
add_executable(picamdemo picam.cpp camera.cpp cameracontrol.cpp graphics.cpp)

target_link_libraries(picamdemo libmmal_core.so libmmal_util.so libmmal_vc_client.so libvcos.so libbcm_host.so libbrcmGLESv2.so libbrcmEGL.so)
</code>```

答:
ok so I asked this question also on the Microsoft forums and got an answer.

"Using '-l' switch, would omit file-extension and prefix 'lib':
E.g. if name of library is 'libmmal_core.so', then

```<code> -lmmal_core
</code>```

https://social.msdn.microsoft.com/Forums/vstudio/en-US/a43c9f43-eb8c-4af1-9615-49fd58e2de92/visual-studio-2017-cross-platform-library-linking?forum=vcgeneral

Body:
I am trying to compile some code using visual studios cross platform feature, but I am having some issues, I copied over the include files like they say you should and intellisense works fine. during compiling at the linking stage I get the can not find lib...

Linking objects
1>  Invoking ld
1>  g++ -o "/home/pi/projects/PiLedTestSetup/bin/ARM/Debug/PiLedTestSetup.out" -Wl,--no-undefined -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/camera.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/cameracontrol.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/main.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/Serial.o -lwiringPi -llibmmal_core -llibmmal_util -llibmmal_vc_client -llibvcos -llibbcm_host -llibbrcmGLESv2 -llibbrcmEGL.so
1>  /usr/bin/ld: cannot find -llibmmal_core
1>  /usr/bin//usr/bin/ld: cannot find -llibmmal_core
1>  /usr/bin/ld: cannot find -llibmmal_util
1>  /usr/bin/ld: cannot find -llibmmal_vc_client
1>  /usr/bin/ld: cannot find -llibvcos
1>  /usr/bin/ld: cannot find -llibbcm_host
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  collect2: error: ld returned 1 exit status

using the make file I originally used(compiling with make on the pi works fine!) it links to the lib folder like this link_directories(/opt/vc/lib) so in vs I added that just like the include Directories in VC++ Directories->Library directory

so I was wondering am I missing something? How do you all add you libraries.

Edit:
so I found out how to add the lib folder, go to properties-general-additional library directory

so now it gives the -L (-L/opt/vc/lib) parameter in the build string or what you call it but its still not finding it. I even tried with file extension but that does not help ether

1>Target Link:
1>  Linking objects
1>  Invoking ld
1>  g++ -o "/home/pi/projects/PiLedTestSetup/bin/ARM/Debug/PiLedTestSetup.out" -Wl,--stats -Wl,--no-undefined -Wl,-L/opt/vc/lib -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/camera.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/cameracontrol.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/main.o /home/pi/projects/PiLedTestSetup/obj/ARM/Debug/Serial.o -lwiringPi -llibmmal_core.so -llibmmal_util.so -llibmmal_vc_client.so -llibvcos.so -llibbcm_host.so -llibbrcmGLESv2.so -llibbrcmEGL.so
1>  /usr/bin/ld: cannot find -llibmmal_core.so
1>  /usr/bin/ld: /usr/bin/ld: cannot find -llibmmal_core.so
1>  /usr/bin/ld: cannot find -llibmmal_util.so
1>  /usr/bin/ld: cannot find -llibmmal_vc_client.so
1>  /usr/bin/ld: cannot find -llibvcos.so
1>  /usr/bincannot find -llibmmal_util.so
1>  /usr/bin/ld: cannot find -llibmmal_vc_client.so
1>  /usr/bin/ld: cannot find -llibvcos.so
1>  /usr/bin/ld: cannot find -llibbcm_host.so
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2.so
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  /ld: cannot find -llibbcm_host.so
1>  /usr/bin/ld: cannot find -llibbrcmGLESv2.so
1>  /usr/bin/ld: cannot find -llibbrcmEGL.so
1>  collect2: error: ld returned 1 exit status

The make file on the pi has this and it compile and links no problem. am I missing something ?

cmake_minimum_required(VERSION 2.8)
project( picamdemo )
SET(COMPILE_DEFINITIONS -Werror)
include_directories(/opt/vc/include)
link_directories(/opt/vc/lib)
add_executable(picamdemo picam.cpp camera.cpp cameracontrol.cpp graphics.cpp)

target_link_libraries(picamdemo libmmal_core.so libmmal_util.so libmmal_vc_client.so libvcos.so libbcm_host.so libbrcmGLESv2.so libbrcmEGL.so)

Body:
ok so I asked this question also on the Microsoft forums and got an answer.

"Using '-l' switch, would omit file-extension and prefix 'lib':
E.g. if name of library is 'libmmal_core.so', then

 -lmmal_core

https://social.msdn.microsoft.com/Forums/vstudio/en-US/a43c9f43-eb8c-4af1-9615-49fd58e2de92/visual-studio-2017-cross-platform-library-linking?forum=vcgeneral


问:
How do you add a macron to a character in an NSString? via Unicode?
Objective-C iOS Programming:

I need to display a number like 8.33333 just as 8.3, with the three having a macron (repeating number symbol, a bar line) above it.  I have done some searching and have not found a solution to this.  I have found the encoding for C/C++/Java source code being "\u0304" and for Unicode being "U+0304".  Is there a way that I can create an NSString from a Unicode character? And how would a create a Unicode character with a macron?

Thanks.

答:
For combining characters such as U+0304, the string should contain the original letter followed by the combining character. For instance,

```<code>NSString *str = @"ca\u0304t";
</code>```

is a representation of cāt.

Body:
For combining characters such as U+0304, the string should contain the original letter followed by the combining character. For instance,

NSString *str = @"ca\u0304t";

is a representation of cāt.


问:
C#: How to set default value if input is empty
If I have a method like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if user input a empty string "", I can write the default value to user, so I can do not only this:

```<code>AddSomething("5");
</code>```

Also both of these:

```<code>AddSomething("5","");
AddSomething("","5");
</code>```

Anyone knows how to do that? THX!

答:
you already answered your question. you can cover null cases also.

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    if(string.IsNullOrEmpty(ice)) ice = "10";
    if(string.IsNullOrEmpty(sweet)) sweet = "20";
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

you can use constants if you don't want to write duplicate literals.

```<code>// these are constant and can be used as default value for parameters.
const string DefaultSweet = "20";
const string DefaultIce = "10";

public void AddSomething(string ice = DefaultSweet, string sweet = DefaultIce)
{
    if(string.IsNullOrEmpty(ice)) ice = DefaultIce;
    if(string.IsNullOrEmpty(sweet)) sweet = DefaultSweet;
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

side note: string.IsNullOrEmpty(ice) is equivalent to ice == "" || ice == null

Body:
If I have a method like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}

so if user input a empty string "", I can write the default value to user, so I can do not only this:

AddSomething("5");

Also both of these:

AddSomething("5","");
AddSomething("","5");

Anyone knows how to do that? THX!

Body:
you already answered your question. you can cover null cases also.

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(string.IsNullOrEmpty(ice)) ice = "10";
    if(string.IsNullOrEmpty(sweet)) sweet = "20";
    Console.Write(ice);
    Console.Write(sweet);
}

you can use constants if you don't want to write duplicate literals.

// these are constant and can be used as default value for parameters.
const string DefaultSweet = "20";
const string DefaultIce = "10";

public void AddSomething(string ice = DefaultSweet, string sweet = DefaultIce)
{
    if(string.IsNullOrEmpty(ice)) ice = DefaultIce;
    if(string.IsNullOrEmpty(sweet)) sweet = DefaultSweet;
    Console.Write(ice);
    Console.Write(sweet);
}

side note: string.IsNullOrEmpty(ice) is equivalent to ice == "" || ice == null


问:
recording audio in android app by holding a button on it
Purpose- I'm actually making doorbell kind of app, where on tapping a button ,app rings(plays a small audio) & on holding it app records audio till user holds it.
my objective- start recording when user holds button & stops when user releases button.

```<code>public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private Button ring,record;
private String outputfile = null;
private MediaRecorder rec = null;
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case REQUEST_RECORD_AUDIO_PERMISSION:
            permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            break;
    }
    if (!permissionToRecordAccepted ) finish();

}

private void startrec()
{
    Log.e(LOG_TAG, "startRecording:Calling ");
    rec = new MediaRecorder();
    rec.setAudioSource(MediaRecorder.AudioSource.MIC);
    rec.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    rec.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    outputfile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.amr";
    rec.setOutputFile(outputfile);
    try {
        rec.prepare();
        rec.start();
    } catch (IOException ioe2) {
    }
    Toast.makeText(MainActivity.this, "RECORDING STARTED", Toast.LENGTH_SHORT).show();

}
private void stoprec(){
    rec.stop();rec.release();
    Toast.makeText(MainActivity.this, "RECORDING STOPPED", Toast.LENGTH_SHORT).show();
    Log.e(LOG_TAG, "stopRecording:Calling ");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ring = findViewById(R.id.ringbutton);
    record =findViewById(R.id.recordbutton);

    ring.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v1) {
            try {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                r.play();
            } catch (IllegalStateException ise) {}
        }
    });

    record.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v2, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) startrec();
         else if (event.getAction() == MotionEvent.ACTION_UP) stoprec();
            return true;}
    });
}
</code>```

}

Problem- app crashes on touching record button

if u know a better way to do this pls tell.

答:
Instead of OnClick You should use OnTouch Listener event and start recording on ACTION_DOWN and stop on ACTION_UP do add permissions as well for audio recording.!

```<code> <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    private MediaRecorder mRecorder = null;

    private String mFileName = null;

      mRecordButton.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {

                    //if Button is Pressed.! or user Id Holding Button
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        startRecording();

                        Toast.makeText(context, "Hold To Record.!", Toast.LENGTH_SHORT).show();

                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                        //Do Nothing
                        stopRecording();

                        Toast.makeText(context, "Recorded.!", Toast.LENGTH_SHORT).show();
                    }

                    return false;
                }
            });

    private void startRecording() {

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        // Record to the external cache directory for visibility
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();

        //getExternalCacheDir().getAbsolutePath();

        String id = new String(UUID.randomUUID().toString());

        mFileName += "/recordedAudio/" + id + ".mp3";
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();

        Log.e(LOG_TAG, "Recording:Calling ");

    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;

        Log.e(LOG_TAG, "stopRecording:Calling ");

    }
</code>```

Body:
Purpose- I'm actually making doorbell kind of app, where on tapping a button ,app rings(plays a small audio) & on holding it app records audio till user holds it.
my objective- start recording when user holds button & stops when user releases button.

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private Button ring,record;
private String outputfile = null;
private MediaRecorder rec = null;
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case REQUEST_RECORD_AUDIO_PERMISSION:
            permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            break;
    }
    if (!permissionToRecordAccepted ) finish();

}

private void startrec()
{
    Log.e(LOG_TAG, "startRecording:Calling ");
    rec = new MediaRecorder();
    rec.setAudioSource(MediaRecorder.AudioSource.MIC);
    rec.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    rec.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    outputfile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.amr";
    rec.setOutputFile(outputfile);
    try {
        rec.prepare();
        rec.start();
    } catch (IOException ioe2) {
    }
    Toast.makeText(MainActivity.this, "RECORDING STARTED", Toast.LENGTH_SHORT).show();

}
private void stoprec(){
    rec.stop();rec.release();
    Toast.makeText(MainActivity.this, "RECORDING STOPPED", Toast.LENGTH_SHORT).show();
    Log.e(LOG_TAG, "stopRecording:Calling ");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ring = findViewById(R.id.ringbutton);
    record =findViewById(R.id.recordbutton);

    ring.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v1) {
            try {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                r.play();
            } catch (IllegalStateException ise) {}
        }
    });

    record.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v2, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) startrec();
         else if (event.getAction() == MotionEvent.ACTION_UP) stoprec();
            return true;}
    });
}

}

Problem- app crashes on touching record button

if u know a better way to do this pls tell.

Body:
Instead of OnClick You should use OnTouch Listener event and start recording on ACTION_DOWN and stop on ACTION_UP do add permissions as well for audio recording.!

 <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    private MediaRecorder mRecorder = null;

    private String mFileName = null;

      mRecordButton.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {

                    //if Button is Pressed.! or user Id Holding Button
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        startRecording();

                        Toast.makeText(context, "Hold To Record.!", Toast.LENGTH_SHORT).show();

                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                        //Do Nothing
                        stopRecording();

                        Toast.makeText(context, "Recorded.!", Toast.LENGTH_SHORT).show();
                    }

                    return false;
                }
            });

    private void startRecording() {

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        // Record to the external cache directory for visibility
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();

        //getExternalCacheDir().getAbsolutePath();

        String id = new String(UUID.randomUUID().toString());

        mFileName += "/recordedAudio/" + id + ".mp3";
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        mRecorder.start();

        Log.e(LOG_TAG, "Recording:Calling ");

    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;

        Log.e(LOG_TAG, "stopRecording:Calling ");

    }


问:
Cufon with hover on parent element
This is what I have: http://thezoomer.net/clubroyale/

I applied Cufon on the a element inside the .nav-item

```<code>Cufon.replace('.nav-item a', {fontFamily: 'Yanone Kaffeesatz',
                                    hover:true,
                                    hoverables: { li:true }
                                    });
</code>```

This is what I have inside the menu

```<code><li class="nav-item"><a href="./">HOME</a></li>
</code>```

and this is what I have inside the css

```<code>.nav-item{
     color: #a8956c;
     background-color:#fff;
     cursor:pointer;

    white-space:nowrap;
}
.nav-item:hover{
     color: #fff;
     background-color:#a8956c;

}
</code>```

Evidently, I want the css hover to work. I know It will not work in this state because Cufon has tied the refresh to the a element and not the whole parent element (which is tied from the css ). However, if I apply the css to .nav-item a the hover will work but only on the portion of the menu element.

Also, I have tried applying Cufon on .nav-item without the a, the hover works but some Cufon draws some weird white spaces without having to.

So, is there something like hoverables: { parent:true } for the element to receive hover events from the parent element too ?

Thanks!

答:
This seems to work as expected:

JS:

```<code>Cufon.replace('.nav-item a', { fontFamily: 'Yanone Kaffeesatz', hover: true });
</code>```

CSS:

```<code>.nav-item a {
    color: #a8956c;
}

.nav-item a:hover {
    color: #fff;
}
</code>```

Title: Cufon with hover on parent element

Body:
This is what I have: http://thezoomer.net/clubroyale/

I applied Cufon on the a element inside the .nav-item

Cufon.replace('.nav-item a', {fontFamily: 'Yanone Kaffeesatz',
                                    hover:true,
                                    hoverables: { li:true }
                                    });

This is what I have inside the menu

HOME

and this is what I have inside the css

.nav-item{
     color: #a8956c;
     background-color:#fff;
     cursor:pointer;

    white-space:nowrap;
}
.nav-item:hover{
     color: #fff;
     background-color:#a8956c;

}

Evidently, I want the css hover to work. I know It will not work in this state because Cufon has tied the refresh to the a element and not the whole parent element (which is tied from the css ). However, if I apply the css to .nav-item a the hover will work but only on the portion of the menu element.

Also, I have tried applying Cufon on .nav-item without the a, the hover works but some Cufon draws some weird white spaces without having to.

So, is there something like hoverables: { parent:true } for the element to receive hover events from the parent element too ?

Thanks!

Body:
This seems to work as expected:

JS:

Cufon.replace('.nav-item a', { fontFamily: 'Yanone Kaffeesatz', hover: true });

CSS:

.nav-item a {
    color: #a8956c;
}

.nav-item a:hover {
    color: #fff;
}


问:
How to get gridview multiple positions and store into array variable
Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position  in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.

Activity

```<code>public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {

String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;

ImageView Ivseats;

public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";

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

    GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

            String a = String.valueOf(position);

            Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
            v.setBackgroundColor(Color.GREEN);
            adapter.notifyDataSetChanged();
        }
    });

}

private void initviews() {

    GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
    GridUserSeats.setOnItemClickListener(this);

    textView1=(TextView) findViewById(R.id.textView1);

   // textView2=(TextView) findViewById(R.id.textView2);

    Intent intent = getIntent();

    first_name = intent.getStringExtra("first_name");
    last_name = intent.getStringExtra("last_name");

}

private void callSeatsApi() {

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("events", event_id);
    RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
            EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}

@Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {

}

@Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
    switch (mode)
    {
        case EM_SEATS:
            EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
            adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
            GridUserSeats.setAdapter(adapter);
            break;
    }

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

}
</code>```

Adapter

```<code>    import android.content.Context;
    import android.content.Intent;
     import android.support.annotation.NonNull;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.squareup.picasso.Picasso;
    import java.util.ArrayList;
    import java.util.List;
    import cfirst.live.com.R;
    import cfirst.live.com.model.BasketModel;
    import cfirst.live.com.model.EM_event_total_UserSeatsModel;

public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private  String[] mobileValuesD;

private static class ViewHolder {
    TextView TvEmUserSeats;
    ImageView IvUsreSeats,available,selctedimag;

}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();

public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
    super(context, R.layout.list_em_get_seats, data);
    this.dataSet = data;
    this.mContext=context;

}
public int getTagFromPosition(int position) {
    return tagCollection[position];
}

@Override
public void onClick(View v) {
    int position=(Integer) v.getTag();
    Object object= getItem(tagCollection[position]);

    EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    EM_event_total_UserSeatsModel dataModel = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag

    final View result;

    if (convertView == null) {

        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);

        viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
        viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);

        result=convertView;

        convertView.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
        result=convertView;
      }

    String blue_available = "seat3.png";
    String red_booked = "seat1.png";

    String get_seat = dataModel.getBookedStatus();
    viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
    if(Integer.parseInt(get_seat) == 1){
        Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);

    }else
    {

        Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);

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

答:
// create an Arraylist and add the selected position in a list</p>

```<code>List <int> selectedArray = new ArrayList<>();

  @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

int click = (int) parent.getItemAtPosition(position);

selectedArray.add(click);
}
</code>```

Body:
Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position  in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.

Activity

public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {

String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;

ImageView Ivseats;

public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";

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

    GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

            String a = String.valueOf(position);

            Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
            v.setBackgroundColor(Color.GREEN);
            adapter.notifyDataSetChanged();
        }
    });

}

private void initviews() {

    GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
    GridUserSeats.setOnItemClickListener(this);

    textView1=(TextView) findViewById(R.id.textView1);

   // textView2=(TextView) findViewById(R.id.textView2);

    Intent intent = getIntent();

    first_name = intent.getStringExtra("first_name");
    last_name = intent.getStringExtra("last_name");

}

private void callSeatsApi() {

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("events", event_id);
    RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
            EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}

@Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {

}

@Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
    switch (mode)
    {
        case EM_SEATS:
            EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
            adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
            GridUserSeats.setAdapter(adapter);
            break;
    }

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

}

Adapter

    import android.content.Context;
    import android.content.Intent;
     import android.support.annotation.NonNull;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.squareup.picasso.Picasso;
    import java.util.ArrayList;
    import java.util.List;
    import cfirst.live.com.R;
    import cfirst.live.com.model.BasketModel;
    import cfirst.live.com.model.EM_event_total_UserSeatsModel;

public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private  String[] mobileValuesD;

private static class ViewHolder {
    TextView TvEmUserSeats;
    ImageView IvUsreSeats,available,selctedimag;

}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();

public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
    super(context, R.layout.list_em_get_seats, data);
    this.dataSet = data;
    this.mContext=context;

}
public int getTagFromPosition(int position) {
    return tagCollection[position];
}

@Override
public void onClick(View v) {
    int position=(Integer) v.getTag();
    Object object= getItem(tagCollection[position]);

    EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    EM_event_total_UserSeatsModel dataModel = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag

    final View result;

    if (convertView == null) {

        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);

        viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
        viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);

        result=convertView;

        convertView.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
        result=convertView;
      }

    String blue_available = "seat3.png";
    String red_booked = "seat1.png";

    String get_seat = dataModel.getBookedStatus();
    viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
    if(Integer.parseInt(get_seat) == 1){
        Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);

    }else
    {

        Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);

    }
    return convertView;
}
}

Body:
// create an Arraylist and add the selected position in a list

List <int> selectedArray = new ArrayList<>();

  @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

int click = (int) parent.getItemAtPosition(position);

selectedArray.add(click);
}


问:
Pandas dataframe column value case insensitive replace where <condition>
Is there a case insensitive version for pandas.DataFrame.replace? https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.replace.html

I need to replace string values in a column subject to a case-insensitive condition of the form "where label == a or label == b or label == c".

答:
I think need convert to lower and then replace by condition with isin:

```<code>d = {'a':['test', 'Test', 'cat', 'CAT', 'dog', 'Cat']}
df = pd.DataFrame(data=d)

m = df['a'].str.lower().isin(['cat','test'])
df.loc[m, 'a'] = 'baby'
print (df)
      a
0  baby
1  baby
2  baby
3  baby
4   dog
5  baby
</code>```

Another solution:

```<code>df['b'] = df['a'].str.replace('test', 'baby', flags=re.I)
print (df)
      a     b
0  test  baby
1  Test  baby
2   cat   cat
3   CAT   CAT
4   dog   dog
5   Cat   Cat
</code>```

Body:
I think need convert to lower and then replace by condition with isin:

d = {'a':['test', 'Test', 'cat', 'CAT', 'dog', 'Cat']}
df = pd.DataFrame(data=d)

m = df['a'].str.lower().isin(['cat','test'])
df.loc[m, 'a'] = 'baby'
print (df)
      a
0  baby
1  baby
2  baby
3  baby
4   dog
5  baby

Another solution:

df['b'] = df['a'].str.replace('test', 'baby', flags=re.I)
print (df)
      a     b
0  test  baby
1  Test  baby
2   cat   cat
3   CAT   CAT
4   dog   dog
5   Cat   Cat