问:
How can I get a simple c# web service to return <?xml version="1.0" encoding="utf-16" ?> header?
I've written a very simple web service that returns an XML document.

The header for that document is currently
    <?xml version="1.0" encoding="utf-8" ?>

and I would like it to return <?xml version="1.0" encoding="utf-16" ?>

How can I change the default output encoding in the .asmx or .cs file?

```<code>smo.asmx
<%@ WebService Language="C#" Class="smo" %>

smo.asmx
using <blah>

[WebService(Namespace="http://www.bl.uk/webservices/")]
public class smo : WebService
{
    [XmlRoot(ElementName = "SQLServer")]
    public class CDatabaseBackup
{
    public string ServerName;
    public string DatabaseCount;
     }

//
// Generic SMO query processor
//
[WebMethod(Description = "WMIClassProperty: ", EnableSession = false, CacheDuration=60)]

public CDatabaseBackup smoDatabaseBackupStatus(string SQLServerName)
{
    CDatabaseBackup result = new CDatabaseBackup();
    Server svr;
              <blah>
              return result;
      }
</code>```

Ultimately this web service will be used within a SQL Server function and converted into an xml data type.  According to the documentation this needs to be UTF-16.

```<code>alter
procedure monitor_sqlbackupaudit
as
begin

declare @l_xml_result   nvarchar(max)
set @l_xml_result   = ( select dbo.uspSMODatabaseBackup('sqlprod1vs') )
--set   @l_xml_result   = replace(@l_xml_result,'UTF-8','UTF-16');

declare @l_xml      xml
set @l_xml      = @l_xml_result

end
go
</code>```

```<code>exec monitor_sqlbackupaudit

Msg 9402, Level 16, State 1, Procedure monitor_sqlbackupaudit, Line 15
XML parsing: line 1, character 38, unable to switch the encoding
</code>```

答:
You can configure your web service to process UTF-16 instead of UTF-8 in the globalization section of Web.config. The requestEncoding and responseEncoding attributes of the globalization tag should be set to UTF-16.

```<code><globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
</code>```

must be converted to

```<code><globalization requestEncoding="utf-16" responseEncoding="utf-16"/>
</code>```

This change will allow the web service to output UTF-16, but it will also require the client to make its request in UTF-16.

Body:
I've written a very simple web service that returns an XML document.

The header for that document is currently
    <?xml version="1.0" encoding="utf-8" ?>

and I would like it to return <?xml version="1.0" encoding="utf-16" ?>

How can I change the default output encoding in the .asmx or .cs file?

smo.asmx
<%@ WebService Language="C#" Class="smo" %>

smo.asmx
using <blah>

[WebService(Namespace="http://www.bl.uk/webservices/")]
public class smo : WebService
{
    [XmlRoot(ElementName = "SQLServer")]
    public class CDatabaseBackup
{
    public string ServerName;
    public string DatabaseCount;
     }

//
// Generic SMO query processor
//
[WebMethod(Description = "WMIClassProperty: ", EnableSession = false, CacheDuration=60)]

public CDatabaseBackup smoDatabaseBackupStatus(string SQLServerName)
{
    CDatabaseBackup result = new CDatabaseBackup();
    Server svr;
              <blah>
              return result;
      }

Ultimately this web service will be used within a SQL Server function and converted into an xml data type.  According to the documentation this needs to be UTF-16.

alter
procedure monitor_sqlbackupaudit
as
begin

declare @l_xml_result   nvarchar(max)
set @l_xml_result   = ( select dbo.uspSMODatabaseBackup('sqlprod1vs') )
--set   @l_xml_result   = replace(@l_xml_result,'UTF-8','UTF-16');

declare @l_xml      xml
set @l_xml      = @l_xml_result

end
go

exec monitor_sqlbackupaudit

Msg 9402, Level 16, State 1, Procedure monitor_sqlbackupaudit, Line 15
XML parsing: line 1, character 38, unable to switch the encoding

Body:
You can configure your web service to process UTF-16 instead of UTF-8 in the globalization section of Web.config. The requestEncoding and responseEncoding attributes of the globalization tag should be set to UTF-16.

<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>

must be converted to

<globalization requestEncoding="utf-16" responseEncoding="utf-16"/>

This change will allow the web service to output UTF-16, but it will also require the client to make its request in UTF-16.


来源: stackexchange

问:
Placing an imageview at the center of the layout regardless of screen size?
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

```<code><?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

答:
Replace your ImageView with,

```<code><ImageView
    android:id="@+id/imageView"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_alignParentTop="true"
    android:layout_centerInParent="true"
    android:layout_marginTop="140dp"
    android:src="@drawable/app_icon" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>

Body:
Replace your ImageView with,

<ImageView
    android:id="@+id/imageView"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_alignParentTop="true"
    android:layout_centerInParent="true"
    android:layout_marginTop="140dp"
    android:src="@drawable/app_icon" />


问:
disable other input[file] untill the first ( file #1 ) one is selected
i have multiple inputs for file upload and i'm trying by jquery to disable the rest until the first ( file #1 ) one is selected then enable the rest

My code :

<input type="file" id="checkupload" name="image" />
<input type="file" id="checkupload" name="image2" />
<input type="file" id="checkupload" name="image3" />
<input type="file" id="checkupload" name="image4" />
<input type="file" id="checkupload" name="image5" />
<input type="file" id="checkupload" name="image6" />
<input type="file" id="checkupload" name="image7" />
<input type="file" id="checkupload" name="image8" />```

答:
Disable rest of fields, enable on change:

$(document).ready(function () {
  $('.checkupload').change(function () {
    if ($(this).next().length) {
      $(this).next().prop('disabled', false);
    }
  });
});```
<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>
<input type="file" class="checkupload" name="image"/>
<input type="file" class="checkupload" name="image2" disabled="disabled"/>
<input type="file" class="checkupload" name="image3" disabled="disabled"/>
<input type="file" class="checkupload" name="image4" disabled="disabled"/>
<input type="file" class="checkupload" name="image5" disabled="disabled"/>
<input type="file" class="checkupload" name="image6" disabled="disabled"/>
<input type="file" class="checkupload" name="image7" disabled="disabled"/>
<input type="file" class="checkupload" name="image8" disabled="disabled"/></code>```

To enable all of them at once, unwrap code from IF and remove .next()

Body:
Disable rest of fields, enable on change:

$(document).ready(function () {
  $('.checkupload').change(function () {
    if ($(this).next().length) {
      $(this).next().prop('disabled', false);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="checkupload" name="image"/>
<input type="file" class="checkupload" name="image2" disabled="disabled"/>
<input type="file" class="checkupload" name="image3" disabled="disabled"/>
<input type="file" class="checkupload" name="image4" disabled="disabled"/>
<input type="file" class="checkupload" name="image5" disabled="disabled"/>
<input type="file" class="checkupload" name="image6" disabled="disabled"/>
<input type="file" class="checkupload" name="image7" disabled="disabled"/>
<input type="file" class="checkupload" name="image8" disabled="disabled"/>

To enable all of them at once, unwrap code from IF and remove .next()


问:
How to implement SearchView with ListView using custom object arraylist?
I have a custom listview, which contains an object type Arraylist, and on this same activity I have a SearchView, how to search and display only the objects according to the keywords eg getName (), getCity () , ...
Here my code, my onResume

```<code>    @Override
    protected void onResume() {
        super.onResume();
ArrayList<User> users;
    searchBar = findViewById(R.id.maBtnSearch);

        db = new DatabaseUser(this);
        users = db.getData();

        final CustomAdapter adapter = new CustomAdapter(this, users);
        listView.setAdapter(adapter);

        searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });

    }
</code>```

This is my adapter class:

```<code>    package com.example.mickael.gestioclientel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by MICKAEL on 02/12/2017.
 */

class CustomAdapter extends ArrayAdapter{

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<User> users; //Lui transmettre le tableau adapter
    private DatabaseUser db;

