问:
parsing an array of elements in xml using java
Here, I'm using SAX method for parsing array. I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List

```<code><bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
</code>```

Any solution will help. Thanks in advance

答:
You can create a custom Handler that extends DefaultHandler and use it to parse your XML and generate the List<Book> for you.

The Handler will maintain a List<Book> and:

every time it will encounter the book start tag, it will create a new Book

every time it will encounter the book end tag, it will add this Book to the List.

In the end it will be holding the complete list of Books and you can access it via its getBooks() method

Assuming this Book class:

```<code>class Book {
    private String category;
    private String title;
    private String author;
    private String year;
    private String price;
    // GETTERS/SETTERS
}
</code>```

You can create a custom Handler like this:

```<code>class MyHandler extends DefaultHandler {

    private boolean title = false;
    private boolean author = false;
    private boolean year = false;
    private boolean price = false;

    // Holds the list of Books
    private List<Book> books = new ArrayList<>();
    // Holds the Book we are currently parsing
    private Book book;

    public void startElement(String uri, String localName,String qName, Attributes attributes) {

        switch (qName) {
            // Create a new Book when finding the start book tag
            case "book": {
                book = new Book();
                book.setCategory(attributes.getValue("category"));
            }
            case "title": title = true;
            case "author": author = true;
            case "year": year = true;
            case "price": price = true;
        }
    }

    public void endElement(String uri, String localName, String qName) {
        // Add the current Book to the list when finding the end book tag
        if("book".equals(qName)) {
            books.add(book);
        }
    }

    public void characters(char[] ch, int start, int length) {
        String value = new String(ch, start, length);

        if (title) {
            book.setTitle(value);
            title = false;
        } else if (author) {
            book.setAuthor(value);
            author = false;
        } else if (year) {
            book.setYear(value);
            year = false;
        } else if (price) {
            book.setPrice(value);
            price = false;
        }
    }

    public List<Book> getBooks() {
        return books;
    }
}
</code>```

Then you parse using this custom Handler and retrieve the list of Books

```<code>SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

MyHandler myHandler = new MyHandler();
saxParser.parse("/path/to/file.xml", myHandler);
List<Book> books = myHandler.getBooks();
</code>```

Body:
Here, I'm using SAX method for parsing array. I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List

<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Any solution will help. Thanks in advance

Body:
You can create a custom Handler that extends DefaultHandler and use it to parse your XML and generate the List<Book> for you.

The Handler will maintain a List<Book> and:

every time it will encounter the book start tag, it will create a new Book

every time it will encounter the book end tag, it will add this Book to the List.

In the end it will be holding the complete list of Books and you can access it via its getBooks() method

Assuming this Book class:

class Book {
    private String category;
    private String title;
    private String author;
    private String year;
    private String price;
    // GETTERS/SETTERS
}

You can create a custom Handler like this:

class MyHandler extends DefaultHandler {

    private boolean title = false;
    private boolean author = false;
    private boolean year = false;
    private boolean price = false;

    // Holds the list of Books
    private List<Book> books = new ArrayList<>();
    // Holds the Book we are currently parsing
    private Book book;

    public void startElement(String uri, String localName,String qName, Attributes attributes) {

        switch (qName) {
            // Create a new Book when finding the start book tag
            case "book": {
                book = new Book();
                book.setCategory(attributes.getValue("category"));
            }
            case "title": title = true;
            case "author": author = true;
            case "year": year = true;
            case "price": price = true;
        }
    }

    public void endElement(String uri, String localName, String qName) {
        // Add the current Book to the list when finding the end book tag
        if("book".equals(qName)) {
            books.add(book);
        }
    }

    public void characters(char[] ch, int start, int length) {
        String value = new String(ch, start, length);

        if (title) {
            book.setTitle(value);
            title = false;
        } else if (author) {
            book.setAuthor(value);
            author = false;
        } else if (year) {
            book.setYear(value);
            year = false;
        } else if (price) {
            book.setPrice(value);
            price = false;
        }
    }

    public List<Book> getBooks() {
        return books;
    }
}

Then you parse using this custom Handler and retrieve the list of Books

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

MyHandler myHandler = new MyHandler();
saxParser.parse("/path/to/file.xml", myHandler);
List<Book> books = myHandler.getBooks();


来源: stackexchange

问:
Admob sending adult content, how to disable this?
I have just completed my first App and I am using Admob to publish adverts. But before I upload to the google play store I have been testing on my device. Everything was going ok until later this evening, when Admob starting advertising adult content.

There any way to disable this, I don't want to get my account disabled if someone downloads my Apps and takes offence at my App. And for some reason it also seems to display the same adult content.

Under App Settings I have these enabled:

"Use keyword-targeted ads and Google certified ad networks (GCANs) to improve fill rate"

"Allow the use of +1 related features and social annotations in ads"

Under Ad filter I have this setting:

"Age Appropriate Ads" which is turned off

I'm using Android Studio 0.4.6.

答:
You need turn off ads from sensitive categories:
https://apps.admob.com/v2/pubcontrols/sensitive-categories</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to loop over query data and insert in structure?
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

```<code>    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019
</code>```

This data should be organized to look like this:

```<code>1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019
</code>```

I tried to get desired data format with this function:

```<code>function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}
</code>```

Here is how my result looks:

```<code>1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61
</code>```

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

答:
@espresso_coffee, Here I've go through your problem. I hope you need to create a structure with key as row count and each key value should be in a structure format. Here I've provide some sample code for with my query. I hope it's useful to you.

```<code><cfquery name="readStudent" datasource="student">
    select * from  user
</cfquery>
</code>```

In my user table having 6 records with firstname, lastName & id. Here I've loop over the query and convert it in to structure key values. I've used script syntax because your code having script style. :)

```<code><cfscript>
    myStr = {};
    for (row in readStudent) {
        structInsert(myStr, #readStudent.currentrow#, row);
    }
    writeDump(myStr);
</cfscript>
</code>```

Here I've create my first structure name as myStr, and loop over query data and insert a structure value for key with current row that is readStudent.currentRow and value is in row . The row having firstname,lastname & id as structure key & it's value.

FYR : I've attached my sample query and converted to  structure value. Correct me if I'm wrong understood your problem

I hope it's helpful to you. Thanks.

Body:
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019

This data should be organized to look like this:

1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019

I tried to get desired data format with this function:

function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}

Here is how my result looks:

1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

Body:
@espresso_coffee, Here I've go through your problem. I hope you need to create a structure with key as row count and each key value should be in a structure format. Here I've provide some sample code for with my query. I hope it's useful to you.

<cfquery name="readStudent" datasource="student">
    select * from  user
</cfquery>

In my user table having 6 records with firstname, lastName & id. Here I've loop over the query and convert it in to structure key values. I've used script syntax because your code having script style. :)

<cfscript>
    myStr = {};
    for (row in readStudent) {
        structInsert(myStr, #readStudent.currentrow#, row);
    }
    writeDump(myStr);
</cfscript>

Here I've create my first structure name as myStr, and loop over query data and insert a structure value for key with current row that is readStudent.currentRow and value is in row . The row having firstname,lastname & id as structure key & it's value.

FYR : I've attached my sample query and converted to  structure value. Correct me if I'm wrong understood your problem

I hope it's helpful to you. Thanks.


问:
can I get parameters from URL in pentaho?
Can I use a parameter from Carte's URL in a Job? Something like this:

http://localhost:8080/kettle/startJob/?name=myjob&xml=Y&testvar=filename.txt

I want to do this because I have a job to transform an input file but I want to change that filename dynamically, and creating a new XML file for each file is a bit nonsense.

I've tried many things and I couldn't find a solution :-(

答: All named parameters must be declared in the parameters tab of said JOB and KTR to be executed and receive the information passed from the URL parameters.</p>


问:
How can I tell which login is being used to connect to a SQL Server linked server?
I can get information about a linked server using the sp_linked_servers stored procedure.  What the SP does not give me, however, is login info entered via sp_addlinkedsrvlogin.

How can I tell which login is being used to connect to the linked server?

答:
```<code>SELECT s.name, s.product, s.data_source, ll.remote_name
    FROM sys.servers s
        INNER JOIN sys.linked_logins ll
            ON s.server_id = ll.server_id
    WHERE ll.remote_name IS NOT NULL
</code>```


问:
RecyclerView does not update after add data
I'm migrating from ListView to RecyclerView, but after entering some data in SQLite, my list is not updated using notifyDataSetChanged (); so I always have to call the setAdapter () method;

I have simplified my code to post here. can anyone help me fix the notifyDataSetChanged (); to work in my code please?

RecyclerViewAdapter

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {

private List<Model> model;
private Context context;

public RecyclerViewAdapter(Context context, List<Model> model) {
    this.context = context;
    this.model = new ArrayList<>(model);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout, parent, false);
    return new ViewHolder(context, view, model);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Model model = model.get(position);
    holder.bind(model);
}

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

ViewHolder

```<code>public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

private List<Model> model = new ArrayList<>();
private Context context;

private TextView textViewGroup;
private TextView textViewName;

public ViewHolder(Context context, View itemView, List<Model> model) {
    super(itemView);

    this.model = model;
    this.context = context;

    itemView.setOnClickListener(this);

    textViewGroup = (TextView) itemView.findViewById(R.id.textViewGroup);
    textViewName = (TextView) itemView.findViewById(R.id.textViewName);

}

public void bind(Model model) {
    textViewGroup.setText(model.getGroup());
    textViewName.setText(model.getName());
    }
}

@Override
public void onClick(View view) {
    Model model = this.model.get(getAdapterPosition());
    Intent intent = new Intent(this.context, ShowGroup.class);
    intent.putExtra("DATA", model);
    intent.putExtra("POSITION", getAdapterPosition());
    ((Activity) this.context).startActivityForResult(intent, 7);

    Log.i(">>", "_IDHOLDER: " + model.getId());
    Log.i(">>", "_POSITION: " + getAdapterPosition());
    Log.i(">>", ".");
} }
</code>```

Model

```<code>public class Model implements Serializable {

public static final String TABLE = "GROUP_NAME";
public static final String ID = "_ID";
public static final String GROUP = "GROUP";
public static final String NAME = "NAME";

private long id;
private String group;
private String name;

public Model() {
    setId(0);
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getGroup() {
    return group;
}

public void setGroup(String group) {
    this.group = group;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
} }
</code>```

Repository

```<code>public class Repository {

private SQLiteDatabase db;

public Repository(SQLiteDatabase db) {
    this.db = db;
}

private ContentValues fillModelValues(Model model) {
    ContentValues values = new ContentValues();
    values.put(Model.GROUP, model.getGroup());
    values.put(Model.NAME, model.getName());

    return values;
}

public void insert(Model model) {
    ContentValues values = fillModelValues(model);
    db.insertOrThrow(Model.TABLE, null, values);
}

public List<Model> consDataBase(Context context) {

    List<Model> listModel = new ArrayList<>();

    Cursor cursor = db.query(Model.TABLE, null, null, null, null, null, null);

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();

        do {
            Model model = new Model();
            model.setId(cursor.getLong(cursor.getColumnIndex(Model.ID)));
            model.setGroup(cursor.getString(cursor.getColumnIndex(Model.GROUP)));
            model.setName(cursor.getString(cursor.getColumnIndex(Model.NAME)));

            listModel.add(model);

        } while (cursor.moveToNext());
    }

    cursor.close();

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

MainActivity

```<code>public class MainActivity extends AppCompatActivity {

private List<Model> listModel;
private LinearLayoutManager layoutManager;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;

private FloatingActionButton fab;

private DataBase dataBase;
private SQLiteDatabase db;
private Repository repository;

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

    layoutManager = new LinearLayoutManager(this);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(layoutManager);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(new Intent(MainActivity.this, AddGroup.class), 4);
        }
    });

    try {
        dataBase = new DataBase(this);
        db = dataBase.getWritableDatabase();
        repository = new Repository(db);

        listModel = repository.consDataBase(context);
        recyclerViewAdapter = new RecyclerViewAdapter(context, listModel);
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerView.setHasFixedSize(true);

    } catch (SQLException e) {

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (db != null) {
        db.close();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 4) {

        listModel = repository.consDataBase(context);
        recyclerViewAdapter = new RecyclerViewAdapter(context, listModel);
        recyclerView.setAdapter(recyclerViewAdapter);
    }
} }
</code>```

AddGroup

```<code>public class AddGroup extends AppCompatActivity {

private EditText editTextGroup;
private EditText editTextName;

private DataBase dataBase;
private SQLiteDatabase db;
private Repository repository;
private Model model;

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

    editTextGroup = (EditText) findViewById(R.id.editTextGroup);
    editTextName = (EditText) findViewById(R.id.editTextName);

    try {
        dataBase = new DataBase(this);
        db = dataBase.getWritableDatabase();
        repository = new Repository(db);
        model = new Model();

    } catch (SQLException e) {

    }
}

private void saveModel() {
    try {
        model.setGroup(editTextGroup.getText().toString().trim());
        model.setName(editTextName.getText().toString().trim());
        if (model.getId() == 0) {
            repository.insert(model);
        }

    } catch (Exception e) {

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (db != null) {
        db.close();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_add_group, menu);

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_save) {
        saveModel();

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

Body:
I'm migrating from ListView to RecyclerView, but after entering some data in SQLite, my list is not updated using notifyDataSetChanged (); so I always have to call the setAdapter () method;

I have simplified my code to post here. can anyone help me fix the notifyDataSetChanged (); to work in my code please?

RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {

private List<Model> model;
private Context context;

public RecyclerViewAdapter(Context context, List<Model> model) {
    this.context = context;
    this.model = new ArrayList<>(model);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout, parent, false);
    return new ViewHolder(context, view, model);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Model model = model.get(position);
    holder.bind(model);
}

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

ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

private List<Model> model = new ArrayList<>();
private Context context;

private TextView textViewGroup;
private TextView textViewName;

public ViewHolder(Context context, View itemView, List<Model> model) {
    super(itemView);

    this.model = model;
    this.context = context;

    itemView.setOnClickListener(this);

    textViewGroup = (TextView) itemView.findViewById(R.id.textViewGroup);
    textViewName = (TextView) itemView.findViewById(R.id.textViewName);

}

public void bind(Model model) {
    textViewGroup.setText(model.getGroup());
    textViewName.setText(model.getName());
    }
}

@Override
public void onClick(View view) {
    Model model = this.model.get(getAdapterPosition());
    Intent intent = new Intent(this.context, ShowGroup.class);
    intent.putExtra("DATA", model);
    intent.putExtra("POSITION", getAdapterPosition());
    ((Activity) this.context).startActivityForResult(intent, 7);

    Log.i(">>", "_IDHOLDER: " + model.getId());
    Log.i(">>", "_POSITION: " + getAdapterPosition());
    Log.i(">>", ".");
} }

Model

public class Model implements Serializable {

public static final String TABLE = "GROUP_NAME";
public static final String ID = "_ID";
public static final String GROUP = "GROUP";
public static final String NAME = "NAME";

private long id;
private String group;
private String name;

public Model() {
    setId(0);
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getGroup() {
    return group;
}

public void setGroup(String group) {
    this.group = group;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
} }

Repository

public class Repository {

private SQLiteDatabase db;

public Repository(SQLiteDatabase db) {
    this.db = db;
}

private ContentValues fillModelValues(Model model) {
    ContentValues values = new ContentValues();
    values.put(Model.GROUP, model.getGroup());
    values.put(Model.NAME, model.getName());

    return values;
}

public void insert(Model model) {
    ContentValues values = fillModelValues(model);
    db.insertOrThrow(Model.TABLE, null, values);
}

public List<Model> consDataBase(Context context) {

    List<Model> listModel = new ArrayList<>();

    Cursor cursor = db.query(Model.TABLE, null, null, null, null, null, null);

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();

        do {
            Model model = new Model();
            model.setId(cursor.getLong(cursor.getColumnIndex(Model.ID)));
            model.setGroup(cursor.getString(cursor.getColumnIndex(Model.GROUP)));
            model.setName(cursor.getString(cursor.getColumnIndex(Model.NAME)));

            listModel.add(model);

        } while (cursor.moveToNext());
    }

    cursor.close();

    return listModel;
} }

MainActivity

public class MainActivity extends AppCompatActivity {

private List<Model> listModel;
private LinearLayoutManager layoutManager;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;

private FloatingActionButton fab;

private DataBase dataBase;
private SQLiteDatabase db;
private Repository repository;

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

    layoutManager = new LinearLayoutManager(this);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(layoutManager);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(new Intent(MainActivity.this, AddGroup.class), 4);
        }
    });

    try {
        dataBase = new DataBase(this);
        db = dataBase.getWritableDatabase();
        repository = new Repository(db);

        listModel = repository.consDataBase(context);
        recyclerViewAdapter = new RecyclerViewAdapter(context, listModel);
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerView.setHasFixedSize(true);

    } catch (SQLException e) {

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (db != null) {
        db.close();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 4) {

        listModel = repository.consDataBase(context);
        recyclerViewAdapter = new RecyclerViewAdapter(context, listModel);
        recyclerView.setAdapter(recyclerViewAdapter);
    }
} }

AddGroup

public class AddGroup extends AppCompatActivity {

private EditText editTextGroup;
private EditText editTextName;

private DataBase dataBase;
private SQLiteDatabase db;
private Repository repository;
private Model model;

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

    editTextGroup = (EditText) findViewById(R.id.editTextGroup);
    editTextName = (EditText) findViewById(R.id.editTextName);

    try {
        dataBase = new DataBase(this);
        db = dataBase.getWritableDatabase();
        repository = new Repository(db);
        model = new Model();

    } catch (SQLException e) {

    }
}

private void saveModel() {
    try {
        model.setGroup(editTextGroup.getText().toString().trim());
        model.setName(editTextName.getText().toString().trim());
        if (model.getId() == 0) {
            repository.insert(model);
        }

    } catch (Exception e) {

    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (db != null) {
        db.close();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_add_group, menu);

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_save) {
        saveModel();

    }
    return super.onOptionsItemSelected(item);
} }

Body:
Simply put:
RecyclerViewAdapter.notyfyDataSetChanged();


问:
Stripe STPCustomerDeserializer unable to parse customer Swift
Customer JSON returned from Stripe API unable to be parsed by using                                 STPCustomerDeserializer(jsonResponse: data), returns nil when locating the "id" field. logging the data shows that the id is not nil.

The customer object is in the exact same format as what the Stripe API returns. Error message 'The response from Stripe failed to get parsed into valid JSON."