    public CustomAdapter(Context context, ArrayList<User> users){
        super(context, R.layout.design_list_user, users); //Lui transmettre le layout design de ta listeview
        db = new DatabaseUser(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.users = users;
    }

    private class ViewHolder{
        TextView name, phone, date;
        ImageView btnDial, btnMap, menuPoint;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        final ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.design_list_user, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.name = convertView.findViewById(R.id.luPrenom);
            viewHolder.phone = convertView.findViewById(R.id.maTxtNumber);
            viewHolder.btnDial = convertView.findViewById(R.id.maBtnDial);
            viewHolder.btnMap = convertView.findViewById(R.id.maBtnMap);
            viewHolder.menuPoint = convertView.findViewById(R.id.luTrois);
            viewHolder.date = convertView.findViewById(R.id.maAdd);

            //Definition du tag
            convertView.setTag(viewHolder);

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

        //Definition des changements
        final User user = users.get(position);

        //On regle la taille du nom selon les caractere
        if(user.getName().length() == 15){
            viewHolder.name.setTextSize(24);
        }else if(user.getName().length() == 16){
            viewHolder.name.setTextSize(23);
        }else if(user.getName().length() == 17){
            viewHolder.name.setTextSize(22);
        }else if(user.getName().length() > 18){
            viewHolder.name.setTextSize(21);
        }
        viewHolder.name.setText(user.getName()); //Definition du nom

        //Definition de lajout ou modification
        String addOrUpdate = "Modifie le";
        viewHolder.date.setText(addOrUpdate + " " + user.getDate()); //Definition de la date
        viewHolder.date.setTextSize(15);

        //TODO Je dois regler ce probleme de zero ci dessous
        String phone = String.valueOf(user.getPhone());
        if(phone.equals("93260")){
            phone = "No number phone";
            viewHolder.phone.setTextSize(16);
        }else{
            phone = "0" + phone;
            viewHolder.phone.setTextSize(20);
        }
        viewHolder.phone.setText(phone);

        //OnClick sur les boutons
        viewHolder.btnDial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        //TODO ICI Aussi Je dois regler ce probleme de zero ci dessous
                        Uri.parse("tel:0" + user.getPhone()));
                context.startActivity(intent); //Laligne la plus importante!!
            }
        });

        viewHolder.btnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adressMap(); //Fonction appel de louverture des map
            }
            public void adressMap() {
                String adress = user.getAdresse();
                String txtFind = " ";
                String txtReplace= "+";
                String tmp;

                int lgFind = txtFind.length();

                for (int k = 0; k < adress.length(); k++) {
                    try {
                        tmp = adress.substring(k, k + lgFind);
                    }
                    catch(Exception e) {
                        break;
                    }
                    if ( tmp.equalsIgnoreCase(txtFind) ) {
                        adress = adress.substring(0, k) + txtReplace + adress.substring(k + lgFind,adress.length());
                    }
                }

                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("google.navigation:q=" +adress+ "+" + user.getCity()));
                context.startActivity(intent);
            } //Remplacement des espace par des "+"
        }); //Pour lancer la navigation

        //le menu a 3 points
        viewHolder.menuPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuTroisPoint(viewHolder, user);
            }
        });

        return convertView;
    }

    public void menuTroisPoint(ViewHolder viewHolder, final User user) {
        PopupMenu popupMenu = new PopupMenu(context, viewHolder.menuPoint);

        popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent;
                switch (item.getItemId()){
                    case R.id.menu_delete:
                        //Si il selectionne Delete on lui apparait un popup de securite
                        dialogConfirmDelete(user);
                        break;
                    case R.id.menu_edit:
                        intentPageEdit(user); //Vers la page dedition
                        break;
                    case R.id.menu_send:
                        popupSendSMS();
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
    }

    public void popupSendSMS() {
        android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_sms, null);

        RadioGroup rg = mView.findViewById(R.id.cdsRadioGroup);
        EditText inputPers = mView.findViewById(R.id.cdsInputPers);

        int radioId = rg.getCheckedRadioButtonId();

        if (radioId == R.id.cdsRadioPers) { //Cest le ID du RADIO LUI MEME
            inputPers.setEnabled(true); //TODO CORRIGER CE PROBLEME
        }

        cBuilder.setView(mView);
        android.support.v7.app.AlertDialog dialog = cBuilder.create();
        dialog.show();
    }

    public void dialogConfirmDelete(final User user) {
        AlertDialog.Builder popupSure = new AlertDialog.Builder(context); //On creer la fenetre
        popupSure.setTitle("Delete"); //Le titre de l'alerte
        popupSure.setMessage("Are you sure?");

        popupSure.setNegativeButton("CANCEL", null);  //Option cancel
        //Option OK
        popupSure.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //On supprime lutilisateur selon le ID
                delete(user);
            }
        });  //Option ok
        popupSure.show(); //On fait apparaitre le popup
    }

    public void delete(User user) {
        db.delete((int)user.getId());
        Toast.makeText(context, "" + user.getName() + " deleted", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
        ((Activity)context).finish();
    } //Supprimer un user

    public void intentPageEdit(User user) {
        Intent intent;
        intent = new Intent(context, AddUserActivity.class);
        Bundle args = new Bundle(); //On creer le bundle car cest un objet
        args.putSerializable("user", (user)); //On pose les donnees de l'intent pour le convertir en bundle en tant que objet
        intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
        context.startActivity(intent);
    } //Aller vers la page dedition

}
</code>```

up
Thanks help me please
Thanks help me please
Thanks help me please
Thanks help me please

答:
Make one more arraylist in your adapter class and make your adapter implements Filterable, try changing your adapter like below :

```<code>class CustomAdapter extends ArrayAdapter implements Filterable{

private Context context;
private LayoutInflater inflater;
private ArrayList<User> users;
private ArrayList<User> usersFilter;
private DatabaseUser db;

public CustomAdapter(Context context, ArrayList<User> users){
    super(context, R.layout.design_list_user, users); //Lui transmettre le layout design de ta listeview
    db = new DatabaseUser(context);
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.users = users;
    this.usersFilter= users;
}

private class ViewHolder{
    TextView name, phone, date;
    ImageView btnDial, btnMap, menuPoint;
}

 @Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String charString = charSequence.toString();

            if (charString.isEmpty()) {

                users= usersFilter;
            } else {

                ArrayList<User> filteredList = new ArrayList<>();

                for (User user: usersFilter) {

                    if ( user.getYourField().toLowerCase().contains(charString)) {

                        filteredList.add(user);
                    }
                }

                users= filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = users;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            users= (ArrayList<User>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final ViewHolder viewHolder;

    if(convertView == null){
        //Reglage general
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.design_list_user, parent, false); //Layout du design

        //Recuperation des ID
        viewHolder.name = convertView.findViewById(R.id.luPrenom);
        viewHolder.phone = convertView.findViewById(R.id.maTxtNumber);
        viewHolder.btnDial = convertView.findViewById(R.id.maBtnDial);
        viewHolder.btnMap = convertView.findViewById(R.id.maBtnMap);
        viewHolder.menuPoint = convertView.findViewById(R.id.luTrois);
        viewHolder.date = convertView.findViewById(R.id.maAdd);

        //Definition du tag
        convertView.setTag(viewHolder);

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

    //Definition des changements
    final User user = users.get(position);

    //On regle la taille du nom selon les caractere
    if(user.getName().length() == 15){
        viewHolder.name.setTextSize(24);
    }else if(user.getName().length() == 16){
        viewHolder.name.setTextSize(23);
    }else if(user.getName().length() == 17){
        viewHolder.name.setTextSize(22);
    }else if(user.getName().length() > 18){
        viewHolder.name.setTextSize(21);
    }
    viewHolder.name.setText(user.getName()); //Definition du nom

    //Definition de lajout ou modification
    String addOrUpdate = "Modifie le";
    viewHolder.date.setText(addOrUpdate + " " + user.getDate()); //Definition de la date
    viewHolder.date.setTextSize(15);

    //TODO Je dois regler ce probleme de zero ci dessous
    String phone = String.valueOf(user.getPhone());
    if(phone.equals("93260")){
        phone = "No number phone";
        viewHolder.phone.setTextSize(16);
    }else{
        phone = "0" + phone;
        viewHolder.phone.setTextSize(20);
    }
    viewHolder.phone.setText(phone);

    //OnClick sur les boutons
    viewHolder.btnDial.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    //TODO ICI Aussi Je dois regler ce probleme de zero ci dessous
                    Uri.parse("tel:0" + user.getPhone()));
            context.startActivity(intent); //Laligne la plus importante!!
        }
    });

    viewHolder.btnMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adressMap(); //Fonction appel de louverture des map
        }
        public void adressMap() {
            String adress = user.getAdresse();
            String txtFind = " ";
            String txtReplace= "+";
            String tmp;

            int lgFind = txtFind.length();

            for (int k = 0; k < adress.length(); k++) {
                try {
                    tmp = adress.substring(k, k + lgFind);
                }
                catch(Exception e) {
                    break;
                }
                if ( tmp.equalsIgnoreCase(txtFind) ) {
                    adress = adress.substring(0, k) + txtReplace + adress.substring(k + lgFind,adress.length());
                }
            }

            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("google.navigation:q=" +adress+ "+" + user.getCity()));
            context.startActivity(intent);
        } //Remplacement des espace par des "+"
    }); //Pour lancer la navigation

    //le menu a 3 points
    viewHolder.menuPoint.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuTroisPoint(viewHolder, user);
        }
    });

    return convertView;
}

public void menuTroisPoint(ViewHolder viewHolder, final User user) {
    PopupMenu popupMenu = new PopupMenu(context, viewHolder.menuPoint);

    popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            Intent intent;
            switch (item.getItemId()){
                case R.id.menu_delete:
                    //Si il selectionne Delete on lui apparait un popup de securite
                    dialogConfirmDelete(user);
                    break;
                case R.id.menu_edit:
                    intentPageEdit(user); //Vers la page dedition
                    break;
                case R.id.menu_send:
                    popupSendSMS();
                    break;
            }
            return true;
        }
    });
    popupMenu.show();
}