Debugging the deserialiser shows that it is failing here:

```<code>// required fields
NSString *stripeId = [dict stp_stringForKey:@"id"];
if (!stripeId) {
    return nil; <<< returning here
}
</code>```

at >>>

```<code>- (nullable NSString *)stp_stringForKey:(NSString *)key {
    id value = self[key];
    if (value && [value isKindOfClass:[NSString class]]) {
        return value;
    }
    return nil; << returning here
}
</code>```

I have tried passing in the customer data in different formats to no avail.

I saw someone asks a similar question here The data could not be read because it isn't in the correct format JSON & SWIFT 3

```<code>["customer": {
    "account_balance" = 0;
    address = "<null>";
    balance = 0;
    created = ***;
    currency = "<null>";
    "default_source" = “***”;
    delinquent = 0;
    description = "<null>";
    discount = "<null>";
    email = “***”;
    id = "cus_***";
    "invoice_prefix" = ***;
    "invoice_settings" =     {
        "custom_fields" = "<null>";
        "default_payment_method" = "<null>";
        footer = "<null>";
    };
    livemode = 1;
    metadata =     {
    };
    name = "<null>";
    object = customer;
    phone = "<null>";
    "preferred_locales" =     (
    );
    shipping = "<null>";
    sources =     {
        data =         (
                        {
                "address_city" = "<null>";
                "address_country" = GB;
                "address_line1" = "<null>";
                "address_line1_check" = "<null>";
                "address_line2" = "<null>";
                "address_state" = "<null>";
                "address_zip" = "<null>";
                "address_zip_check" = "<null>";
                brand = Visa;
                country = GB;
                customer = "cus_***";
                "cvc_check" = pass;
                "dynamic_last4" = "<null>";
                "exp_month" = ***;
                "exp_year" = ***;
                fingerprint = ***;
                funding = debit;
                id = "card_***";
                last4 = ***;
                metadata =                 {
                };
                name = "<null>";
                object = card;
                "tokenization_method" = "<null>";
            }
        );
        "has_more" = 0;
        object = list;
        "total_count" = 1;
        url = "/v1/customers/cus_***/sources";
    };
    subscriptions =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/subscriptions";
    };
    "tax_exempt" = none;
    "tax_ids" =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/tax_ids";
    };
    "tax_info" = "<null>";
    "tax_info_verification" = "<null>";
}]
</code>```

答:
I have solved a similar issue, error in this case seems to be that a key is not found. Try making the variables in your model optionals (?).If it doesn't have a value it will return nil or the value associated.

Are you sure the id which you mentioned is NSString, try with NSInteger or other DataTypes.

Body:
Customer JSON returned from Stripe API unable to be parsed by using                                 STPCustomerDeserializer(jsonResponse: data), returns nil when locating the "id" field. logging the data shows that the id is not nil.

The customer object is in the exact same format as what the Stripe API returns. Error message 'The response from Stripe failed to get parsed into valid JSON."

Debugging the deserialiser shows that it is failing here:

// required fields
NSString *stripeId = [dict stp_stringForKey:@"id"];
if (!stripeId) {
    return nil; <<< returning here
}

at >>>

- (nullable NSString *)stp_stringForKey:(NSString *)key {
    id value = self[key];
    if (value && [value isKindOfClass:[NSString class]]) {
        return value;
    }
    return nil; << returning here
}

I have tried passing in the customer data in different formats to no avail.

I saw someone asks a similar question here The data could not be read because it isn't in the correct format JSON & SWIFT 3

["customer": {
    "account_balance" = 0;
    address = "<null>";
    balance = 0;
    created = ***;
    currency = "<null>";
    "default_source" = “***”;
    delinquent = 0;
    description = "<null>";
    discount = "<null>";
    email = “***”;
    id = "cus_***";
    "invoice_prefix" = ***;
    "invoice_settings" =     {
        "custom_fields" = "<null>";
        "default_payment_method" = "<null>";
        footer = "<null>";
    };
    livemode = 1;
    metadata =     {
    };
    name = "<null>";
    object = customer;
    phone = "<null>";
    "preferred_locales" =     (
    );
    shipping = "<null>";
    sources =     {
        data =         (
                        {
                "address_city" = "<null>";
                "address_country" = GB;
                "address_line1" = "<null>";
                "address_line1_check" = "<null>";
                "address_line2" = "<null>";
                "address_state" = "<null>";
                "address_zip" = "<null>";
                "address_zip_check" = "<null>";
                brand = Visa;
                country = GB;
                customer = "cus_***";
                "cvc_check" = pass;
                "dynamic_last4" = "<null>";
                "exp_month" = ***;
                "exp_year" = ***;
                fingerprint = ***;
                funding = debit;
                id = "card_***";
                last4 = ***;
                metadata =                 {
                };
                name = "<null>";
                object = card;
                "tokenization_method" = "<null>";
            }
        );
        "has_more" = 0;
        object = list;
        "total_count" = 1;
        url = "/v1/customers/cus_***/sources";
    };
    subscriptions =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/subscriptions";
    };
    "tax_exempt" = none;
    "tax_ids" =     {
        data =         (
        );
        "has_more" = 0;
        object = list;
        "total_count" = 0;
        url = "/v1/customers/cus_***/tax_ids";
    };
    "tax_info" = "<null>";
    "tax_info_verification" = "<null>";
}]


问:
Not able to access the Word Document on my system using the UWP application
I am trying to edit a existing Word document using the UWP app (Universal Windows). But for some reason I am getting "File does not exist" error.

I have tried using the below code to access the word document:

```<code>using(WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\Users\\Public\\Desktop\\Doc1.docx", true))
{

}
</code>```

System.IO.FileNotFoundException: 'Could not find document'

答:
Based on further clarification in the comments section, please see the following instructions.

Add your .DOCX file to the Assets folder within your project and set the build action to "Content".

In order to write any changes to the file, we'll need to copy it to the packages LocalFolder and then access it from there.

```<code>var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/doc1.docx"));
if (file != null)
{
    //Copy .docx file to LocalFolder so we can write to it
    await file.CopyAsync(ApplicationData.Current.LocalFolder);
    String newFile = ApplicationData.Current.LocalFolder.Path + "/doc1.docx";

    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(newFile, true))
    {
            //Your code here
    }
}
</code>```

You'll need to expand on this somewhat to make sure the file is only copied to the LocalFolder once etc, but you get the basic idea.

Body:
I am trying to edit a existing Word document using the UWP app (Universal Windows). But for some reason I am getting "File does not exist" error.

I have tried using the below code to access the word document:

using(WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\Users\\Public\\Desktop\\Doc1.docx", true))
{

}

System.IO.FileNotFoundException: 'Could not find document'

Body:
Based on further clarification in the comments section, please see the following instructions.

Add your .DOCX file to the Assets folder within your project and set the build action to "Content".

In order to write any changes to the file, we'll need to copy it to the packages LocalFolder and then access it from there.

var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/doc1.docx"));
if (file != null)
{
    //Copy .docx file to LocalFolder so we can write to it
    await file.CopyAsync(ApplicationData.Current.LocalFolder);
    String newFile = ApplicationData.Current.LocalFolder.Path + "/doc1.docx";

    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(newFile, true))
    {
            //Your code here
    }
}

You'll need to expand on this somewhat to make sure the file is only copied to the LocalFolder once etc, but you get the basic idea.


问:
Changing wordpress old images path url doesn't reflect in my database using SQL
I have set a new cdn to serve images cdn.example.net . all my new uploads works fine with it , but my old images has path example.net .

I tried to use WP_CONTENT_URL to change images but it reflects in plugins,themes file to be broken . so I needed to upload all my plugins,themes files [That's not a good option as every new plugin I'll need to install , I will need to uploads it's files ] .

I tried using SQL UPDATE wp_posts SET post_content = REPLACE (post_content,'http://example.net/blog','http://cdn.example.com.net'); . it tells me that there is row matched but with no rows affected

答:
I managed to solve this issue by editing my wp-config.php

First one will change all [Images,Plugins,Themes] path to another url , your cdn as an example

```<code>define( 'WP_CONTENT_URL', 'your_cdn_website_url/wp-content' );
</code>```

I left this url so old one so plugins won't be broken

```<code>define( 'WP_PLUGIN_URL', 'your_website_url/wp-content/plugins' );
</code>```

Body:
I managed to solve this issue by editing my wp-config.php

First one will change all [Images,Plugins,Themes] path to another url , your cdn as an example

define( 'WP_CONTENT_URL', 'your_cdn_website_url/wp-content' );

I left this url so old one so plugins won't be broken

define( 'WP_PLUGIN_URL', 'your_website_url/wp-content/plugins' );


问:
how to make app full screen when a FragmentDialog is showing
i make my app Full Screen but when i create and show a Fragment Dialog it'll exit from Full Screen

i try two way but none working for me , check out code 1 and code 2

code 1 :
add
adding <item name="android:windowFullscreen">true</item>
to my style.xml
code 2 :
override onShow in Fragment Dialog

```<code>    @Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }
</code>```

nothing happened and my app exit from Full Screen again

答:
try this:</p>

```<code>@Override
public void onResume() {
    // Get existing layout params for the window
    ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
    // Assign window properties to fill the parent
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    params.height = WindowManager.LayoutParams.WRAP_CONTENT;
    getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    // Call super onResume after sizing
    super.onResume()

}
</code>```

Body:
i make my app Full Screen but when i create and show a Fragment Dialog it'll exit from Full Screen

i try two way but none working for me , check out code 1 and code 2

code 1 :
add
adding <item name="android:windowFullscreen">true</item>
to my style.xml
code 2 :
override onShow in Fragment Dialog

    @Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }

nothing happened and my app exit from Full Screen again

Body:
try this:

@Override
public void onResume() {
    // Get existing layout params for the window
    ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
    // Assign window properties to fill the parent
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    params.height = WindowManager.LayoutParams.WRAP_CONTENT;
    getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    // Call super onResume after sizing
    super.onResume()

}


问:
Directtostage error when playing published application in another computer
I have a Director application that has several modules, but one in particular decided to not work. That is the Video section of the program.

So basically when Im developing in Director, everything works perfectly, but when I try to run the application in another computer, I get the error "Property doesen't exists: directtostage", and comes from this like of code:

```<code>sprite("VideoShape").member.DirectToStage = true;
</code>```

The direct to stage property allows the video to have a better (and faster) rendering, thus allowing it to actually be playable. Without it, although works, makes is ultra slow and flikery, so having it is considered to be important.

I have checked and there is a video played at the time that line of code kicks in ,so i'm sure it "has" that property. Please keep in mind that the video plays perfectly when I am testing it out in director, when I publish it it still works fine, and only when I tried it on another computer has the error occurred.

The videos are in mp4 format (Quicktime) and the destination computer is running on Windows Vista.

Did any of you had this problem and knows of a possible fix?
Thanks.

答: Figured out that the pc in question did not have Quicktime installed. It was fixed afterwards. thanks for anyone that looked at the question :P</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a Director application that has several modules, but one in particular decided to not work. That is the Video section of the program.

So basically when Im developing in Director, everything works perfectly, but when I try to run the application in another computer, I get the error "Property doesen't exists: directtostage", and comes from this like of code:

sprite("VideoShape").member.DirectToStage = true;

The direct to stage property allows the video to have a better (and faster) rendering, thus allowing it to actually be playable. Without it, although works, makes is ultra slow and flikery, so having it is considered to be important.

I have checked and there is a video played at the time that line of code kicks in ,so i'm sure it "has" that property. Please keep in mind that the video plays perfectly when I am testing it out in director, when I publish it it still works fine, and only when I tried it on another computer has the error occurred.

The videos are in mp4 format (Quicktime) and the destination computer is running on Windows Vista.

Did any of you had this problem and knows of a possible fix?
Thanks.


问:
DHT Routing Table - Why use Buckets and not a map?
Closest question to this I think.

One obvious method of structuring a routing table is to simply maintain
a literal table. Map(XOR,Node)

Kademlia discusses the use of 'Buckets' which are organised by the most significant bit of the XOR. What is the actual purpose of 'buckets'?
Why mess around with 'longest prefix' when we can simply hold the 'actual' XOR as a key in a map?

Obviously the map could potentially be 2^160 large, but we could use some heuristics to limit the size of the map, rather than implementing some arbitrary bucket concept?
In any case (buckets or not) when searching for a nodeId close to the one we've been asked to find, we still have to iterate through all nodes in the table and do an XOR on each?

What am I missing?

答:
One obvious method of structuring a routing table is to simply maintain a literal table. Map(XOR,Node)

I read the key is xor but the xor of what? xor takes two argument:

```<code>distance = xor(hash, peerid)
</code>```

What is the actual purpose of 'buckets'?

k-bukcets allow to speed the following python code:

```<code>nsmallest(k, peers, key=functools.partial(operator.xor, hash))
</code>```

That is find the closest peers to a given hash.

Why mess around with 'longest prefix' when we can simply hold the 'actual' XOR as a key in a map?

Like  I said, above you can not store the xor value of every possible hash.

when searching for a nodeId close to the one we've been asked to find, we still have to iterate through all nodes in the table and do an XOR on each?

That the thing with k-buckets you don't need to iterate over the whole map to find the closest peers, because peers hash aka. peerid are organized by prefix and you know that the nearest peers share the same prefix as the given hash.

Why use Buckets and not a map?

You can use a map instead of k-bucket.

Body:
One obvious method of structuring a routing table is to simply maintain a literal table. Map(XOR,Node)

I read the key is xor but the xor of what? xor takes two argument:

distance = xor(hash, peerid)

What is the actual purpose of 'buckets'?

k-bukcets allow to speed the following python code:

nsmallest(k, peers, key=functools.partial(operator.xor, hash))

That is find the closest peers to a given hash.

Why mess around with 'longest prefix' when we can simply hold the 'actual' XOR as a key in a map?

Like  I said, above you can not store the xor value of every possible hash.

when searching for a nodeId close to the one we've been asked to find, we still have to iterate through all nodes in the table and do an XOR on each?

That the thing with k-buckets you don't need to iterate over the whole map to find the closest peers, because peers hash aka. peerid are organized by prefix and you know that the nearest peers share the same prefix as the given hash.

Why use Buckets and not a map?

You can use a map instead of k-bucket.


问:
Android - What is the name of this button?
When the soft keyboard is active, the back button is switched to this one

What is the name of the button? And what is the method that is called after pressing it?

答:
this one is simply a Hardware back button and on some devices its inside screen as you shown in the screenshot. Its called Back Button.

you can override onBackPressed method in your Activity which will be called when this button is pressed.

```<code> @override
 public void onBackPressed() {

      // .... Do your task here
      super.onBackPressed();
 }
</code>```

Body:
this one is simply a Hardware back button and on some devices its inside screen as you shown in the screenshot. Its called Back Button.

you can override onBackPressed method in your Activity which will be called when this button is pressed.

 @override
 public void onBackPressed() {

      // .... Do your task here
      super.onBackPressed();
 }


问:
create two differents variables from the same array
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working : </p>

```<code>    var letters = ['b', 'c', 'a']; // datas

    const lettersUnsorted = letters;        // i want the array like the var "letters"
    const letterSorted = letters.sort();    // i want the array like the var "letters" but sorted

    console.log(letterSorted);    // OK => returns: ["a", "b", "c"]
    console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
</code>```

答:
This is because the reference to the original letters array is maintained.

lettersUnsorted and letterSorted are both referencing to the letters variable. This is because letters is an array (which is technically an object), and in JavaScript, assigning another variable to it will result in assignment by reference (rather than assignment by value). Therefore, any operations or mutation to letters will result in both lettersUnsorted and letterSorted in having the same result as letters, due to the reference to letter.

You should create a shallow clone of the original letters array. This will allow you to safely carry out any mutation without affecting the other array.  We can achieve this using ES6's spread syntax.

const letters = ['b', 'c', 'a'];
const lettersClone = [...letters].sort();

console.log(letters);
console.log(lettersClone);```

Body:
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :

    var letters = ['b', 'c', 'a']; // datas

    const lettersUnsorted = letters;        // i want the array like the var "letters"
    const letterSorted = letters.sort();    // i want the array like the var "letters" but sorted

    console.log(letterSorted);    // OK => returns: ["a", "b", "c"]
    console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']


问:
Configuring 2 way SSL Client authentication on Apache web server
Wanted to get some advice on setting up simple 2 way apache SSL.

We have created a key file and csr request using openSSL. We have then submitted it to a CA and recieved a crt file back with the CA's crt file.

We have configured the apache http.conf file and added the following params after loading the mod_ssl module.

SSLEngine on

SSLCACertificateFile /local/fast/fcHome/deployment/apache01/conf/ssl.crt/ca.crt - the CA root cert recieved with the cert

SSLCertificateFile /local/fast/fcHome/deployment/apache01/conf/ssl.crt/server.crt -the crt file recieved from CA for the server

SSLCertificateKeyFile /local/fast/fcHome/deployment/apache01/conf/ssl.key/server.key - the keyfile used to generate the csr

SSLVerifyClient require

SSLVerifyDepth  10

We then have a client who is also using a certificate signed by the same CA attempting to connect to the https service. The client is getting SSL handshake errors when connecting.

The apache error logs show the following:

ssl_engine_kernel.c(1884): OpenSSL: Write: SSLv3 read client certificate B
ssl_engine_kernel.c(1903): OpenSSL: Exit: error in SSLv3 read client certificate B
ssl_engine_kernel.c(1903): OpenSSL: Exit: error in SSLv3 read client certificate B
SSL Library Error: 336105671 error:140890C7:SSL routines:SSL3_GET_CLIENT_CERTIFICATE:peer did not return a certificate No CAs known to server for verification?

I can't seem to figure out why this is. Is it possible that even though the client certificate is signed by Versign it is not matched to the server's CA.crt file?

Any help would be greatly appreciated

答:
The client must provide the client certificate in order to connect to server.

For example in python:

```<code>import requests

cert = (client_cert_file_path, client_key_file_path)

resp = requests.get(url, cert=cert, verify=False)
</code>```

Body:
The client must provide the client certificate in order to connect to server.

For example in python:

import requests

cert = (client_cert_file_path, client_key_file_path)

resp = requests.get(url, cert=cert, verify=False)


问:
Div with margin-left and width:100% overflowing on the right side
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

```<code><div style="width:100%;">
    <div style="margin-left:45px; width:100%;">
    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If I don't do the 100%, then the textbox is not 100% wide.

答:
Add some css either in the head or in a external document. asp:TextBox are rendered as input :