public void popupSendSMS() {
    android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
    View mView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_sms, null);

    RadioGroup rg = mView.findViewById(R.id.cdsRadioGroup);
    EditText inputPers = mView.findViewById(R.id.cdsInputPers);

    int radioId = rg.getCheckedRadioButtonId();

    if (radioId == R.id.cdsRadioPers) { //Cest le ID du RADIO LUI MEME
        inputPers.setEnabled(true); //TODO CORRIGER CE PROBLEME
    }

    cBuilder.setView(mView);
    android.support.v7.app.AlertDialog dialog = cBuilder.create();
    dialog.show();
}

public void dialogConfirmDelete(final User user) {
    AlertDialog.Builder popupSure = new AlertDialog.Builder(context); //On creer la fenetre
    popupSure.setTitle("Delete"); //Le titre de l'alerte
    popupSure.setMessage("Are you sure?");

    popupSure.setNegativeButton("CANCEL", null);  //Option cancel
    //Option OK
    popupSure.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //On supprime lutilisateur selon le ID
            delete(user);
        }
    });  //Option ok
    popupSure.show(); //On fait apparaitre le popup
}

public void delete(User user) {
    db.delete((int)user.getId());
    Toast.makeText(context, "" + user.getName() + " deleted", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(context, MainActivity.class);
    context.startActivity(intent);
    ((Activity)context).finish();
} //Supprimer un user

public void intentPageEdit(User user) {
    Intent intent;
    intent = new Intent(context, AddUserActivity.class);
    Bundle args = new Bundle(); //On creer le bundle car cest un objet
    args.putSerializable("user", (user)); //On pose les donnees de l'intent pour le convertir en bundle en tant que objet
    intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
    context.startActivity(intent);
} //Aller vers la page dedition

}
</code>```

NOTE  : Replace user.getYourField() with whatever field in your User class to check against the filter text you passed into the adapter

Body:
I have a custom listview, which contains an object type Arraylist, and on this same activity I have a SearchView, how to search and display only the objects according to the keywords eg getName (), getCity () , ...
Here my code, my onResume

    @Override
    protected void onResume() {
        super.onResume();
ArrayList<User> users;
    searchBar = findViewById(R.id.maBtnSearch);

        db = new DatabaseUser(this);
        users = db.getData();

        final CustomAdapter adapter = new CustomAdapter(this, users);
        listView.setAdapter(adapter);

        searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });

    }

This is my adapter class:

    package com.example.mickael.gestioclientel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by MICKAEL on 02/12/2017.
 */

class CustomAdapter extends ArrayAdapter{

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<User> users; //Lui transmettre le tableau adapter
    private DatabaseUser db;

    public CustomAdapter(Context context, ArrayList<User> users){
        super(context, R.layout.design_list_user, users); //Lui transmettre le layout design de ta listeview
        db = new DatabaseUser(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.users = users;
    }

    private class ViewHolder{
        TextView name, phone, date;
        ImageView btnDial, btnMap, menuPoint;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        final ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.design_list_user, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.name = convertView.findViewById(R.id.luPrenom);
            viewHolder.phone = convertView.findViewById(R.id.maTxtNumber);
            viewHolder.btnDial = convertView.findViewById(R.id.maBtnDial);
            viewHolder.btnMap = convertView.findViewById(R.id.maBtnMap);
            viewHolder.menuPoint = convertView.findViewById(R.id.luTrois);
            viewHolder.date = convertView.findViewById(R.id.maAdd);

            //Definition du tag
            convertView.setTag(viewHolder);

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

        //Definition des changements
        final User user = users.get(position);

        //On regle la taille du nom selon les caractere
        if(user.getName().length() == 15){
            viewHolder.name.setTextSize(24);
        }else if(user.getName().length() == 16){
            viewHolder.name.setTextSize(23);
        }else if(user.getName().length() == 17){
            viewHolder.name.setTextSize(22);
        }else if(user.getName().length() > 18){
            viewHolder.name.setTextSize(21);
        }
        viewHolder.name.setText(user.getName()); //Definition du nom

        //Definition de lajout ou modification
        String addOrUpdate = "Modifie le";
        viewHolder.date.setText(addOrUpdate + " " + user.getDate()); //Definition de la date
        viewHolder.date.setTextSize(15);

        //TODO Je dois regler ce probleme de zero ci dessous
        String phone = String.valueOf(user.getPhone());
        if(phone.equals("93260")){
            phone = "No number phone";
            viewHolder.phone.setTextSize(16);
        }else{
            phone = "0" + phone;
            viewHolder.phone.setTextSize(20);
        }
        viewHolder.phone.setText(phone);

        //OnClick sur les boutons
        viewHolder.btnDial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        //TODO ICI Aussi Je dois regler ce probleme de zero ci dessous
                        Uri.parse("tel:0" + user.getPhone()));
                context.startActivity(intent); //Laligne la plus importante!!
            }
        });

        viewHolder.btnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adressMap(); //Fonction appel de louverture des map
            }
            public void adressMap() {
                String adress = user.getAdresse();
                String txtFind = " ";
                String txtReplace= "+";
                String tmp;

                int lgFind = txtFind.length();

                for (int k = 0; k < adress.length(); k++) {
                    try {
                        tmp = adress.substring(k, k + lgFind);
                    }
                    catch(Exception e) {
                        break;
                    }
                    if ( tmp.equalsIgnoreCase(txtFind) ) {
                        adress = adress.substring(0, k) + txtReplace + adress.substring(k + lgFind,adress.length());
                    }
                }

                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("google.navigation:q=" +adress+ "+" + user.getCity()));
                context.startActivity(intent);
            } //Remplacement des espace par des "+"
        }); //Pour lancer la navigation

        //le menu a 3 points
        viewHolder.menuPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuTroisPoint(viewHolder, user);
            }
        });

        return convertView;
    }

    public void menuTroisPoint(ViewHolder viewHolder, final User user) {
        PopupMenu popupMenu = new PopupMenu(context, viewHolder.menuPoint);

        popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent;
                switch (item.getItemId()){
                    case R.id.menu_delete:
                        //Si il selectionne Delete on lui apparait un popup de securite
                        dialogConfirmDelete(user);
                        break;
                    case R.id.menu_edit:
                        intentPageEdit(user); //Vers la page dedition
                        break;
                    case R.id.menu_send:
                        popupSendSMS();
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
    }

    public void popupSendSMS() {
        android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_sms, null);

        RadioGroup rg = mView.findViewById(R.id.cdsRadioGroup);
        EditText inputPers = mView.findViewById(R.id.cdsInputPers);

        int radioId = rg.getCheckedRadioButtonId();

        if (radioId == R.id.cdsRadioPers) { //Cest le ID du RADIO LUI MEME
            inputPers.setEnabled(true); //TODO CORRIGER CE PROBLEME
        }

        cBuilder.setView(mView);
        android.support.v7.app.AlertDialog dialog = cBuilder.create();
        dialog.show();
    }

    public void dialogConfirmDelete(final User user) {
        AlertDialog.Builder popupSure = new AlertDialog.Builder(context); //On creer la fenetre
        popupSure.setTitle("Delete"); //Le titre de l'alerte
        popupSure.setMessage("Are you sure?");

        popupSure.setNegativeButton("CANCEL", null);  //Option cancel
        //Option OK
        popupSure.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //On supprime lutilisateur selon le ID
                delete(user);
            }
        });  //Option ok
        popupSure.show(); //On fait apparaitre le popup
    }

    public void delete(User user) {
        db.delete((int)user.getId());
        Toast.makeText(context, "" + user.getName() + " deleted", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
        ((Activity)context).finish();
    } //Supprimer un user

    public void intentPageEdit(User user) {
        Intent intent;
        intent = new Intent(context, AddUserActivity.class);
        Bundle args = new Bundle(); //On creer le bundle car cest un objet
        args.putSerializable("user", (user)); //On pose les donnees de l'intent pour le convertir en bundle en tant que objet
        intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
        context.startActivity(intent);
    } //Aller vers la page dedition

}

up
Thanks help me please
Thanks help me please
Thanks help me please
Thanks help me please

Body:
Make one more arraylist in your adapter class and make your adapter implements Filterable, try changing your adapter like below :

class CustomAdapter extends ArrayAdapter implements Filterable{

private Context context;
private LayoutInflater inflater;
private ArrayList<User> users;
private ArrayList<User> usersFilter;
private DatabaseUser db;

public CustomAdapter(Context context, ArrayList<User> users){
    super(context, R.layout.design_list_user, users); //Lui transmettre le layout design de ta listeview
    db = new DatabaseUser(context);
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.users = users;
    this.usersFilter= users;
}

private class ViewHolder{
    TextView name, phone, date;
    ImageView btnDial, btnMap, menuPoint;
}

 @Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String charString = charSequence.toString();

            if (charString.isEmpty()) {

                users= usersFilter;
            } else {

                ArrayList<User> filteredList = new ArrayList<>();

                for (User user: usersFilter) {

                    if ( user.getYourField().toLowerCase().contains(charString)) {

                        filteredList.add(user);
                    }
                }

                users= filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = users;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            users= (ArrayList<User>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final ViewHolder viewHolder;

    if(convertView == null){
        //Reglage general
        viewHolder = new ViewHolder();
        convertView = inflater.inflate(R.layout.design_list_user, parent, false); //Layout du design

        //Recuperation des ID
        viewHolder.name = convertView.findViewById(R.id.luPrenom);
        viewHolder.phone = convertView.findViewById(R.id.maTxtNumber);
        viewHolder.btnDial = convertView.findViewById(R.id.maBtnDial);
        viewHolder.btnMap = convertView.findViewById(R.id.maBtnMap);
        viewHolder.menuPoint = convertView.findViewById(R.id.luTrois);
        viewHolder.date = convertView.findViewById(R.id.maAdd);

        //Definition du tag
        convertView.setTag(viewHolder);

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

    //Definition des changements
    final User user = users.get(position);

    //On regle la taille du nom selon les caractere
    if(user.getName().length() == 15){
        viewHolder.name.setTextSize(24);
    }else if(user.getName().length() == 16){
        viewHolder.name.setTextSize(23);
    }else if(user.getName().length() == 17){
        viewHolder.name.setTextSize(22);
    }else if(user.getName().length() > 18){
        viewHolder.name.setTextSize(21);
    }
    viewHolder.name.setText(user.getName()); //Definition du nom

    //Definition de lajout ou modification
    String addOrUpdate = "Modifie le";
    viewHolder.date.setText(addOrUpdate + " " + user.getDate()); //Definition de la date
    viewHolder.date.setTextSize(15);

    //TODO Je dois regler ce probleme de zero ci dessous
    String phone = String.valueOf(user.getPhone());
    if(phone.equals("93260")){
        phone = "No number phone";
        viewHolder.phone.setTextSize(16);
    }else{
        phone = "0" + phone;
        viewHolder.phone.setTextSize(20);
    }
    viewHolder.phone.setText(phone);

    //OnClick sur les boutons
    viewHolder.btnDial.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    //TODO ICI Aussi Je dois regler ce probleme de zero ci dessous
                    Uri.parse("tel:0" + user.getPhone()));
            context.startActivity(intent); //Laligne la plus importante!!
        }
    });

    viewHolder.btnMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adressMap(); //Fonction appel de louverture des map
        }
        public void adressMap() {
            String adress = user.getAdresse();
            String txtFind = " ";
            String txtReplace= "+";
            String tmp;

            int lgFind = txtFind.length();

            for (int k = 0; k < adress.length(); k++) {
                try {
                    tmp = adress.substring(k, k + lgFind);
                }
                catch(Exception e) {
                    break;
                }
                if ( tmp.equalsIgnoreCase(txtFind) ) {
                    adress = adress.substring(0, k) + txtReplace + adress.substring(k + lgFind,adress.length());
                }
            }

            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("google.navigation:q=" +adress+ "+" + user.getCity()));
            context.startActivity(intent);
        } //Remplacement des espace par des "+"
    }); //Pour lancer la navigation

    //le menu a 3 points
    viewHolder.menuPoint.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuTroisPoint(viewHolder, user);
        }
    });

    return convertView;
}

public void menuTroisPoint(ViewHolder viewHolder, final User user) {
    PopupMenu popupMenu = new PopupMenu(context, viewHolder.menuPoint);

    popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            Intent intent;
            switch (item.getItemId()){
                case R.id.menu_delete:
                    //Si il selectionne Delete on lui apparait un popup de securite
                    dialogConfirmDelete(user);
                    break;
                case R.id.menu_edit:
                    intentPageEdit(user); //Vers la page dedition
                    break;
                case R.id.menu_send:
                    popupSendSMS();
                    break;
            }
            return true;
        }
    });
    popupMenu.show();
}

public void popupSendSMS() {
    android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
    View mView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_sms, null);

    RadioGroup rg = mView.findViewById(R.id.cdsRadioGroup);
    EditText inputPers = mView.findViewById(R.id.cdsInputPers);

    int radioId = rg.getCheckedRadioButtonId();

    if (radioId == R.id.cdsRadioPers) { //Cest le ID du RADIO LUI MEME
        inputPers.setEnabled(true); //TODO CORRIGER CE PROBLEME
    }

    cBuilder.setView(mView);
    android.support.v7.app.AlertDialog dialog = cBuilder.create();
    dialog.show();
}

public void dialogConfirmDelete(final User user) {
    AlertDialog.Builder popupSure = new AlertDialog.Builder(context); //On creer la fenetre
    popupSure.setTitle("Delete"); //Le titre de l'alerte
    popupSure.setMessage("Are you sure?");

    popupSure.setNegativeButton("CANCEL", null);  //Option cancel
    //Option OK
    popupSure.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //On supprime lutilisateur selon le ID
            delete(user);
        }
    });  //Option ok
    popupSure.show(); //On fait apparaitre le popup
}

public void delete(User user) {
    db.delete((int)user.getId());
    Toast.makeText(context, "" + user.getName() + " deleted", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(context, MainActivity.class);
    context.startActivity(intent);
    ((Activity)context).finish();
} //Supprimer un user

public void intentPageEdit(User user) {
    Intent intent;
    intent = new Intent(context, AddUserActivity.class);
    Bundle args = new Bundle(); //On creer le bundle car cest un objet
    args.putSerializable("user", (user)); //On pose les donnees de l'intent pour le convertir en bundle en tant que objet
    intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
    context.startActivity(intent);
} //Aller vers la page dedition

}

NOTE  : Replace user.getYourField() with whatever field in your User class to check against the filter text you passed into the adapter


问:
How to force a time series to plot on the whole year, when data is only a few months

I have multiple time series each having a different beginning and end time. When I plot them using pandas and matplotlib I get nice graphs beginning from t0 and ending at tx for each individual series. I know that I cannot plot different length series in one plot, but i would like to at least view them with the months lining up.

For example, say I have two series: 1, begins April and ends September, 2 begins February and ends December.

How do visualize them so that each series is plotted on a yearly graph (Jan to Dec) even though the data does not span those dates? I want to see them one above the other they lining up according to months.

I have it like this so far, with xlim=('jan', 'dec'), but I just get blank plots

```<code>for dfl in dfl_list[0:2]:
       dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
            ax=p1, fontsize=15, xlim=('Jan', 'Dec'))
       p1.set_title('Time vs VWC', fontsize=15)
       p1.set_ylabel('VWC (%)  ' + '{}'.format(imei), fontsize=15)
       p1.set_xlabel('Time Stamp', fontsize=15)