```<code>input {
     width:100%;
}
</code>```

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

```<code>.divClass input {
     width:100%;
}
</code>```

Body:
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox>

If I don't do the 100%, then the textbox is not 100% wide.

Body:
Add some css either in the head or in a external document. asp:TextBox are rendered as input :

input {
     width:100%;
}

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

.divClass input {
     width:100%;
}


问:
HANA OData create procedure - where is my new ID?
In my UI5 app, I have a list of items. I create a new item via a pop-up (enter some details and click OK). With my JSON data for the new entity, I then call 'create' on my OData model. The OData entity (as defined in my xsodata service) uses a stored proc to create db records, and uses a sequence to generate the next ID. Up to this point, all is well. The record is created, and my success callback is executed. However, what I now need is to have the new record's ID in my response payload, but I cannot manage to get it. Here is the JS code running the create, with the success/error callbacks:

```<code>// Update the model and add our new forecast
    this.getView().getModel().create('/Forecasts', oData, {
        success : jQuery.proxy(function(mResponse) {
            // nav to newly created Forecast
            this.getRouter().navTo("forecast", {
                forecastId: mResponse.ID, // EMPTY!
                tab: "data"
            }, false);
        }, this),
        error : jQuery.proxy(function(mResponse) {
            this.showErrorAlert("Problem creating new forecast");
        }, this)
    });
</code>```

mResponse.ID is always empty. I figure, it shouldn't be. ID is defined as a key in the entity forecast.

```<code>@Catalog.tableType: #ROW
entity forecast {
    key ID: IdType;
    NAME: NameType;
    CREATED: UTCDateTime;
    USER: UsernameType;
    EFFECTIVE: LocalDate;
    DAYS: Integer;
};
</code>```

And the xsodata service (schema and namespace references removed):

```<code>service {

    // Forecasts
    "<namesapce>.data::models.forecast" as "Forecasts"
    create using "<namesapce>.procedures::createForecast";
}
</code>```

Here is the stored proc, performing the insert:

```<code>PROCEDURE "<schema>"."<namespace>.procedures::createForecast" (
    IN intab "<schema>"."<namespace>.data::models.procedures.forecast",
    OUT outtab "<schema>"."<namespace>.data::models.procedures.errors"
)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
AS
-- DEFAULT SCHEMA <schema>
-- READS SQL DATA AS
BEGIN
    DECLARE lv_name string;
    DECLARE lv_days integer;

    SELECT NAME, DAYS INTO lv_name, lv_days FROM :intab;

    -- Now validate and insert
    IF :lv_name = '' THEN
        outtab = SELECT 500 AS http_status_code,
                    'Empty Forecast name' AS error_message,
                    'The Forecast name cannot be empty' AS detail FROM dummy;
    ELSEIF :lv_days = 0 THEN
        outtab = SELECT 500 AS http_status_code,
                    'Empty Forecast days' AS error_message,
                    'The Forecast days cannot be empty' AS detail FROM dummy;
    ELSE
        -- Perform the INSERT
        INSERT INTO "<namespace>.data::models.forecast"
        VALUES ("<namespace>.data::forecast".NEXTVAL,
                lv_name,
                CURRENT_TIMESTAMP,
                CURRENT_USER,
                CURRENT_DATE,
                lv_days);
    END IF;
END;
</code>```

How do I get that NEXTVAL value (now CURRVAL) into my response payload, so it can be accessed in the success calback of the model's create function? I've tried multiple out tables, but encounter constant problems. Surely there is an easy way to do this? The key of the inserted record is paramount. I don't want to create the ID on the client side, as it won't be accurate - I need it to be returned from the INSERT.

答:
The official documentation for SAP HANA OData Service Definitions (XS Advanced) states that it is not possible to use a sequence to create an entry in a table exposed by an OData service:

Without any support for IN/OUT table parameters in SQLScript, it is
  not possible to use a sequence to create an entry in a table exposed
  by an OData service. However, you can use XS JavaScript exits to
  update a table with a generated value.

Body:
In my UI5 app, I have a list of items. I create a new item via a pop-up (enter some details and click OK). With my JSON data for the new entity, I then call 'create' on my OData model. The OData entity (as defined in my xsodata service) uses a stored proc to create db records, and uses a sequence to generate the next ID. Up to this point, all is well. The record is created, and my success callback is executed. However, what I now need is to have the new record's ID in my response payload, but I cannot manage to get it. Here is the JS code running the create, with the success/error callbacks:

// Update the model and add our new forecast
    this.getView().getModel().create('/Forecasts', oData, {
        success : jQuery.proxy(function(mResponse) {
            // nav to newly created Forecast
            this.getRouter().navTo("forecast", {
                forecastId: mResponse.ID, // EMPTY!
                tab: "data"
            }, false);
        }, this),
        error : jQuery.proxy(function(mResponse) {
            this.showErrorAlert("Problem creating new forecast");
        }, this)
    });

mResponse.ID is always empty. I figure, it shouldn't be. ID is defined as a key in the entity forecast.

@Catalog.tableType: #ROW
entity forecast {
    key ID: IdType;
    NAME: NameType;
    CREATED: UTCDateTime;
    USER: UsernameType;
    EFFECTIVE: LocalDate;
    DAYS: Integer;
};

And the xsodata service (schema and namespace references removed):

service {

    // Forecasts
    "<namesapce>.data::models.forecast" as "Forecasts"
    create using "<namesapce>.procedures::createForecast";
}

Here is the stored proc, performing the insert:

PROCEDURE "<schema>"."<namespace>.procedures::createForecast" (
    IN intab "<schema>"."<namespace>.data::models.procedures.forecast",
    OUT outtab "<schema>"."<namespace>.data::models.procedures.errors"
)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
AS
-- DEFAULT SCHEMA <schema>
-- READS SQL DATA AS
BEGIN
    DECLARE lv_name string;
    DECLARE lv_days integer;

    SELECT NAME, DAYS INTO lv_name, lv_days FROM :intab;

    -- Now validate and insert
    IF :lv_name = '' THEN
        outtab = SELECT 500 AS http_status_code,
                    'Empty Forecast name' AS error_message,
                    'The Forecast name cannot be empty' AS detail FROM dummy;
    ELSEIF :lv_days = 0 THEN
        outtab = SELECT 500 AS http_status_code,
                    'Empty Forecast days' AS error_message,
                    'The Forecast days cannot be empty' AS detail FROM dummy;
    ELSE
        -- Perform the INSERT
        INSERT INTO "<namespace>.data::models.forecast"
        VALUES ("<namespace>.data::forecast".NEXTVAL,
                lv_name,
                CURRENT_TIMESTAMP,
                CURRENT_USER,
                CURRENT_DATE,
                lv_days);
    END IF;
END;

How do I get that NEXTVAL value (now CURRVAL) into my response payload, so it can be accessed in the success calback of the model's create function? I've tried multiple out tables, but encounter constant problems. Surely there is an easy way to do this? The key of the inserted record is paramount. I don't want to create the ID on the client side, as it won't be accurate - I need it to be returned from the INSERT.


问:
how to manage personal profile using android management api?
From my last posted question below,
Not getting any idea about the workflow of managing an android device from another device using an pre installed android in both devices
I am here today with new problem. I used android management api to create enterprise, enrolling a device with device policies(Used the sample provided in here a link. But what I am trying to achieve I am not getting it. I want the app to be able to disable all normal apps and camera when parent app blocks them in childs device from its own device using android management api. But what I am getting is that upon upload of enrollment of the policy using enrollment token I see a  separate work profile is being created in android device which is not my requirement in the app.
So if anyone out here can help me out in this one be very thankful.</p>

答:
TL DR:

To fully control a device you must enroll it in DEVICE OWNER mode.

I'll try to stick only to this question and address your other concerns answering the other.

You can enroll a device mainly in two modes WORK PROFILE and DEVICE OWNER, one is thought for enterprises that want to allow a BYOD model, the other for enterprises that provide company owned terminals and who wants exert full control on them.

From the docs: https://developers.google.com/android/management/provision-device

The work profile provisioning methods create a work profile on a device. A work profile is a self-contained space that separates work apps from personal apps (see employee-owned devices for more information). On devices with work profiles:

Android Device Policy is installed within the work profile.

devices.managementMode is set to PROFILE_OWNER.

Most policies and commands apply to the work profile only.

The fully managed and dedicated device provisioning methods provide enterprises with full management control over a device:

Android Device Policy is installed on the device's personal (primary) profile.

devices.managementMode is set to DEVICE_OWNER.

Policies and commands apply to the entire device.

Your idea probably needs DEVICE_OWNER mode but here there is the big problem, to enable them you must enroll a device that is factory reset!

So you need a much specific process to prepare a device before use, you cannot achieve a so strict control on a device just installing an app and control it from outside permissions or not. It's against the logic of a "personal device".


问:
Using Prophet package to forecast by groups and create plot
I am using Prophet package to forecasting in groups in a dataframe, and I want to create plots using the grouped dataframe.

I was following the answers in Using Prophet Package to Predict by Group in Dataframe in R. Are there easier ways to create the plots, compared to how I did it below?

```<code>library(dplyr)
library(prophet)

df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
                     a = rnorm(n = 25, mean = 100000, sd = 7500),
                     b = rnorm(n = 25, mean = 100000, sd = 7500),
                     c = rnorm(n = 25, mean = 100000, sd = 7500))
</code>```

The columns a, b and c are sales numbers for each product. And, I would like to run forecasting for all 3 products and the total sales in next 12 periods.

So, I tidy up the dataframe, then do group forecasting.

```<code>d1 <- df %>%
        gather(key = "prod", value = "y", a:c) %>%
        nest(-prod) %>%
        mutate(m = map(data, prophet)) %>%
        mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
        mutate(forecast = map2(m, future, predict)) %>%
        mutate(p = map2(m, forecast, plot))
</code>```

The output looks like this:

```<code># A tibble: 3 x 6
  dept  data              m             future                forecast               p
  <chr> <list>            <list>        <list>                <list>                 <list>
1 a     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
2 b     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
3 c     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
</code>```

Then, I create the plots manually, and rearrange them using grid.arrange

```<code>gridExtra::grid.arrange(d1$p[[1]], d1$p[[2]], d1$p[[3]]
</code>```

Are there any ways to do it quicker and automatically?

答:
I couldn't find a way to pipe the call to grid.arrange, but you can use do.call to avoid manually selecting plots.

do.call(gridExtra::grid.arrange, d1$p)

Example:

```<code>library(dplyr)
library(prophet)
library(tidyr)
library(purrr)

df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
                 a = rnorm(n = 25, mean = 100000, sd = 7500),
                 b = rnorm(n = 25, mean = 100000, sd = 7500),
                 c = rnorm(n = 25, mean = 100000, sd = 7500))

d1 <- df %>%
  gather(key = "prod", value = "y", a:c) %>%
  nest(-prod) %>%
  mutate(m = map(data, prophet)) %>%
  mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
  mutate(forecast = map2(m, future, predict)) %>%
  mutate(p = map2(m, forecast, plot))
</code>```

Body:
I am using Prophet package to forecasting in groups in a dataframe, and I want to create plots using the grouped dataframe.

I was following the answers in Using Prophet Package to Predict by Group in Dataframe in R. Are there easier ways to create the plots, compared to how I did it below?

library(dplyr)
library(prophet)

df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
                     a = rnorm(n = 25, mean = 100000, sd = 7500),
                     b = rnorm(n = 25, mean = 100000, sd = 7500),
                     c = rnorm(n = 25, mean = 100000, sd = 7500))