</code>```

I've also tried xticks instead of xlim, but I also get blank plots.

答:
The problem that I was having was that I thought that the argument for xlim could be be the strings 'Jan', and 'Dec', this ended up returning blank graphs because pyplot did not know how to fit a graph on string type. the solution is that xlim has to be passed datetime arguments:</p>

```<code>for dfl in dfl_list[0:2]:
    dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
       ax=p1, fontsize=15, xlim=(datetime(2017,1,1), datetime(2017,12,31))
    p1.set_title('Time vs VWC', fontsize=15)
    p1.set_ylabel('VWC (%)  ' + '{}'.format(imei), fontsize=15)
    p1.set_xlabel('Time Stamp', fontsize=15)
</code>```

Body:
I have multiple time series each having a different beginning and end time. When I plot them using pandas and matplotlib I get nice graphs beginning from t0 and ending at tx for each individual series. I know that I cannot plot different length series in one plot, but i would like to at least view them with the months lining up.

For example, say I have two series: 1, begins April and ends September, 2 begins February and ends December.

How do visualize them so that each series is plotted on a yearly graph (Jan to Dec) even though the data does not span those dates? I want to see them one above the other they lining up according to months.

I have it like this so far, with xlim=('jan', 'dec'), but I just get blank plots

for dfl in dfl_list[0:2]:
       dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
            ax=p1, fontsize=15, xlim=('Jan', 'Dec'))
       p1.set_title('Time vs VWC', fontsize=15)
       p1.set_ylabel('VWC (%)  ' + '{}'.format(imei), fontsize=15)
       p1.set_xlabel('Time Stamp', fontsize=15)

I've also tried xticks instead of xlim, but I also get blank plots.

Body:
The problem that I was having was that I thought that the argument for xlim could be be the strings 'Jan', and 'Dec', this ended up returning blank graphs because pyplot did not know how to fit a graph on string type. the solution is that xlim has to be passed datetime arguments:

for dfl in dfl_list[0:2]:
    dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
       ax=p1, fontsize=15, xlim=(datetime(2017,1,1), datetime(2017,12,31))
    p1.set_title('Time vs VWC', fontsize=15)
    p1.set_ylabel('VWC (%)  ' + '{}'.format(imei), fontsize=15)
    p1.set_xlabel('Time Stamp', fontsize=15)


问:
In rails 5 @font-face custom css is not working after I put fonts in assets's font folder?
I am using font-awesome custom css but it is not working in my rails application.

I am getting this error:

ActionController::RoutingError (No route matches [GET]
  "/fonts/fontawesome-webfont.woff2"):

added font In assets's stylesheet folder make style.css

```<code>@font-face { font-family: 'ProximaNovaA-Light'; src:
url('ProximaNovaA-Light.otf') format('opentype'),
url('ProximaNovaA-Light.woff') format('woff'),
url('ProximaNovaA-Light.eot') format('embedded-opentype'),
url('ProximaNovaA-Light.ttf') format('truetype'),
url('ProximaNovaA-Light.svg#ProximaNovaA-Light') format('svg');
font-weight: normal; font-style: normal; }
</code>```

I think this is a path issue, how can we fix it?

答:
Try this</p>

```<code>font-family: '/assets/ProximaNovaA-Light';
src: url('/assets/ProximaNovaA-Light.otf') format('opentype')
</code>```

Body:
I am using font-awesome custom css but it is not working in my rails application.

I am getting this error:

ActionController::RoutingError (No route matches [GET]
  "/fonts/fontawesome-webfont.woff2"):

added font In assets's stylesheet folder make style.css

@font-face { font-family: 'ProximaNovaA-Light'; src:
url('ProximaNovaA-Light.otf') format('opentype'),
url('ProximaNovaA-Light.woff') format('woff'),
url('ProximaNovaA-Light.eot') format('embedded-opentype'),
url('ProximaNovaA-Light.ttf') format('truetype'),
url('ProximaNovaA-Light.svg#ProximaNovaA-Light') format('svg');
font-weight: normal; font-style: normal; }

I think this is a path issue, how can we fix it?

Body:
Try this

font-family: '/assets/ProximaNovaA-Light';
src: url('/assets/ProximaNovaA-Light.otf') format('opentype')

ContentLicense: CC BY-SA 4.0


问:
Mobile UI frameworks & other UI scripts
I'm looking for the best cross browser compatible swipe script for android, iphone and other touch phones.  Has anyone used any of the available frameworks or have you used custom scripts?  What is your experience with these?

SenchaTouch
jQTouch
Phone Gap
Unify Project

Any others?  I am joining a mobile task force and would like to get more involved in one or more of these communities so I can provide some UI support.

Thanks,
Seth

答:
First of all, let's sort out the apples and oranges.

PhoneGap and Appcelerator Titanium are NOT UI frameworks.  They are both Web to Native bridging technologies.  They provide JavaScript API's for mobile capabilities like accelerometer, contacts, GPS, telephony, etc.  Also, they facilitate the creation of a deployable mobile app (versus a web page)

Sencha Touch, jqTouch, and jQuery Mobile are mobile UI frameworks that provide support for mobile UI concepts, like touch, swipe, transitions, small screen sizes, etc.   They can run in a pure web page or be used in conjunction with PhoneGap or Appcelerator Titanium in a mobile app.

I'm not too familiar with the Unify Project, but it seems to be a bundle of PhoneGap plus their own UI framework.

Both Sencha Touch and jQuery Mobile are in early days, but already have some great capabilities and they're moving fast.

ContentLicense: CC BY-SA 2.5

Title: Mobile UI frameworks & other UI scripts


问:
how to require user give an image filepath?
I am new to Android.

I'm trying to build an Image player.

I ask the user for an image they want to open.

But I don't know the way how to ask the user to provide that URL.

Please Help me....

答:
```<code>Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_CODE_LOAD_IMAGE);
</code>```


问:
Cannot set my custom NSView as first responder
I've created a simple subclass of NSView, but calling becomeFirstResponder seems to have no effect - the framework doesn't even call my acceptsFirstResponder method.

However, if I click with my mouse on my view it seems to becomes the first responder and I can receive keyDown events.

Here is my NSView subclass:

```<code>@interface MyView : NSView
@end

@implementation MyView
- (void) keyDown: (NSEvent*) with {
    NSLog(@"keyDown");
}

- (BOOL)acceptsFirstResponder {
    NSLog(@"acceptsFirstResponder");
    return YES;
}

- (BOOL)canBecomeKeyView {
    NSLog(@"canBecomeKeyView");
    return YES;
}

@end
</code>```

And here is how I'm setting it up in my AppDelegate:

```<code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

      NSRect frameRect = NSMakeRect(0,0,100,100);
      MyView *myView = [[MyView alloc] initWithFrame:frameRect];
      [_window.contentView addSubview:myView];

      [myView becomeFirstResponder];
}
</code>```

What am I doing wrong?

答:
Whoops - the documentation says 'Never invoke this method directly'.  So I should call

```<code>[_window makeFirstResponder:myView];
</code>```

instead of

```<code>[myView becomeFirstResponder];
</code>```

Thanks to Willeke for the hint.

Body:
I've created a simple subclass of NSView, but calling becomeFirstResponder seems to have no effect - the framework doesn't even call my acceptsFirstResponder method.

However, if I click with my mouse on my view it seems to becomes the first responder and I can receive keyDown events.

Here is my NSView subclass:

@interface MyView : NSView
@end

@implementation MyView
- (void) keyDown: (NSEvent*) with {
    NSLog(@"keyDown");
}

- (BOOL)acceptsFirstResponder {
    NSLog(@"acceptsFirstResponder");
    return YES;
}

- (BOOL)canBecomeKeyView {
    NSLog(@"canBecomeKeyView");
    return YES;
}

@end

And here is how I'm setting it up in my AppDelegate:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

      NSRect frameRect = NSMakeRect(0,0,100,100);
      MyView *myView = [[MyView alloc] initWithFrame:frameRect];
      [_window.contentView addSubview:myView];

      [myView becomeFirstResponder];
}

What am I doing wrong?

Body:
Whoops - the documentation says 'Never invoke this method directly'.  So I should call

[_window makeFirstResponder:myView];

instead of

[myView becomeFirstResponder];

Thanks to Willeke for the hint.


问:
Why gets this initializer argument destroyed?
I have an initializer with two arguments:

```<code>-(id) initWithSourceFrame:(CGRect)sourceViewFrame  mappedFrame:(CGRect)mappedViewFrame {
  CGRect copy = mappedViewFrame;
  self = [super init];
  if (self) {
    // not able to access mappedViewFrame here..
    // copy is ok
    // doing initialization here...
  }
  return self;
}
</code>```

It seemed to get wrong values from the second argument (mappedViewFrame). When looking for the error, I found out that mappedViewFrame gets destroyed (overridden in memory?).
This can be easily observed in the debugger:

Debugger Screenshot on flickr (I cannot post images yet)

The copy is still holding the original values, so using the copy was a workaround in this case. But of course I want to understand why this could happen.
The class is a direct subclass of NSObject, the whole project is a OS X native app.
The first argument was never destroyed. The problem does not relate to the values passed in. I switched them and it was always the second which was corrupted.

For example, I called the initializer with these example arguments (different from those in the debugger screenshots), and the error occured in the same way:

```<code>Mapper *mapper = [[Mapper alloc] initWithSourceFrame:CGRectMake(0, 0, 100, 100) mappedFrame:CGRectMake(0,0, 200,200)];
</code>```

The method declaration:

```<code>-(id) initWithSourceFrame:(CGRect) sourceViewFrame mappedFrame:(CGRect) mappedViewFrame;
</code>```

I'm somewhat new to Objective-C, so I am sorry if I missed something obvious. However, it looks strange that an argument does not keep valid during method invocation.

答:
I have tried this quickly in a few minutes. I've never really tried to create a Mac OS X project, just Foundation and iPhone projects, but the idea seems the same. I created a Cocoa Application project "Stack1". I'm assuming you have done the same, because I don't think a Foundation project would support CGRect structs without manually importing CGGeometry.h or something... Anyway, I set up a new Objective C class called "Mapper" and implemented the initWithSourceFrame:mappedFrame: method you specified.

Mapper.h

```<code>#import <Cocoa/Cocoa.h>

@interface Mapper : NSObject {

}

-(id) initWithSourceFrame:(CGRect) sourceViewFrame mappedFrame:(CGRect) mappedViewFrame;

@end
</code>```

Mapper.m

```<code>#import "Mapper.h"

@implementation Mapper

-(id) initWithSourceFrame:(CGRect)sourceViewFrame  mappedFrame:(CGRect)mappedViewFrame {
    NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    self = [super init];
    NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    if (self) {
        NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    }
    return self;
}

@end
</code>```

I didn't alter Stack1AppDelegate.h.

Stack1AppDelegate.m

```<code>#import "Stack1AppDelegate.h"
#import "Mapper.h"

@implementation Stack1AppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    Mapper *mapper = [[Mapper alloc] initWithSourceFrame:CGRectMake(0, 0, 100, 100) mappedFrame:CGRectMake(0,0, 200,200)];

}