The columns a, b and c are sales numbers for each product. And, I would like to run forecasting for all 3 products and the total sales in next 12 periods.

So, I tidy up the dataframe, then do group forecasting.

d1 <- df %>%
        gather(key = "prod", value = "y", a:c) %>%
        nest(-prod) %>%
        mutate(m = map(data, prophet)) %>%
        mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
        mutate(forecast = map2(m, future, predict)) %>%
        mutate(p = map2(m, forecast, plot))

The output looks like this:

# A tibble: 3 x 6
  dept  data              m             future                forecast               p
  <chr> <list>            <list>        <list>                <list>                 <list>
1 a     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
2 b     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
3 c     <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>

Then, I create the plots manually, and rearrange them using grid.arrange

gridExtra::grid.arrange(d1$p[[1]], d1$p[[2]], d1$p[[3]]

Are there any ways to do it quicker and automatically?

Body:
I couldn't find a way to pipe the call to grid.arrange, but you can use do.call to avoid manually selecting plots.

do.call(gridExtra::grid.arrange, d1$p)

Example:

library(dplyr)
library(prophet)
library(tidyr)
library(purrr)

df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
                 a = rnorm(n = 25, mean = 100000, sd = 7500),
                 b = rnorm(n = 25, mean = 100000, sd = 7500),
                 c = rnorm(n = 25, mean = 100000, sd = 7500))

d1 <- df %>%
  gather(key = "prod", value = "y", a:c) %>%
  nest(-prod) %>%
  mutate(m = map(data, prophet)) %>%
  mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
  mutate(forecast = map2(m, future, predict)) %>%
  mutate(p = map2(m, forecast, plot))


问:
How to add JVM argument `-Dcom.ibm.mq.cfg.useIBMCipherMappings=false` to IBM MQ?
Recently I've been migrated to IBM MQ v8 to IBM MQ v9 (v9.1.2.0 specifically). I used SSL to communicate with the broker. So as per Deprecated CipherSpecs document, IBM has deprecated number of cipher suites that came up with MQ 8 and seems all of the cipher suites I've been using, have been deprecated with v9 upward. Therefore, I've implemented new TLS cipher suites to work with my application which runs on a Oracle JVM (version 1.8.0_211). Ever since I'm getting following exception in the application though;

```<code>com.ibm.mq.MQException: MQJE001: Completion Code '2', Reason '2400'.
    at com.ibm.mq.MQManagedConnectionJ11.constructMQCD(MQManagedConnectionJ11.java:1437)
    at com.ibm.mq.MQManagedConnectionJ11.constructCNO(MQManagedConnectionJ11.java:1537)
    at com.ibm.mq.MQManagedConnectionJ11.<init>(MQManagedConnectionJ11.java:221)
    ... (Omitted the rest)
</code>```

When I dig about the reason, found that's a problem with IBM MQ cipher suites and Oracle JRE cipher suite name mismatch. But I did refer TLS CipherSpecs and CipherSuites in IBM MQ classes for JMS document to map cipher suite names. I used some of Equivalent CipherSuite (Oracle JRE) column values in my application that already available in IBM MQ as well. But still getting the issue.

After I found this answer that advises to add this -Dcom.ibm.mq.cfg.useIBMCipherMappings=false argument to IBM MQ's JRE (As I understand). This might allow IBM MQ to use Oracle complied cipher suite names. My question is,

How to add this JVM argument -Dcom.ibm.mq.cfg.useIBMCipherMappings=false to IBM MQ JRE?

This Problem Connecting a Java Client (JMS) to a IBM MQ question suggests that the same parameter needed to be added to the application as a system property System.setProperty("com.ibm.mq.cfg.useIBMCipherMappings", "false"), but it didn't make any different.

Java connection to WMQ 8 question also states the same solution, but doesn't mention how to add this JVM argument to IBM MQ.

Update 1

I did some research about how to add a JVM argument to IBM MQ. But I was only able to find a solutions for Websphere application server.

CipherSuite I'm currently using in the application is;

TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (Oracle JRE complied)

IBM MQ has respective;

ECDHE_ECDSA_AES_128_CBC_SHA256 (IBM MQ complied)

Update 2

After creating a key.kdb file with ikeyman tool with the stash option queue manager can successfully read the certificates in it. Also, I've included a self-signed certificate labeled with ibmwebspheremq<lowercase_queue_manage_name>. But now I'm getting a different exception in the client side;

```<code>Exception in thread "main" com.ibm.mq.MQException: MQJE001: Completion Code '2', Reason '2059'.
    at com.ibm.mq.MQManagedConnectionJ11.<init>(MQManagedConnectionJ11.java:255)
    at com.ibm.mq.MQClientManagedConnectionFactoryJ11._createManagedConnection(MQClientManagedConnectionFactoryJ11.java:450)
    at com.ibm.mq.MQClientManagedConnectionFactoryJ11.createManagedConnection(MQClientManagedConnectionFactoryJ11.java:487)
    at com.ibm.mq.StoredManagedConnection.<init>(StoredManagedConnection.java:97)
</code>```

and in the MQ log I can find this entry;

```<code>AMQ9637E: Channel is lacking a certificate.
</code>```

with some explanation.

答:
Note: Adding answer to capture information provided to OP in comments that have been removed.

See the following IBM MQ Knowledge center page for a table showing cert type compatibility with MQ v9.1:

IBM MQ 9.1.x/IBM MQ/Securing/Confidentiality of messages/Enabling CipherSpecs

The ciphers with ECDHE_ECDSA require a suite b cert for the queue manager. If using a client cert for your application it will also need to be suite b.

Note that you can use ECDHE_RSA ciphers with non-suite b certs.

The stash file (key.sth for example) is used by the queue manager to access the kdb file. The java equivalent on the client end is you specifying the jks password.

Body:
Recently I've been migrated to IBM MQ v8 to IBM MQ v9 (v9.1.2.0 specifically). I used SSL to communicate with the broker. So as per Deprecated CipherSpecs document, IBM has deprecated number of cipher suites that came up with MQ 8 and seems all of the cipher suites I've been using, have been deprecated with v9 upward. Therefore, I've implemented new TLS cipher suites to work with my application which runs on a Oracle JVM (version 1.8.0_211). Ever since I'm getting following exception in the application though;

com.ibm.mq.MQException: MQJE001: Completion Code '2', Reason '2400'.
    at com.ibm.mq.MQManagedConnectionJ11.constructMQCD(MQManagedConnectionJ11.java:1437)
    at com.ibm.mq.MQManagedConnectionJ11.constructCNO(MQManagedConnectionJ11.java:1537)
    at com.ibm.mq.MQManagedConnectionJ11.<init>(MQManagedConnectionJ11.java:221)
    ... (Omitted the rest)

When I dig about the reason, found that's a problem with IBM MQ cipher suites and Oracle JRE cipher suite name mismatch. But I did refer TLS CipherSpecs and CipherSuites in IBM MQ classes for JMS document to map cipher suite names. I used some of Equivalent CipherSuite (Oracle JRE) column values in my application that already available in IBM MQ as well. But still getting the issue.

After I found this answer that advises to add this -Dcom.ibm.mq.cfg.useIBMCipherMappings=false argument to IBM MQ's JRE (As I understand). This might allow IBM MQ to use Oracle complied cipher suite names. My question is,

How to add this JVM argument -Dcom.ibm.mq.cfg.useIBMCipherMappings=false to IBM MQ JRE?

This Problem Connecting a Java Client (JMS) to a IBM MQ question suggests that the same parameter needed to be added to the application as a system property System.setProperty("com.ibm.mq.cfg.useIBMCipherMappings", "false"), but it didn't make any different.

Java connection to WMQ 8 question also states the same solution, but doesn't mention how to add this JVM argument to IBM MQ.

Update 1

I did some research about how to add a JVM argument to IBM MQ. But I was only able to find a solutions for Websphere application server.

CipherSuite I'm currently using in the application is;

TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (Oracle JRE complied)

IBM MQ has respective;

ECDHE_ECDSA_AES_128_CBC_SHA256 (IBM MQ complied)

Update 2

After creating a key.kdb file with ikeyman tool with the stash option queue manager can successfully read the certificates in it. Also, I've included a self-signed certificate labeled with ibmwebspheremq<lowercase_queue_manage_name>. But now I'm getting a different exception in the client side;

Exception in thread "main" com.ibm.mq.MQException: MQJE001: Completion Code '2', Reason '2059'.
    at com.ibm.mq.MQManagedConnectionJ11.<init>(MQManagedConnectionJ11.java:255)
    at com.ibm.mq.MQClientManagedConnectionFactoryJ11._createManagedConnection(MQClientManagedConnectionFactoryJ11.java:450)
    at com.ibm.mq.MQClientManagedConnectionFactoryJ11.createManagedConnection(MQClientManagedConnectionFactoryJ11.java:487)
    at com.ibm.mq.StoredManagedConnection.<init>(StoredManagedConnection.java:97)

and in the MQ log I can find this entry;

AMQ9637E: Channel is lacking a certificate.

with some explanation.


答:
You should make a copy the array first because sort() method modifies the original array. You can make the copy of the array using slice()

var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterSorted = letters.slice().sort();    //this line is changed
console.log(letterSorted);
console.log(lettersUnsorted);```

Title: create two differents variables from the same array


问:
A line graph for non-numeric data
I have a dataset with mostly non numeric forms. I would love to create a visualization for them but I am having an error message.

My data set looks like this

```<code> |plant_name|Customer_name|Job site|Delivery.Date|DeliveryQuantity|
 |SN13|John|Sweden|01.01.2019|6|
 |SN14|Ruth|France|01.04.2018|4|
 |SN15|Jane|Serbia|01.01.2019|2|
 |SN11|Rome|Denmark|01.04.2018|10|
 |SN14|John|Sweden|03.04.2018|5|
 |SN15|John|Sweden|04.09.2019|7|
 |
</code>```

I need to create a lineplot to show how many times John made a purchase using Delivery Date as my timeline (x-axis)

```<code>import  pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
pd.set_option("display.max_rows", 5)

hr_data = pd.read_excel("D:\data\Days_Calculation.xlsx", parse_dates = True)

x = hr_data['DeliveryDate']
y = hr_data ['Customer_name']

sns.lineplot(x,y)

Error: No numeric types to aggregate
</code>```

My expected result show be a line graph like this

John's marker will present on the timeline (Delivery Date) on "01.01.2019", "03.04.2018" and "04.09.2019"

Another instance
To plot string vs float for example Total number of quantity (DeliveryQuantity) vs Customer Name .How can one approach this

how do one format the axes distance of a plot  (not label)

答:
Why not make Delivery Date a timestamp object instead of a string?

```<code>hr_data["Delivery.Date"] = pd.to_datetime(hr_data["Delivery.Date"])
</code>```

Now you got plot options.

Working with John.

```<code>john_data = hr_data[hr_data["Customer_name"]=="John"]
sns.countplot(john_data["Delivery.Date"])
</code>```

Title: A line graph for non-numeric data

Body:
I have a dataset with mostly non numeric forms. I would love to create a visualization for them but I am having an error message.

My data set looks like this

 |plant_name|Customer_name|Job site|Delivery.Date|DeliveryQuantity|
 |SN13|John|Sweden|01.01.2019|6|
 |SN14|Ruth|France|01.04.2018|4|
 |SN15|Jane|Serbia|01.01.2019|2|
 |SN11|Rome|Denmark|01.04.2018|10|
 |SN14|John|Sweden|03.04.2018|5|
 |SN15|John|Sweden|04.09.2019|7|
 |

I need to create a lineplot to show how many times John made a purchase using Delivery Date as my timeline (x-axis)

import  pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
pd.set_option("display.max_rows", 5)

hr_data = pd.read_excel("D:\data\Days_Calculation.xlsx", parse_dates = True)

x = hr_data['DeliveryDate']
y = hr_data ['Customer_name']

sns.lineplot(x,y)

Error: No numeric types to aggregate

My expected result show be a line graph like this

John's marker will present on the timeline (Delivery Date) on "01.01.2019", "03.04.2018" and "04.09.2019"

Another instance
To plot string vs float for example Total number of quantity (DeliveryQuantity) vs Customer Name .How can one approach this

how do one format the axes distance of a plot  (not label)

Body:
Why not make Delivery Date a timestamp object instead of a string?

hr_data["Delivery.Date"] = pd.to_datetime(hr_data["Delivery.Date"])

Now you got plot options.

Working with John.

john_data = hr_data[hr_data["Customer_name"]=="John"]
sns.countplot(john_data["Delivery.Date"])


问:
Ethereum address and port on local host
I've geth node running on my local and I need to find out http url and ethereum url to deploy dapp on Mix IDE. Can any one please help and tell where to find these two parameters ?</p>

答:
If you are in default mode probably one of those ports:

8545 TCP, used by the HTTP based JSON RPC API

8546 TCP, used by the WebSocket based JSON RPC API

Are you connecting through JSON RPC API?

```<code>$ geth attach ipc:/some/custom/path
$ geth attach http://191.168.1.1:8545
$ geth attach ws://191.168.1.1:8546
</code>```

Note that by default the geth node doesn't start the http and weboscket service and not all functionality is provided over these interfaces due to security reasons. These defaults can be overridden when the --rpcapi and --wsapi arguments when the geth node is started.

Title: Ethereum address and port on local host

Body:
If you are in default mode probably one of those ports:

8545 TCP, used by the HTTP based JSON RPC API

8546 TCP, used by the WebSocket based JSON RPC API

Are you connecting through JSON RPC API?

$ geth attach ipc:/some/custom/path
$ geth attach http://191.168.1.1:8545
$ geth attach ws://191.168.1.1:8546

Note that by default the geth node doesn't start the http and weboscket service and not all functionality is provided over these interfaces due to security reasons. These defaults can be overridden when the --rpcapi and --wsapi arguments when the geth node is started.


问:
Upload Binary Content with Tink Web
I want to upload an arrayBuffer from my javascript client, but i can't figure out how to define my Route

I tried the @:consumes metadata with application/octet-stream MimeType but the compiler doesn't like it.

```<code>class Api {

    public function new() { }

    @:post('/upload')
    @:consumes("application/octet-stream")
    public function upload(data:ArrayBuffer){
        trace(data);
    }

}
</code>```

src/server/Api.hx:17: lines 17-19 : Warning : All defined routes are incomplete
src/server/Api.hx:15: characters 9-18 : Warning : Route does not capture argumentdata

答:
I suspect that ArrayBuffer can't be created from the body stream? What if you changed it to just a https://api.haxe.org/haxe/io/Bytes.html?

Edit:
The docs (https://haxetink.github.io/tink_web/#/basics/parameters?id=advanced-data-types) mentions that parsers only exist for application/json and form-urlencoded mime types. an octet-stream parser doesn't exist (https://github.com/haxetink/tink_web/blob/master/src/tink/web/macros/MimeType.hx). you can probably write one, and parse the bytes into a Bytes object quite easily.

Title: Upload Binary Content with Tink Web

Body:
I want to upload an arrayBuffer from my javascript client, but i can't figure out how to define my Route

I tried the @:consumes metadata with application/octet-stream MimeType but the compiler doesn't like it.

class Api {

    public function new() { }

    @:post('/upload')
    @:consumes("application/octet-stream")
    public function upload(data:ArrayBuffer){
        trace(data);
    }

}

src/server/Api.hx:17: lines 17-19 : Warning : All defined routes are incomplete
src/server/Api.hx:15: characters 9-18 : Warning : Route does not capture argumentdata


问:
How can i restrict to delete only one document at a time in firestore using security Rule?
I have a collection called 'customers' and i have allowed read and write permissions to that collection to some users.My requirement is i have to restrict the delete operation only to one document at a time,to avoid mass deletion of the collection.How can i achieve this using firestore security rule.?Right now i have tried with the below code

```<code>match /customers/{customer=**} {

    function isSignedIn() {
      return request.auth != null;
    }

    function isRole(roles) {
        return get(/databases/$(database)/documents/Teachers/$(request.auth.uid)).data.permissions.pages.hasAny(roles);
        }

    function isSize(size){
      return request.resource.data.size()==size;
    }

    allow read: if isSignedIn()&&isRole(['create','modify']);
    allow create,update:if isSignedIn()&&isRole(['create','modify']);;
    allow delete:if isSignedIn()&&isSize(1)

 }