@end
</code>```

All my code did was allocate a Mapper instance as yours did and also use NSLog to print the width and height before [super init], after [super init], and also within the if (self) block.

Here's the log:

```<code>2011-01-23 16:09:07.167 Stack1[935:a0f] height: 200.000000, width: 200.000000
2011-01-23 16:09:07.170 Stack1[935:a0f] height: 200.000000, width: 200.000000
2011-01-23 16:09:07.170 Stack1[935:a0f] height: 200.000000, width: 200.000000
</code>```

I've also uploaded the whole project here:

http://ak.net84.net/files/temp/Stack1.zip

Body:
I have an initializer with two arguments:

-(id) initWithSourceFrame:(CGRect)sourceViewFrame  mappedFrame:(CGRect)mappedViewFrame {
  CGRect copy = mappedViewFrame;
  self = [super init];
  if (self) {
    // not able to access mappedViewFrame here..
    // copy is ok
    // doing initialization here...
  }
  return self;
}

It seemed to get wrong values from the second argument (mappedViewFrame). When looking for the error, I found out that mappedViewFrame gets destroyed (overridden in memory?).
This can be easily observed in the debugger:

Debugger Screenshot on flickr (I cannot post images yet)

The copy is still holding the original values, so using the copy was a workaround in this case. But of course I want to understand why this could happen.
The class is a direct subclass of NSObject, the whole project is a OS X native app.
The first argument was never destroyed. The problem does not relate to the values passed in. I switched them and it was always the second which was corrupted.

For example, I called the initializer with these example arguments (different from those in the debugger screenshots), and the error occured in the same way:

Mapper *mapper = [[Mapper alloc] initWithSourceFrame:CGRectMake(0, 0, 100, 100) mappedFrame:CGRectMake(0,0, 200,200)];

The method declaration:

-(id) initWithSourceFrame:(CGRect) sourceViewFrame mappedFrame:(CGRect) mappedViewFrame;

I'm somewhat new to Objective-C, so I am sorry if I missed something obvious. However, it looks strange that an argument does not keep valid during method invocation.

Body:
I have tried this quickly in a few minutes. I've never really tried to create a Mac OS X project, just Foundation and iPhone projects, but the idea seems the same. I created a Cocoa Application project "Stack1". I'm assuming you have done the same, because I don't think a Foundation project would support CGRect structs without manually importing CGGeometry.h or something... Anyway, I set up a new Objective C class called "Mapper" and implemented the initWithSourceFrame:mappedFrame: method you specified.

Mapper.h

#import <Cocoa/Cocoa.h>

@interface Mapper : NSObject {

}

-(id) initWithSourceFrame:(CGRect) sourceViewFrame mappedFrame:(CGRect) mappedViewFrame;

@end

Mapper.m

#import "Mapper.h"

@implementation Mapper

-(id) initWithSourceFrame:(CGRect)sourceViewFrame  mappedFrame:(CGRect)mappedViewFrame {
    NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    self = [super init];
    NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    if (self) {
        NSLog(@"height: %f, width: %f", mappedViewFrame.size.height, mappedViewFrame.size.width);
    }
    return self;
}

@end

I didn't alter Stack1AppDelegate.h.

Stack1AppDelegate.m

#import "Stack1AppDelegate.h"
#import "Mapper.h"

@implementation Stack1AppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    Mapper *mapper = [[Mapper alloc] initWithSourceFrame:CGRectMake(0, 0, 100, 100) mappedFrame:CGRectMake(0,0, 200,200)];

}

@end

All my code did was allocate a Mapper instance as yours did and also use NSLog to print the width and height before [super init], after [super init], and also within the if (self) block.

Here's the log:

2011-01-23 16:09:07.167 Stack1[935:a0f] height: 200.000000, width: 200.000000
2011-01-23 16:09:07.170 Stack1[935:a0f] height: 200.000000, width: 200.000000
2011-01-23 16:09:07.170 Stack1[935:a0f] height: 200.000000, width: 200.000000

I've also uploaded the whole project here:

http://ak.net84.net/files/temp/Stack1.zip


问:
Pandas substring search for filter
I have a use case where I need to validate each row in the df and mark if it is correct or not. Validation rules are in another df.

```<code>Main

    col1 col2
0    1    take me home
1    2    country roads
2    2    country roads take
3    4    me home

Rules

   col3 col4
0    1    take
1    2    home
2    3    country
3    4    om
4    2    take
</code>```

A row in main is marked as pass if the following condition matches for any row in rules

The condition for passing is:
    col1==col3 and col4 is substring of col2

```<code> Main

     col1 col2               result
 0    1    take me home       Pass
 1    2    country roads      Fail
 2    2    country roads take Pass
 3    4    me home            Pass
</code>```

My initial approach was to parse Rules df and create a function out of it dynamically and then run

```<code>    def action_function(row) -> object:
        if self.combined_filter()(row): #combined_filter() is the lambda equivalent of Rules df
            return success_action(row) #mark as pass
        return fail_action(row) #mark as fail

    Main["result"] = self.df.apply(action_function, axis=1)
</code>```

This turned out to be very slow as apply is not vectorized. The main df is about 3 million and Rules df is around 500 entries. Time taken is around 3 hour.

I am trying to use pandas merge for this. But substring match is not supported by the merge operation. I cannot split words by space or anything.

This will be used as part of a system. So I cannot hardcode anything. I need to read the df from excel every time system starts.
Can you please suggest an approach for this?

答:
Merge and then apply the condtion using np.where i.e </p>

```<code>temp = main.merge(rules,left_on='col1',right_on='col3')
temp['results'] = temp.apply(lambda x : np.where(x['col4'] in x['col2'],'Pass','Fail'),1)

no_dupe_df = temp.drop_duplicates('col2',keep='last').drop(['col3','col4'],1)

   col1                col2 results
0     1        take me home    Pass
2     2       country roads    Fail
4     2  country roads take    Pass
5     4             me home    Pass
</code>```

Title: Pandas substring search for filter

Body:
I have a use case where I need to validate each row in the df and mark if it is correct or not. Validation rules are in another df.

Main

    col1 col2
0    1    take me home
1    2    country roads
2    2    country roads take
3    4    me home

Rules

   col3 col4
0    1    take
1    2    home
2    3    country
3    4    om
4    2    take

A row in main is marked as pass if the following condition matches for any row in rules

The condition for passing is:
    col1==col3 and col4 is substring of col2

 Main

     col1 col2               result
 0    1    take me home       Pass
 1    2    country roads      Fail
 2    2    country roads take Pass
 3    4    me home            Pass

My initial approach was to parse Rules df and create a function out of it dynamically and then run

    def action_function(row) -> object:
        if self.combined_filter()(row): #combined_filter() is the lambda equivalent of Rules df
            return success_action(row) #mark as pass
        return fail_action(row) #mark as fail

    Main["result"] = self.df.apply(action_function, axis=1)

This turned out to be very slow as apply is not vectorized. The main df is about 3 million and Rules df is around 500 entries. Time taken is around 3 hour.

I am trying to use pandas merge for this. But substring match is not supported by the merge operation. I cannot split words by space or anything.

This will be used as part of a system. So I cannot hardcode anything. I need to read the df from excel every time system starts.
Can you please suggest an approach for this?

Body:
Merge and then apply the condtion using np.where i.e

temp = main.merge(rules,left_on='col1',right_on='col3')
temp['results'] = temp.apply(lambda x : np.where(x['col4'] in x['col2'],'Pass','Fail'),1)

no_dupe_df = temp.drop_duplicates('col2',keep='last').drop(['col3','col4'],1)

   col1                col2 results
0     1        take me home    Pass
2     2       country roads    Fail
4     2  country roads take    Pass
5     4             me home    Pass


问:
Microsoft Edge Native Messaging - Object expected
I am looking to create a web extension on the Edge browser with native messaging permissions.  It is super easy to get all this up and running with Chrome and Firefox, but apparently Microsoft does things their own way.  I downloaded the SecureInput project (https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos/tree/master/SecureInput), which almost seems like it works for everyone but for me.
Note: I have 0 experience with UWP.

I have followed the README on the project, but no luck.

I am able to Deploy the NativeMessagingHostInProcess project successfully.  Yes, I did make sure NativeMessagingHostInProcess is referenced in PasswordInputProtection\Program.cs and Extension\background.js.  I don't how this magically works, but after Deploy I do see the extension installed on my Edge browser.  I only need to enable it.
I have the secureinput.html in my localhost.  I have scattered logging messages throughout, and indeed I see the extension invoked when I visit http://localhost/secureinput.html.

Here is where it is failing... in background.js (connect method):

port = browser.runtime.connectNative("NativeMessagingHostInProcessService");

The statement above throws an "Object expected" error.

I am running Microsoft Edge 38.14393.1066.0, Microsoft EdgeHTML 14.14393.
I am running Visual Studio 2017.
The NativeMessagingHostInProcess project has Target version "Windows 10 Anniversary Edition (10.0; Build 14393) with Min version "Windows 10 (10.0; Build 10586).

Any help?

答:
Your deploying and debugging steps for the sample looks right. But this feature, native messaging to communicate with a companion Universal Windows Platform (UWP) app, is came with the Windows 10 Creators Update. Details please reference Native messaging in Microsoft Edge.

It looks like your windows 10 version is 14393. Please try to upgrade your device to Windows 10 Creators Update or higher to ensure the native messaging can work well. You could also check the target device family min version of the sample.


问:
ScrollBar always visible
I found great piece of code under the link here.

But in my case there is more to do.

My main VC is a UITableViewController. Controller can display two type of cells. One of them (MyCell) is having a subview of type UITextView (textView). The size of it's text is based on fontSize variable. I have two buttons that can lower or greater the fontSize, then both reloads the tableView. According to the link above and having in mind that UITextView is a subclass of UIScrollView, I made my piece of code I placed in didEndDisplayingCell:

```<code>-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.class == [ConduiteTableCellView class])
    {
        ConduiteTableCellView *conduiteCell = (ConduiteTableCellView *)cell;
        for (UIView *view in conduiteCell.textView.subviews)
        {
            if ([view isKindOfClass:[UIImageView class]])
            {
                if (view.alpha == 0 && view.frame.size.width < 10)
                {
                    view.alpha = 1;
                    break;
                }
            }
        }
        [conduiteCell.textView flashScrollIndicators];
    }
}
</code>```

But after the [self.tableView reloadData]; nothing happens. What am I doing wrong? Shall I place my code in some other method?

答:
Remove [conduiteCell.textView flashScrollIndicators]; and it will work.

```<code>-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (cell.class == [ConduiteTableCellView class])
  {
    ConduiteTableCellView *conduiteCell = (ConduiteTableCellView *)cell;
    for (UIView *view in conduiteCell.textView.subviews)
    {
      if ([view isKindOfClass:[UIImageView class]])
      {
        if (view.alpha == 0 && view.frame.size.width < 10)
        {
          view.alpha = 1;
          break;
        }
      }
    }
  }
}
</code>```

Title: ScrollBar always visible

Body:
I found great piece of code under the link here.

But in my case there is more to do.

My main VC is a UITableViewController. Controller can display two type of cells. One of them (MyCell) is having a subview of type UITextView (textView). The size of it's text is based on fontSize variable. I have two buttons that can lower or greater the fontSize, then both reloads the tableView. According to the link above and having in mind that UITextView is a subclass of UIScrollView, I made my piece of code I placed in didEndDisplayingCell:

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.class == [ConduiteTableCellView class])
    {
        ConduiteTableCellView *conduiteCell = (ConduiteTableCellView *)cell;
        for (UIView *view in conduiteCell.textView.subviews)
        {
            if ([view isKindOfClass:[UIImageView class]])
            {
                if (view.alpha == 0 && view.frame.size.width < 10)
                {
                    view.alpha = 1;
                    break;
                }
            }
        }
        [conduiteCell.textView flashScrollIndicators];
    }
}

But after the [self.tableView reloadData]; nothing happens. What am I doing wrong? Shall I place my code in some other method?

Body:
Remove [conduiteCell.textView flashScrollIndicators]; and it will work.

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (cell.class == [ConduiteTableCellView class])
  {
    ConduiteTableCellView *conduiteCell = (ConduiteTableCellView *)cell;
    for (UIView *view in conduiteCell.textView.subviews)
    {
      if ([view isKindOfClass:[UIImageView class]])
      {
        if (view.alpha == 0 && view.frame.size.width < 10)
        {
          view.alpha = 1;
          break;
        }
      }
    }
  }
}


问:
Vue.js gives weird object with Observer data
I'm receiving data with axios like this:

```<code>getData() {
    Axios.get(
        '/vue/get-data/',
        {
            params: {
                categories: this.category,
                activeFilters: this.activeFilters,
            }
        }
    ).then((response) => {
        this.banners = response.data;
        this.setBanner();
    })
},
</code>```

Then I get this:

When I try console.log(response.data.length) I get undefined. What could
be going on here very weird!

When I look in my vue-devtools banners has 2 objects:

So how can response.data.length be undefined?

答:
You are getting object not array that why .length is not working, and you are getting as undefined

```<code>this.banners = response.data[0];// for first
</code>```

Or loop over this, to get each object's data

```<code>for(var i in response.data){
     console.log(response.data[i]);
}
</code>```

If to get each value is not your purpose , and you want to just size check this answer

Body:
I'm receiving data with axios like this:

getData() {
    Axios.get(
        '/vue/get-data/',
        {
            params: {
                categories: this.category,
                activeFilters: this.activeFilters,
            }
        }
    ).then((response) => {
        this.banners = response.data;
        this.setBanner();
    })
},

Then I get this:

When I try console.log(response.data.length) I get undefined. What could
be going on here very weird!

When I look in my vue-devtools banners has 2 objects:

So how can response.data.length be undefined?

Body:
You are getting object not array that why .length is not working, and you are getting as undefined

this.banners = response.data[0];// for first

Or loop over this, to get each object's data

for(var i in response.data){
     console.log(response.data[i]);
}

If to get each value is not your purpose , and you want to just size check this answer


问:
How to find new technosphere providers and change its location in Brightway2
I want to create a new dataset on copper production in 'CH', based on the current dataset 'copper production in AU'. I tried to apply the following functions, but the last function returned "Cannot find this location". Can anyone help? Thanks in advance!</p>

```<code>data = w.extract_brightway2_databases(["ecoinvent 3.4 cutoff"])
copper_production = w.contains("name", "copper production")
musuizi=w.get_one(data,w.equals('location','AU'),copper_production)
musuizi2=w.transformations.geo.copy_to_new_location(musuizi, 'CH')
w.transformations.geo.relink_technosphere_exchanges(musuizi2,data,exclusive=True, drop_invalid=False, biggest_first=False, contained=False)
</code>```

答:
(Note: This question is actually about the wurst library, not Brightway)

It looks like there are some bugs due to sync problems between the ecoinvent database and the geographical definitions. For the time being, you can do the following:

```<code>import wurst as w
data = w.extract_brightway2_databases(["ecoinvent 3.4 cutoff"])

mapping = {
    "ASCC": "US-ASCC",
    "CSG": "CN-CSG",
    "FRCC": "US-FRCC",
    "HICC": "US-HICC",
    "IAI Area, Africa": 'IAI Area 1, Africa',
    "IAI Area, Asia, without China and GCC": 'IAI Area 4&5, without China',
    "IAI Area, Gulf Cooperation Council": 'IAI Area 8, Gulf',
    "IAI Area, North America, without Quebec": 'IAI Area 2, without Quebec',
    "IAI Area, Russia & RER w/o EU27 & EFTA": 'IAI Area, Europe outside EU & EFTA',
    "IAI Area, South America": 'IAI Area 3, South America',
    "MRO, US only": "US-MRO",
    "NPCC, US only": "US-NPCC",
    "RFC": "US-RFC",
    "SERC": "US-SERC",
    "SGCC": "CN-SGCC",
    "SPP": "US-SPP",
    "TRE": "US-TRE",
    "WECC, US only": "US-WECC",
}

def update_all_locations(data):
    for ds in data:
        ds['location'] = mapping.get(ds['location'], ds['location'])