</code>```

Here is the code to delete operation;

```<code>async(id:string){

  const batch=afs.firestore.batch();
  const coll=await afs.firestore.collection('customers').ref.limit(1).where('id','==',id).get();
  for(const i of coll.docs){
   const ref= await afs.firestore.collection('customers').doc(i.id);
   await batch.delete(ref);
  }
  return await batch.commit();

}
</code>```

but the above rule always returning permission denied while making a delete operation.

答:
This is currently not possible.  Firebase security rules doesn't provide any way to limit the rate or volume of any operation.  There is also no way to detect if the current operation is a part of a batch or transaction.

Even if there was a way to detect if there is a batch operation, the user could still call delete() repeatedly to achieve the same effect.

Instead, you could experiment with sending client requests through Cloud Functions, which could try to record requests to delete documents, and reject the request if it exceeds some limit you define.  The documents would have to be fully unwritable by security rules, while they would still be accessible to the Admin or server SDK you use in Cloud Functions.

Body:
I have a collection called 'customers' and i have allowed read and write permissions to that collection to some users.My requirement is i have to restrict the delete operation only to one document at a time,to avoid mass deletion of the collection.How can i achieve this using firestore security rule.?Right now i have tried with the below code

match /customers/{customer=**} {

    function isSignedIn() {
      return request.auth != null;
    }

    function isRole(roles) {
        return get(/databases/$(database)/documents/Teachers/$(request.auth.uid)).data.permissions.pages.hasAny(roles);
        }

    function isSize(size){
      return request.resource.data.size()==size;
    }

    allow read: if isSignedIn()&&isRole(['create','modify']);
    allow create,update:if isSignedIn()&&isRole(['create','modify']);;
    allow delete:if isSignedIn()&&isSize(1)

 }

Here is the code to delete operation;

async(id:string){

  const batch=afs.firestore.batch();
  const coll=await afs.firestore.collection('customers').ref.limit(1).where('id','==',id).get();
  for(const i of coll.docs){
   const ref= await afs.firestore.collection('customers').doc(i.id);
   await batch.delete(ref);
  }
  return await batch.commit();

}

but the above rule always returning permission denied while making a delete operation.


问:
Disposing a singleton instance shared between NUnit tests
I have a bunch of NUnit acceptance tests (that is, not unit tests) that need to connect to several Redis instances during the course of the execution.

StackExchange.Redis best practices advise to store and reuse the ConnectionMultiplexer instances (see here: https://stackexchange.github.io/StackExchange.Redis/Basics), so I came up with this singleton that allows to re-use a ConnectionMultiplexer object:

```<code>internal static class RedisConnectionCache
{
    // concurrency locks omitted for simplicity
    private static readonly Dictionary<string, IConnectionMultiplexer> ConnectionCache = new Dictionary<string, IConnectionMultiplexer>();
    public static IConnectionMultiplexer GetMultiplexer(string connectionString)
    {
        if (ConnectionCache.TryGetValue(connectionString, out var multiplexer))
        {
            return multiplexer;
        }

        var multiplexer= ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(connectionString));
        ConnectionCache.Add(connectionString, multiplexer);

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

Which is then invoked like this in many tests:

```<code>var redisConnection = RedisConnectionCache.GetMultiplexer(connectionString);
var redisDb = redisConnection.GetDatabase(db);
redisDb.KeyDelete(key);
</code>```

Unfortunately, since this is all happening inside many different NUnit test fixtures, I don't have a good way to dispose my dictionary of Redis connections.

Provided that I need to reuse the connection objects between different test fixtures inside the same test run, what are my options?
So far, the best I can think of is OneTimeTearDown test that would empty the connections after all tests are done.

答:
Setup Fixture does the trick here. One caveat is that I needed to put the class outside of the test namespaces to run after any tests in the assembly.

In a generic fashion, my code ended up being similar to this:

```<code>using NUnit.Framework;
// ReSharper disable CheckNamespace

[SetUpFixture]
public class SingletonTeardown
{
    [OneTimeTearDown]
    public void RunAfter()
    {
        if (SingletonType.Instance.IsValueCreated)
        {
            SingletonType.Instance.Value.Dispose();
        }
    }
}
</code>```

Body:
I have a bunch of NUnit acceptance tests (that is, not unit tests) that need to connect to several Redis instances during the course of the execution.

StackExchange.Redis best practices advise to store and reuse the ConnectionMultiplexer instances (see here: https://stackexchange.github.io/StackExchange.Redis/Basics), so I came up with this singleton that allows to re-use a ConnectionMultiplexer object:

internal static class RedisConnectionCache
{
    // concurrency locks omitted for simplicity
    private static readonly Dictionary<string, IConnectionMultiplexer> ConnectionCache = new Dictionary<string, IConnectionMultiplexer>();
    public static IConnectionMultiplexer GetMultiplexer(string connectionString)
    {
        if (ConnectionCache.TryGetValue(connectionString, out var multiplexer))
        {
            return multiplexer;
        }

        var multiplexer= ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(connectionString));
        ConnectionCache.Add(connectionString, multiplexer);

        return multiplexer;
    }
}

Which is then invoked like this in many tests:

var redisConnection = RedisConnectionCache.GetMultiplexer(connectionString);
var redisDb = redisConnection.GetDatabase(db);
redisDb.KeyDelete(key);

Unfortunately, since this is all happening inside many different NUnit test fixtures, I don't have a good way to dispose my dictionary of Redis connections.

Provided that I need to reuse the connection objects between different test fixtures inside the same test run, what are my options?
So far, the best I can think of is OneTimeTearDown test that would empty the connections after all tests are done.

Body:
Setup Fixture does the trick here. One caveat is that I needed to put the class outside of the test namespaces to run after any tests in the assembly.

In a generic fashion, my code ended up being similar to this:

using NUnit.Framework;
// ReSharper disable CheckNamespace

[SetUpFixture]
public class SingletonTeardown
{
    [OneTimeTearDown]
    public void RunAfter()
    {
        if (SingletonType.Instance.IsValueCreated)
        {
            SingletonType.Instance.Value.Dispose();
        }
    }
}


问:
How can I determine if the query is working?
I can't see if there's an error because the application is not prompting anything. I want to get a value from the database and put it inside a variable to be displayed later when I need it.

I'm fairly new to programming, I've tried to watch tutorials, but I just can't seem to get how some things are properly done since tutors have their own approach on doing stuff.

public void selectQuery(String input) throws SQLException {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String USERNAME = "root";
        String PASSWORD = "root";
        String CONN_STRING =
            "jdbc:mysql://localhost:3306/javaddy?serverTimezone=UTC";
        Connection connection =
            DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);

        try {
            String q = "SELECT Inquiry_answer,Inquiry_question FROM inquiries WHERE Inquiry_question = '" + input + "'";
            Statement stmt = connection.createStatement();
            ResultSet res = stmt.executeQuery(q);
            String answer;
            answer = res.getString("Inquiry_answer");
            // /* there is no value returned here (I think) because after passing to
            // bot method, it doesn't print anything */
            bot(answer);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    } catch (ClassNotFoundException e) {
        System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {
        System.out.println("Could not connect to the database " + e.getMessage());
    }
}
```

I expect to receive a value from the database but there is none returned.

答:
Without doing resultset.next() you can not get result.

Correct way of doing it:

```<code>                ResultSet res = stmt.executeQuery(q);
                String answer;
                res.next();
                answer = res.getString("Inquiry_answer");
                // /* there is no value returned here (I think) because after passing to
                // bot method, it doesn't print anything */
                bot(answer);
</code>```

or still better way to put this code in loop like:

```<code>while (res.next())
{
  String answer = res.getString("Inquiry_answer");
  System.out.println(answer);
}
</code>```

I suppose bot method prints string.

Body:
I can't see if there's an error because the application is not prompting anything. I want to get a value from the database and put it inside a variable to be displayed later when I need it.

I'm fairly new to programming, I've tried to watch tutorials, but I just can't seem to get how some things are properly done since tutors have their own approach on doing stuff.

public void selectQuery(String input) throws SQLException {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String USERNAME = "root";
        String PASSWORD = "root";
        String CONN_STRING =
            "jdbc:mysql://localhost:3306/javaddy?serverTimezone=UTC";
        Connection connection =
            DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);

        try {
            String q = "SELECT Inquiry_answer,Inquiry_question FROM inquiries WHERE Inquiry_question = '" + input + "'";
            Statement stmt = connection.createStatement();
            ResultSet res = stmt.executeQuery(q);
            String answer;
            answer = res.getString("Inquiry_answer");
            // /* there is no value returned here (I think) because after passing to
            // bot method, it doesn't print anything */
            bot(answer);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    } catch (ClassNotFoundException e) {
        System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {
        System.out.println("Could not connect to the database " + e.getMessage());
    }
}

I expect to receive a value from the database but there is none returned.

Body:
Without doing resultset.next() you can not get result.

Correct way of doing it:

                ResultSet res = stmt.executeQuery(q);
                String answer;
                res.next();
                answer = res.getString("Inquiry_answer");
                // /* there is no value returned here (I think) because after passing to
                // bot method, it doesn't print anything */
                bot(answer);

or still better way to put this code in loop like:

while (res.next())
{
  String answer = res.getString("Inquiry_answer");
  System.out.println(answer);
}

I suppose bot method prints string.