update_all_locations(data)
copper_in_au = w.get_one(data, w.equals('location','AU'), w.contains("name", "copper production"))
copper_in_ch = w.transformations.geo.copy_to_new_location(copper_in_au, 'CH')
data.append(copper_in_ch)
w.transformations.geo.relink_technosphere_exchanges(
    copper_in_ch,
    data,
    contained=False
)
</code>```

Body:
I want to create a new dataset on copper production in 'CH', based on the current dataset 'copper production in AU'. I tried to apply the following functions, but the last function returned "Cannot find this location". Can anyone help? Thanks in advance!

data = w.extract_brightway2_databases(["ecoinvent 3.4 cutoff"])
copper_production = w.contains("name", "copper production")
musuizi=w.get_one(data,w.equals('location','AU'),copper_production)
musuizi2=w.transformations.geo.copy_to_new_location(musuizi, 'CH')
w.transformations.geo.relink_technosphere_exchanges(musuizi2,data,exclusive=True, drop_invalid=False, biggest_first=False, contained=False)

Body:
(Note: This question is actually about the wurst library, not Brightway)

It looks like there are some bugs due to sync problems between the ecoinvent database and the geographical definitions. For the time being, you can do the following:

import wurst as w
data = w.extract_brightway2_databases(["ecoinvent 3.4 cutoff"])

mapping = {
    "ASCC": "US-ASCC",
    "CSG": "CN-CSG",
    "FRCC": "US-FRCC",
    "HICC": "US-HICC",
    "IAI Area, Africa": 'IAI Area 1, Africa',
    "IAI Area, Asia, without China and GCC": 'IAI Area 4&5, without China',
    "IAI Area, Gulf Cooperation Council": 'IAI Area 8, Gulf',
    "IAI Area, North America, without Quebec": 'IAI Area 2, without Quebec',
    "IAI Area, Russia & RER w/o EU27 & EFTA": 'IAI Area, Europe outside EU & EFTA',
    "IAI Area, South America": 'IAI Area 3, South America',
    "MRO, US only": "US-MRO",
    "NPCC, US only": "US-NPCC",
    "RFC": "US-RFC",
    "SERC": "US-SERC",
    "SGCC": "CN-SGCC",
    "SPP": "US-SPP",
    "TRE": "US-TRE",
    "WECC, US only": "US-WECC",
}

def update_all_locations(data):
    for ds in data:
        ds['location'] = mapping.get(ds['location'], ds['location'])

update_all_locations(data)
copper_in_au = w.get_one(data, w.equals('location','AU'), w.contains("name", "copper production"))
copper_in_ch = w.transformations.geo.copy_to_new_location(copper_in_au, 'CH')
data.append(copper_in_ch)
w.transformations.geo.relink_technosphere_exchanges(
    copper_in_ch,
    data,
    contained=False
)


问:
repeating previous regex
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

```<code>x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))
</code>```

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

```<code>x = re.search("(\d+\s+){5}", line)
</code>```

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

答:
In your regular expression, there is only one group, since you have only one pair of parentheses.  This group will return the last match, as you found out yourself.

If you want to use regular expressions, and you know the number of integers in a line in advance, I would go for

```<code>x = re.search("\s+".join(["(\d+)"] * 5), line)
</code>```

in this case.

(Note that

```<code>x = re.search("(\d+\s+){5}", line)
</code>```

requires a space after the last number.)

But for the example you gave I'd actually use

```<code>line = "0 1 1 75 55"
int_list = map(int, line.split())
</code>```

Title: repeating previous regex

Body:
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

x = re.search("(\d+\s+){5}", line)

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

Body:
In your regular expression, there is only one group, since you have only one pair of parentheses.  This group will return the last match, as you found out yourself.

If you want to use regular expressions, and you know the number of integers in a line in advance, I would go for

x = re.search("\s+".join(["(\d+)"] * 5), line)

in this case.

(Note that

x = re.search("(\d+\s+){5}", line)

requires a space after the last number.)

But for the example you gave I'd actually use

line = "0 1 1 75 55"
int_list = map(int, line.split())


问:
Distutils partially ignoring CC environment variable when building python extension
I am trying to install the subprocess32 python module (https://github.com/google/python-subprocess32) and am having some issues with distutils. The module includes a C extension that has to be built, but when I run either pip install . or python setup.py install I get the following output:

```<code>...
creating build
creating build/temp.linux-x86_64-2.7
/non/existent/path/gcc -pthread -fPIC ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
unable to execute '/non/existent/path/gcc': No such file or directory
</code>```

Obviously distutils is using the wrong path to gcc for some reason. I then tried to manually specify the right path to gcc using export CC=/correct/path/to/gcc and I get this output:

```<code>building '_posixsubprocess' extension
creating build/temp.linux-x86_64-2.7
/correct/path/to/gcc -fPIC -fno-strict-aliasing -g -O2 ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
/non/existent/path/gcc -pthread -shared ... build/temp.linux-x86_64-2.7/_posixsubprocess.o -o build/lib.linux-x86_64-2.7/_posixsubprocess.so
unable to execute '/non/existent/path/gcc': No such file or directory
</code>```

The original problematic command is now using the correct path, but it is still trying to use the incorrect location of gcc to build the shared library. Is there another environment variable I need to specify to correct this behaviour?

答:
I've experimented the exactly same problem with you. I spent some time digging into distutils source code and found the problem.

distutils will use the link config from when Python is built. In this case, the gcc used for building python is different with the gcc you're using to build extension.

Run this command too see the default link command:

```<code>python2 "from distutils.sysconfig import get_config_var; print(get_config_var('LDSHARED'))"
</code>```

You should found the incorrent gcc is in the start of the config, for example:

```<code>/non/existent/path/gcc -pthread -shared
</code>```

First solution

Set LDSHARED enviroment variable to overwrite it with the corrent gcc path:

```<code>export LDSHARED="/correct/path/to/gcc -pthread -shared"
</code>```

And then rebuild the extension, it should works.

Second solution (and possibly better)

The LDSHARED config is retrieved from lib/python2.7/_sysconfigdata.py file, which is generated at build time.

You can modify this file so there's no need to set environment variables.

Debug skills

Set DISTUTILS_DEBUG environment to activate debug mode, so you can see the traceback when compilation fails.

Body:
I am trying to install the subprocess32 python module (https://github.com/google/python-subprocess32) and am having some issues with distutils. The module includes a C extension that has to be built, but when I run either pip install . or python setup.py install I get the following output:

...
creating build
creating build/temp.linux-x86_64-2.7
/non/existent/path/gcc -pthread -fPIC ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
unable to execute '/non/existent/path/gcc': No such file or directory

Obviously distutils is using the wrong path to gcc for some reason. I then tried to manually specify the right path to gcc using export CC=/correct/path/to/gcc and I get this output:

building '_posixsubprocess' extension
creating build/temp.linux-x86_64-2.7
/correct/path/to/gcc -fPIC -fno-strict-aliasing -g -O2 ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
/non/existent/path/gcc -pthread -shared ... build/temp.linux-x86_64-2.7/_posixsubprocess.o -o build/lib.linux-x86_64-2.7/_posixsubprocess.so
unable to execute '/non/existent/path/gcc': No such file or directory

The original problematic command is now using the correct path, but it is still trying to use the incorrect location of gcc to build the shared library. Is there another environment variable I need to specify to correct this behaviour?

Body:
I've experimented the exactly same problem with you. I spent some time digging into distutils source code and found the problem.

distutils will use the link config from when Python is built. In this case, the gcc used for building python is different with the gcc you're using to build extension.

Run this command too see the default link command:

python2 "from distutils.sysconfig import get_config_var; print(get_config_var('LDSHARED'))"

You should found the incorrent gcc is in the start of the config, for example:

/non/existent/path/gcc -pthread -shared

First solution

Set LDSHARED enviroment variable to overwrite it with the corrent gcc path:

export LDSHARED="/correct/path/to/gcc -pthread -shared"

And then rebuild the extension, it should works.

Second solution (and possibly better)

The LDSHARED config is retrieved from lib/python2.7/_sysconfigdata.py file, which is generated at build time.

You can modify this file so there's no need to set environment variables.

Debug skills

Set DISTUTILS_DEBUG environment to activate debug mode, so you can see the traceback when compilation fails.


问:
Is there a builtin identity function in python?
I'd like to point to a function that does nothing:

```<code>def identity(*args)
    return args
</code>```

my use case is something like this

```<code>try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity
</code>```

Of course, I could use the identity defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently, map and filter use None for the identity, but this is specific to their implementations.

```<code>>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
</code>```

答:
Stub of a single-argument function

gettext.gettext (the OP's example use case) accepts a single argument, message. If one needs a stub for it, there's no reason to return [message] instead of message (def identity(*args): return args). Thus both

```<code>_ = lambda message: message

def _(message):
    return message
</code>```

fit perfectly.

...but a built-in would certainly run faster (and avoid bugs introduced by my own).

Bugs in such a trivial case are barely relevant. For an argument of predefined type, say str, we can use str() itself as an identity function (because of string interning it even retains object identity, see id note below) and compare its performance with the lambda solution:

```<code>$ python3 -m timeit -s "f = lambda m: m" "f('foo')"
10000000 loops, best of 3: 0.0852 usec per loop
$ python3 -m timeit "str('foo')"
10000000 loops, best of 3: 0.107 usec per loop
</code>```

A micro-optimisation is possible. For example, the following Cython code:

test.pyx

```<code>cpdef str f(str message):
    return message
</code>```

Then:

```<code>$ pip install runcython3
$ makecython3 test.pyx
$ python3 -m timeit -s "from test import f" "f('foo')"
10000000 loops, best of 3: 0.0317 usec per loop
</code>```

Build-in object identity function

Don't confuse an identity function with the id built-in function which returns the 'identity' of an object (meaning a unique identifier for that particular object rather than that object's value, as compared with == operator), its memory address in CPython.

Body:
I'd like to point to a function that does nothing:

def identity(*args)
    return args

my use case is something like this

try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity

Of course, I could use the identity defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently, map and filter use None for the identity, but this is specific to their implementations.

>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Body:
Stub of a single-argument function

gettext.gettext (the OP's example use case) accepts a single argument, message. If one needs a stub for it, there's no reason to return [message] instead of message (def identity(*args): return args). Thus both

_ = lambda message: message

def _(message):
    return message

fit perfectly.

...but a built-in would certainly run faster (and avoid bugs introduced by my own).

Bugs in such a trivial case are barely relevant. For an argument of predefined type, say str, we can use str() itself as an identity function (because of string interning it even retains object identity, see id note below) and compare its performance with the lambda solution:

$ python3 -m timeit -s "f = lambda m: m" "f('foo')"
10000000 loops, best of 3: 0.0852 usec per loop
$ python3 -m timeit "str('foo')"
10000000 loops, best of 3: 0.107 usec per loop

A micro-optimisation is possible. For example, the following Cython code:

test.pyx

cpdef str f(str message):
    return message

Then:

$ pip install runcython3
$ makecython3 test.pyx
$ python3 -m timeit -s "from test import f" "f('foo')"
10000000 loops, best of 3: 0.0317 usec per loop

Build-in object identity function

Don't confuse an identity function with the id built-in function which returns the 'identity' of an object (meaning a unique identifier for that particular object rather than that object's value, as compared with == operator), its memory address in CPython.